SendEmail搭配使用 AWS SDK - Amazon Simple Email Service

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

SendEmail搭配使用 AWS SDK

以下代码示例演示如何使用 SendEmail

.NET
AWS SDK for .NET
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

/// <summary> /// Sends an email with the specified content and options. /// </summary> /// <param name="fromEmailAddress">The email address to send the email from.</param> /// <param name="toEmailAddresses">The email addresses to send the email to.</param> /// <param name="subject">The subject of the email.</param> /// <param name="htmlContent">The HTML content of the email.</param> /// <param name="textContent">The text content of the email.</param> /// <param name="templateName">The name of the email template to use (optional).</param> /// <param name="templateData">The data to replace placeholders in the email template (optional).</param> /// <param name="contactListName">The name of the contact list for unsubscribe functionality (optional).</param> /// <returns>The MessageId response from the SendEmail operation.</returns> public async Task<string> SendEmailAsync(string fromEmailAddress, List<string> toEmailAddresses, string? subject, string? htmlContent, string? textContent, string? templateName = null, string? templateData = null, string? contactListName = null) { var request = new SendEmailRequest { FromEmailAddress = fromEmailAddress }; if (toEmailAddresses.Any()) { request.Destination = new Destination { ToAddresses = toEmailAddresses }; } if (!string.IsNullOrEmpty(templateName)) { request.Content = new EmailContent() { Template = new Template { TemplateName = templateName, TemplateData = templateData } }; } else { request.Content = new EmailContent { Simple = new Message { Subject = new Content { Data = subject }, Body = new Body { Html = new Content { Data = htmlContent }, Text = new Content { Data = textContent } } } }; } if (!string.IsNullOrEmpty(contactListName)) { request.ListManagementOptions = new ListManagementOptions { ContactListName = contactListName }; } try { var response = await _sesClient.SendEmailAsync(request); return response.MessageId; } catch (AccountSuspendedException ex) { Console.WriteLine("The account's ability to send email has been permanently restricted."); Console.WriteLine(ex.Message); } catch (MailFromDomainNotVerifiedException ex) { Console.WriteLine("The sending domain is not verified."); Console.WriteLine(ex.Message); } catch (MessageRejectedException ex) { Console.WriteLine("The message content is invalid."); Console.WriteLine(ex.Message); } catch (SendingPausedException ex) { Console.WriteLine("The account's ability to send email is currently paused."); 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 sending the email: {ex.Message}"); } return string.Empty; }
  • 有关API详细信息,请参阅 “AWS SDK for .NET API参考 SendEmail” 中的。

Java
SDK适用于 Java 2.x
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

发送邮件。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sesv2.model.Body; import software.amazon.awssdk.services.sesv2.model.Content; import software.amazon.awssdk.services.sesv2.model.Destination; import software.amazon.awssdk.services.sesv2.model.EmailContent; import software.amazon.awssdk.services.sesv2.model.Message; import software.amazon.awssdk.services.sesv2.model.SendEmailRequest; import software.amazon.awssdk.services.sesv2.model.SesV2Exception; import software.amazon.awssdk.services.sesv2.SesV2Client; /** * Before running this AWS SDK for Java (v2) example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class SendEmail { public static void main(String[] args) { final String usage = """ Usage: <sender> <recipient> <subject>\s Where: sender - An email address that represents the sender.\s recipient - An email address that represents the recipient.\s subject - The subject line.\s """; if (args.length != 3) { System.out.println(usage); System.exit(1); } String sender = args[0]; String recipient = args[1]; String subject = args[2]; Region region = Region.US_EAST_1; SesV2Client sesv2Client = SesV2Client.builder() .region(region) .build(); // The HTML body of the email. String bodyHTML = "<html>" + "<head></head>" + "<body>" + "<h1>Hello!</h1>" + "<p> See the list of customers.</p>" + "</body>" + "</html>"; send(sesv2Client, sender, recipient, subject, bodyHTML); } public static void send(SesV2Client client, String sender, String recipient, String subject, String bodyHTML) { Destination destination = Destination.builder() .toAddresses(recipient) .build(); Content content = Content.builder() .data(bodyHTML) .build(); Content sub = Content.builder() .data(subject) .build(); Body body = Body.builder() .html(content) .build(); Message msg = Message.builder() .subject(sub) .body(body) .build(); EmailContent emailContent = EmailContent.builder() .simple(msg) .build(); SendEmailRequest emailRequest = SendEmailRequest.builder() .destination(destination) .content(emailContent) .fromEmailAddress(sender) .build(); try { System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java..."); client.sendEmail(emailRequest); System.out.println("email was sent"); } catch (SesV2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }

使用模板发送消息。

String coupons = Files.readString(Paths.get("resources/coupon_newsletter/sample_coupons.json")); for (String emailAddress : contactEmails) { SendEmailRequest newsletterRequest = SendEmailRequest.builder() .destination(Destination.builder().toAddresses(emailAddress).build()) .content(EmailContent.builder() .template(Template.builder() .templateName(TEMPLATE_NAME) .templateData(coupons) .build()) .build()) .fromEmailAddress(this.verifiedEmail) .listManagementOptions(ListManagementOptions.builder() .contactListName(CONTACT_LIST_NAME) .build()) .build(); SendEmailResponse newsletterResponse = sesClient.sendEmail(newsletterRequest); System.out.println("Newsletter sent to " + emailAddress + ": " + newsletterResponse.messageId()); }
  • 有关API详细信息,请参阅 “AWS SDK for Java 2.x API参考 SendEmail” 中的。

Python
SDK适用于 Python (Boto3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 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 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}'.")

使用模板向联系人列表中的所有成员发送消息。

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 self.ses_client.send_email( FromEmailAddress=self.verified_email, Destination={"ToAddresses": [email_address]}, Content={ "Template": { "TemplateName": TEMPLATE_NAME, "TemplateData": coupon_items, } }, ListManagementOptions={"ContactListName": CONTACT_LIST_NAME}, )
  • 有关API详细信息,请参阅SendEmail中的 AWS SDKPython (Boto3) API 参考。

Ruby
SDK对于 Ruby
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

require 'aws-sdk-sesv2' require_relative 'config' # Recipient and sender email addresses. # Set up the SESv2 client. client = Aws::SESV2::Client.new(region: AWS_REGION) def send_email(client, sender_email, recipient_email) response = client.send_email( { from_email_address: sender_email, destination: { to_addresses: [recipient_email] }, content: { simple: { subject: { data: 'Test email subject' }, body: { text: { data: 'Test email body' } } } } } ) puts "Email sent from #{SENDER_EMAIL} to #{RECIPIENT_EMAIL} with message ID: #{response.message_id}" end send_email(client, SENDER_EMAIL, RECIPIENT_EMAIL)
  • 有关API详细信息,请参阅 “AWS SDK for Ruby API参考 SendEmail” 中的。

Rust
SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

向联系人列表中的所有成员发送消息。

async fn send_message( client: &Client, list: &str, from: &str, subject: &str, message: &str, ) -> Result<(), Error> { // Get list of email addresses from contact list. let resp = client .list_contacts() .contact_list_name(list) .send() .await?; let contacts = resp.contacts(); let cs: Vec<String> = contacts .iter() .map(|i| i.email_address().unwrap_or_default().to_string()) .collect(); let mut dest: Destination = Destination::builder().build(); dest.to_addresses = Some(cs); let subject_content = Content::builder() .data(subject) .charset("UTF-8") .build() .expect("building Content"); let body_content = Content::builder() .data(message) .charset("UTF-8") .build() .expect("building Content"); let body = Body::builder().text(body_content).build(); let msg = Message::builder() .subject(subject_content) .body(body) .build(); let email_content = EmailContent::builder().simple(msg).build(); client .send_email() .from_email_address(from) .destination(dest) .content(email_content) .send() .await?; println!("Email sent to list"); Ok(()) }

使用模板向联系人列表中的所有成员发送消息。

let coupons = std::fs::read_to_string("../resources/newsletter/sample_coupons.json") .unwrap_or_else(|_| r#"{"coupons":[]}"#.to_string()); let email_content = EmailContent::builder() .template( Template::builder() .template_name(TEMPLATE_NAME) .template_data(coupons) .build(), ) .build(); match self .client .send_email() .from_email_address(self.verified_email.clone()) .destination(Destination::builder().to_addresses(email.clone()).build()) .content(email_content) .list_management_options( ListManagementOptions::builder() .contact_list_name(CONTACT_LIST_NAME) .build()?, ) .send() .await { Ok(output) => { if let Some(message_id) = output.message_id { writeln!( self.stdout, "Newsletter sent to {} with message ID {}", email, message_id )?; } else { writeln!(self.stdout, "Newsletter sent to {}", email)?; } } Err(e) => return Err(anyhow!("Error sending newsletter to {}: {}", email, e)), }
  • 有关API详细信息,请参见SendEmail中的 Rust AWS SDK API 参考

有关 AWS SDK开发者指南和代码示例的完整列表,请参阅将 Amazon SES 与 AWS SDK。本主题还包括有关入门的信息以及有关先前SDK版本的详细信息。