Use CreateContact com um AWS SDK ou CLI - AWS SDKExemplos de código

Há mais AWS SDK exemplos disponíveis no GitHub repositório AWS Doc SDK Examples.

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Use CreateContact com um AWS SDK ou CLI

Os exemplos de código a seguir mostram como usar o CreateContact.

Exemplos de ações são trechos de código de programas maiores e devem ser executados em contexto. É possível ver essa ação no contexto no seguinte exemplo de código:

.NET
AWS SDK for .NET
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

/// <summary> /// Creates a contact and adds it to the specified contact list. /// </summary> /// <param name="emailAddress">The email address of the contact.</param> /// <param name="contactListName">The name of the contact list.</param> /// <returns>The response from the CreateContact operation.</returns> public async Task<bool> CreateContactAsync(string emailAddress, string contactListName) { var request = new CreateContactRequest { EmailAddress = emailAddress, ContactListName = contactListName }; try { var response = await _sesClient.CreateContactAsync(request); return response.HttpStatusCode == HttpStatusCode.OK; } catch (AlreadyExistsException ex) { Console.WriteLine($"Contact with email address {emailAddress} already exists in the contact list {contactListName}."); Console.WriteLine(ex.Message); return true; } catch (NotFoundException ex) { Console.WriteLine($"The contact list {contactListName} does not exist."); Console.WriteLine(ex.Message); } catch (TooManyRequestsException ex) { Console.WriteLine("Too many requests were made. Please try again later."); Console.WriteLine(ex.Message); } catch (Exception ex) { Console.WriteLine($"An error occurred while creating the contact: {ex.Message}"); } return false; }
  • Para API obter detalhes, consulte CreateContactem AWS SDK for .NET APIReferência.

Java
SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

try { // Create a new contact with the provided email address in the CreateContactRequest contactRequest = CreateContactRequest.builder() .contactListName(CONTACT_LIST_NAME) .emailAddress(emailAddress) .build(); sesClient.createContact(contactRequest); contacts.add(emailAddress); System.out.println("Contact created: " + emailAddress); // Send a welcome email to the new contact String welcomeHtml = Files.readString(Paths.get("resources/coupon_newsletter/welcome.html")); String welcomeText = Files.readString(Paths.get("resources/coupon_newsletter/welcome.txt")); SendEmailRequest welcomeEmailRequest = SendEmailRequest.builder() .fromEmailAddress(this.verifiedEmail) .destination(Destination.builder().toAddresses(emailAddress).build()) .content(EmailContent.builder() .simple( Message.builder() .subject(Content.builder().data("Welcome to the Weekly Coupons Newsletter").build()) .body(Body.builder() .text(Content.builder().data(welcomeText).build()) .html(Content.builder().data(welcomeHtml).build()) .build()) .build()) .build()) .build(); SendEmailResponse welcomeEmailResponse = sesClient.sendEmail(welcomeEmailRequest); System.out.println("Welcome email sent: " + welcomeEmailResponse.messageId()); } catch (AlreadyExistsException e) { // If the contact already exists, skip this step for that contact and proceed // with the next contact System.out.println("Contact already exists, skipping creation..."); } catch (Exception e) { System.err.println("Error occurred while processing email address " + emailAddress + ": " + e.getMessage()); throw e; } }
  • Para API obter detalhes, consulte CreateContactem AWS SDK for Java 2.x APIReferência.

Python
SDKpara Python (Boto3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

def main(): """ The main function that orchestrates the execution of the workflow. """ print(INTRO) ses_client = boto3.client("sesv2") workflow = SESv2Workflow(ses_client) try: workflow.prepare_application() workflow.gather_subscriber_email_addresses() workflow.send_coupon_newsletter() workflow.monitor_and_review() except ClientError as e: print_error(e) workflow.clean_up() class SESv2Workflow: """ A class to manage the SES v2 Coupon Newsletter Workflow. """ def __init__(self, ses_client, sleep=True): self.ses_client = ses_client self.sleep = sleep try: # Create a new contact self.ses_client.create_contact( ContactListName=CONTACT_LIST_NAME, EmailAddress=email ) print(f"Contact with email '{email}' created successfully.") # Send the welcome email self.ses_client.send_email( FromEmailAddress=self.verified_email, Destination={"ToAddresses": [email]}, Content={ "Simple": { "Subject": { "Data": "Welcome to the Weekly Coupons Newsletter" }, "Body": { "Text": {"Data": welcome_text}, "Html": {"Data": welcome_html}, }, } }, ) print(f"Welcome email sent to '{email}'.") if self.sleep: # 1 email per second in sandbox mode, remove in production. sleep(1.1) except ClientError as e: # If the contact already exists, skip and proceed if e.response["Error"]["Code"] == "AlreadyExistsException": print(f"Contact with email '{email}' already exists. Skipping...") else: raise e
  • Para API obter detalhes, consulte a CreateContactReferência AWS SDK do Python (Boto3). API

Rust
SDKpara Rust
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

async fn add_contact(client: &Client, list: &str, email: &str) -> Result<(), Error> { client .create_contact() .contact_list_name(list) .email_address(email) .send() .await?; println!("Created contact"); Ok(()) }
  • Para API obter detalhes, consulte CreateContacta AWS SDKAPIreferência do Rust.