CreateContactÚselo con un AWS SDK o CLI - AWS SDKEjemplos de código

Hay más AWS SDK ejemplos disponibles en el GitHub repositorio de AWS Doc SDK Examples.

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

CreateContactÚselo con un AWS SDK o CLI

En los siguientes ejemplos de código, se muestra cómo utilizar CreateContact.

Los ejemplos de acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Puede ver esta acción en contexto en el siguiente ejemplo de código:

.NET
AWS SDK for .NET
nota

Hay más en marcha GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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 obtener más información, consulte CreateContactla AWS SDK for .NET APIReferencia.

Java
SDKpara Java 2.x
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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 obtener más información, consulte CreateContactla AWS SDK for Java 2.x APIReferencia.

Python
SDKpara Python (Boto3)
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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 obtener más información, consulte CreateContactla AWS SDKreferencia de Python (Boto3). API

Rust
SDKpara Rust
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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 obtener más información, consulte CreateContactla APIreferencia AWS SDK de Rust.