Use CreateEmailTemplate 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 CreateEmailTemplate com um AWS SDK ou CLI

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

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 an email template with the specified content. /// </summary> /// <param name="templateName">The name of the email template.</param> /// <param name="subject">The subject of the email template.</param> /// <param name="htmlContent">The HTML content of the email template.</param> /// <param name="textContent">The text content of the email template.</param> /// <returns>True if successful.</returns> public async Task<bool> CreateEmailTemplateAsync(string templateName, string subject, string htmlContent, string textContent) { var request = new CreateEmailTemplateRequest { TemplateName = templateName, TemplateContent = new EmailTemplateContent { Subject = subject, Html = htmlContent, Text = textContent } }; try { var response = await _sesClient.CreateEmailTemplateAsync(request); return response.HttpStatusCode == HttpStatusCode.OK; } catch (AlreadyExistsException ex) { Console.WriteLine($"Email template with name {templateName} already exists."); Console.WriteLine(ex.Message); } catch (LimitExceededException ex) { Console.WriteLine("The limit for email templates has been exceeded."); 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 email template: {ex.Message}"); } return false; }
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 an email template named "weekly-coupons" String newsletterHtml = loadFile("resources/coupon_newsletter/coupon-newsletter.html"); String newsletterText = loadFile("resources/coupon_newsletter/coupon-newsletter.txt"); CreateEmailTemplateRequest templateRequest = CreateEmailTemplateRequest.builder() .templateName(TEMPLATE_NAME) .templateContent(EmailTemplateContent.builder() .subject("Weekly Coupons Newsletter") .html(newsletterHtml) .text(newsletterText) .build()) .build(); sesClient.createEmailTemplate(templateRequest); System.out.println("Email template created: " + TEMPLATE_NAME); } catch (AlreadyExistsException e) { // If the template already exists, skip this step and proceed with the next // operation System.out.println("Email template already exists, skipping creation..."); } catch (LimitExceededException e) { // If the limit for email templates is exceeded, fail the workflow and inform // the user System.err.println("You have reached the limit for email templates. Please remove some templates and try again."); throw e; } catch (Exception e) { System.err.println("Error occurred while creating email template: " + e.getMessage()); throw e; }
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: template_content = { "Subject": "Weekly Coupons Newsletter", "Html": load_file_content("coupon-newsletter.html"), "Text": load_file_content("coupon-newsletter.txt"), } self.ses_client.create_email_template( TemplateName=TEMPLATE_NAME, TemplateContent=template_content ) print(f"Email template '{TEMPLATE_NAME}' created successfully.") except ClientError as e: # If the template already exists, skip and proceed if e.response["Error"]["Code"] == "AlreadyExistsException": print(f"Email template '{TEMPLATE_NAME}' already exists.") else: raise e
  • Para API obter detalhes, consulte a CreateEmailTemplateReferê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.

let template_html = std::fs::read_to_string("../resources/newsletter/coupon-newsletter.html") .unwrap_or_else(|_| "Missing coupon-newsletter.html".to_string()); let template_text = std::fs::read_to_string("../resources/newsletter/coupon-newsletter.txt") .unwrap_or_else(|_| "Missing coupon-newsletter.txt".to_string()); // Create the email template let template_content = EmailTemplateContent::builder() .subject("Weekly Coupons Newsletter") .html(template_html) .text(template_text) .build(); match self .client .create_email_template() .template_name(TEMPLATE_NAME) .template_content(template_content) .send() .await { Ok(_) => writeln!(self.stdout, "Email template created successfully.")?, Err(e) => match e.into_service_error() { CreateEmailTemplateError::AlreadyExistsException(_) => { writeln!( self.stdout, "Email template already exists, skipping creation." )?; } e => return Err(anyhow!("Error creating email template: {}", e)), }, }