使用 AWS 软件开发工具包发送原始电子邮件 - Amazon Simple Email Service

如果我们为英文版本指南提供翻译,那么如果存在任何冲突,将以英文版本指南为准。在提供翻译时使用机器翻译。

使用 AWS 软件开发工具包发送原始电子邮件

AWS 开发工具包包含与 Amazon SES 以及多个其他 AWS 服务交互的内置方法。如果计划使用 Amazon SES 以及其他 AWS 服务,建议使用开发工具包。要了解有关 AWS 开发工具包的更多信息,请参阅适用于 Amazon Web Services 的工具

本节提供以多种编程语言表示的代码示例,这些代码示例介绍使用 AWS 开发工具包通过 Amazon SES 发送原始电子邮件的过程。

Java

下面的代码示例介绍如何使用 JavaMail 库和 AWS SDK for Java 编写和发送包含 HTML 部分、文本部分和附件的原始电子邮件。

此代码示例假定您已安装 AWS SDK for Java,并且您已创建共享凭证文件。有关创建共享凭证文件的更多信息,请参阅创建共享凭证文件

重要

可使用共享凭证文件来传递 AWS 访问密钥 ID 和秘密访问密钥。作为使用共享凭证文件的替代方案,您可以通过设置两个环境变量(分别为 AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEY)来指定 AWS 访问密钥 ID 和秘密访问密钥。除非您使用下列方法之一指定凭证,否则此示例无法正常运行。

package com.amazonaws.samples; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.nio.ByteBuffer; import java.util.Properties; // JavaMail libraries. Download the JavaMail API // from https://javaee.github.io/javamail/ import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; // AWS SDK libraries. Download the AWS SDK for Java // from https://aws.amazon.com/sdk-for-java import com.amazonaws.regions.Regions; import com.amazonaws.services.simpleemail.AmazonSimpleEmailService; import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder; import com.amazonaws.services.simpleemail.model.RawMessage; import com.amazonaws.services.simpleemail.model.SendRawEmailRequest; public class AmazonSESSample { // Replace sender@example.com with your "From" address. // This address must be verified with Amazon SES. private static String SENDER = "Sender Name <sender@example.com>"; // Replace recipient@example.com with a "To" address. If your account // is still in the sandbox, this address must be verified. private static String RECIPIENT = "recipient@example.com"; // Specify a configuration set. If you do not want to use a configuration // set, comment the following variable, and the // ConfigurationSetName=CONFIGURATION_SET argument below. private static String CONFIGURATION_SET = "ConfigSet"; // The subject line for the email. private static String SUBJECT = "Customer service contact info"; // The full path to the file that will be attached to the email. // If you're using Windows, escape backslashes as shown in this variable. private static String ATTACHMENT = "C:\\Users\\sender\\customers-to-contact.xlsx"; // The email body for recipients with non-HTML email clients. private static String BODY_TEXT = "Hello,\r\n" + "Please see the attached file for a list " + "of customers to contact."; // The HTML body of the email. private static String BODY_HTML = "<html>" + "<head></head>" + "<body>" + "<h1>Hello!</h1>" + "<p>Please see the attached file for a " + "list of customers to contact.</p>" + "</body>" + "</html>"; public static void main(String[] args) throws AddressException, MessagingException, IOException { Session session = Session.getDefaultInstance(new Properties()); // Create a new MimeMessage object. MimeMessage message = new MimeMessage(session); // Add subject, from and to lines. message.setSubject(SUBJECT, "UTF-8"); message.setFrom(new InternetAddress(SENDER)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(RECIPIENT)); // Create a multipart/alternative child container. MimeMultipart msg_body = new MimeMultipart("alternative"); // Create a wrapper for the HTML and text parts. MimeBodyPart wrap = new MimeBodyPart(); // Define the text part. MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent(BODY_TEXT, "text/plain; charset=UTF-8"); // Define the HTML part. MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(BODY_HTML,"text/html; charset=UTF-8"); // Add the text and HTML parts to the child container. msg_body.addBodyPart(textPart); msg_body.addBodyPart(htmlPart); // Add the child container to the wrapper object. wrap.setContent(msg_body); // Create a multipart/mixed parent container. MimeMultipart msg = new MimeMultipart("mixed"); // Add the parent container to the message. message.setContent(msg); // Add the multipart/alternative part to the message. msg.addBodyPart(wrap); // Define the attachment MimeBodyPart att = new MimeBodyPart(); DataSource fds = new FileDataSource(ATTACHMENT); att.setDataHandler(new DataHandler(fds)); att.setFileName(fds.getName()); // Add the attachment to the message. msg.addBodyPart(att); // Try to send the email. try { System.out.println("Attempting to send an email through Amazon SES " +"using the AWS SDK for Java..."); // Instantiate an Amazon SES client, which will make the service // call with the supplied AWS credentials. AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard() // Replace US_WEST_2 with the AWS Region you're using for // Amazon SES. .withRegion(Regions.US_WEST_2).build(); // Print the raw email content on the console PrintStream out = System.out; message.writeTo(out); // Send the email. ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); message.writeTo(outputStream); RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray())); SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage) .withConfigurationSetName(CONFIGURATION_SET); client.sendRawEmail(rawEmailRequest); System.out.println("Email sent!"); // Display an error if something goes wrong. } catch (Exception ex) { System.out.println("Email Failed"); System.err.println("Error message: " + ex.getMessage()); ex.printStackTrace(); } } }
PHP

下面的代码示例介绍如何使用 PHPMailer 程序包和 适用于 PHP 的 AWS 开发工具包 编写和发送包含 HTML 部分、文本部分和附件的原始电子邮件。

此代码示例假设您已安装了 PHPMailer包 使用 撰写人. 它还假定您已安装了 适用于 PHP 的 AWS 开发工具包,并且您已创建了共享凭证文件。有关创建共享凭证文件的更多信息,请参阅创建共享凭证文件

重要

可使用共享凭证文件来传递 AWS 访问密钥 ID 和秘密访问密钥。作为使用共享凭证文件的替代方案,您可以通过设置两个环境变量(分别为 AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEY)来指定 AWS 访问密钥 ID 和秘密访问密钥。除非您使用下列方法之一指定凭证,否则此示例无法正常运行。

<?php require 'vendor/autoload.php'; use PHPMailer\PHPMailer\PHPMailer; use Aws\Ses\SesClient; use Aws\Ses\Exception\SesException; // Replace sender@example.com with your "From" address. // This address must be verified with Amazon SES. $sender = 'sender@example.com'; $sendername = 'Sender Name'; // Replace recipient@example.com with a "To" address. If your account // is still in the sandbox, this address must be verified. $recipient = 'recipient@example.com'; // Specify a configuration set. $configset = 'ConfigSet'; // Replace us-west-2 with the AWS Region you're using for Amazon SES. $region = 'us-west-2'; $subject = 'List of customers to contact'; $htmlbody = <<<EOD <html> <head></head> <body> <h1>Hello!</h1> <p>Please see the attached file for a list of customers to contact.</p> </body> </html> EOD; $textbody = <<<EOD Hello, Please see the attached file for a list of customers to contact. EOD; // The full path to the file that will be attached to the email. $att = 'path/to/customers-to-contact.xlsx'; // Create an SesClient. $client = SesClient::factory(array( 'version'=> 'latest', 'region' => $region )); // Create a new PHPMailer object. $mail = new PHPMailer; // Add components to the email. $mail->setFrom($sender, $sendername); $mail->addAddress($recipient); $mail->Subject = $subject; $mail->Body = $htmlbody; $mail->AltBody = $textbody; $mail->addAttachment($att); $mail->addCustomHeader('X-SES-CONFIGURATION-SET', $configset); // Attempt to assemble the above components into a MIME message. if (!$mail->preSend()) { echo $mail->ErrorInfo; } else { // Create a new variable that contains the MIME message. $message = $mail->getSentMIMEMessage(); } // Try to send the message. try { $result = $client->sendRawEmail([ 'RawMessage' => [ 'Data' => $message ] ]); // If the message was sent, show the message ID. $messageId = $result->get('MessageId'); echo("Email sent! Message ID: $messageId"."\n"); } catch (SesException $error) { // If the message was not sent, show a message explaining what went wrong. echo("The email was not sent. Error message: " .$error->getAwsErrorMessage()."\n"); } ?>
Python

下面的代码示例介绍如何使用 Python email 程序包和 AWS SDK for Python (Boto) 编写和发送包含 HTML 部分、文本部分和附件的原始电子邮件。

此代码示例假定您已安装 AWS SDK for Python (Boto),并且您已创建共享凭证文件。有关创建共享凭证文件的更多信息,请参阅创建共享凭证文件

重要

可使用共享凭证文件来传递 AWS 访问密钥 ID 和秘密访问密钥。作为使用共享凭证文件的替代方案,您可以通过设置两个环境变量(分别为 AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEY)来指定 AWS 访问密钥 ID 和秘密访问密钥。除非您使用下列方法之一指定凭证,否则此示例无法正常运行。

import os import boto3 from botocore.exceptions import ClientError from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication # Replace sender@example.com with your "From" address. # This address must be verified with Amazon SES. SENDER = "Sender Name <sender@example.com>" # Replace recipient@example.com with a "To" address. If your account # is still in the sandbox, this address must be verified. RECIPIENT = "recipient@example.com" # Specify a configuration set. If you do not want to use a configuration # set, comment the following variable, and the # ConfigurationSetName=CONFIGURATION_SET argument below. CONFIGURATION_SET = "ConfigSet" # If necessary, replace us-west-2 with the AWS Region you're using for Amazon SES. AWS_REGION = "us-west-2" # The subject line for the email. SUBJECT = "Customer service contact info" # The full path to the file that will be attached to the email. ATTACHMENT = "path/to/customers-to-contact.xlsx" # The email body for recipients with non-HTML email clients. BODY_TEXT = "Hello,\r\nPlease see the attached file for a list of customers to contact." # The HTML body of the email. BODY_HTML = """\ <html> <head></head> <body> <h1>Hello!</h1> <p>Please see the attached file for a list of customers to contact.</p> </body> </html> """ # The character encoding for the email. CHARSET = "utf-8" # Create a new SES resource and specify a region. client = boto3.client('ses',region_name=AWS_REGION) # Create a multipart/mixed parent container. msg = MIMEMultipart('mixed') # Add subject, from and to lines. msg['Subject'] = SUBJECT msg['From'] = SENDER msg['To'] = RECIPIENT # Create a multipart/alternative child container. msg_body = MIMEMultipart('alternative') # Encode the text and HTML content and set the character encoding. This step is # necessary if you're sending a message with characters outside the ASCII range. textpart = MIMEText(BODY_TEXT.encode(CHARSET), 'plain', CHARSET) htmlpart = MIMEText(BODY_HTML.encode(CHARSET), 'html', CHARSET) # Add the text and HTML parts to the child container. msg_body.attach(textpart) msg_body.attach(htmlpart) # Define the attachment part and encode it using MIMEApplication. att = MIMEApplication(open(ATTACHMENT, 'rb').read()) # Add a header to tell the email client to treat this part as an attachment, # and to give the attachment a name. att.add_header('Content-Disposition','attachment',filename=os.path.basename(ATTACHMENT)) # Attach the multipart/alternative child container to the multipart/mixed # parent container. msg.attach(msg_body) # Add the attachment to the parent container. msg.attach(att) #print(msg) try: #Provide the contents of the email. response = client.send_raw_email( Source=SENDER, Destinations=[ RECIPIENT ], RawMessage={ 'Data':msg.as_string(), }, ConfigurationSetName=CONFIGURATION_SET ) # Display an error if something goes wrong. except ClientError as e: print(e.response['Error']['Message']) else: print("Email sent! Message ID:"), print(response['MessageId'])
Ruby

下面的代码示例介绍如何使用 Ruby MIME Gem 和 适用于 Ruby 的 AWS 开发工具包 编写和发送包含 HTML 部分、文本部分和附件的原始电子邮件。

此代码示例假定您已安装了 适用于 Ruby 的 AWS 开发工具包 和 MIME Gem,并且您已创建了共享凭证文件。有关创建共享凭证文件的更多信息,请参阅创建共享凭证文件

重要

可使用共享凭证文件来传递 AWS 访问密钥 ID 和秘密访问密钥。作为使用共享凭证文件的替代方案,您可以通过设置两个环境变量(分别为 AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEY)来指定 AWS 访问密钥 ID 和秘密访问密钥。除非您使用下列方法之一指定凭证,否则此示例无法正常运行。

require 'base64' #standard library require 'aws-sdk' #gem install aws-sdk require 'mime' #gem install mime # Replace sender@example.com with your "From" address. # This address must be verified with Amazon SES. sender = "sender@example.com" sendername = "Sender Name" # Replace recipient@example.com with a "To" address. If your account # is still in the sandbox, this address must be verified. recipient = "recipient@example.com" # Specify a configuration set. configsetname = "ConfigSet" # Replace us-west-2 with the AWS Region you're using for Amazon SES. awsregion = "us-west-2" # The subject line for the email. subject = "Customer service contact info" # The full path to the file that will be attached to the email. attachment = "path/to/customers-to-contact.xlsx" # The email body for recipients with non-HTML email clients. textbody = """ Hello, Please see the attached file for a list of customers to contact. """ # The HTML body of the email. htmlbody = """ <html> <head></head> <body> <h1>Hello!</h1> <p>Please see the attached file for a list of customers to contact.</p> </body> </html> """ # Create a new MIME text object that contains the base64-encoded content of the # file that will be attached to the message. file = MIME::Application.new(Base64::encode64(open(attachment,"rb").read)) # Specify that the file is a base64-encoded attachment to ensure that the # receiving client handles it correctly. file.transfer_encoding = 'base64' file.disposition = 'attachment' # Create a MIME Multipart Mixed object. This object will contain the body of the # email and the attachment. msg_mixed = MIME::Multipart::Mixed.new # Create a MIME Multipart Alternative object. This object will contain both the # HTML and plain text versions of the email. msg_body = MIME::Multipart::Alternative.new # Add the plain text and HTML content to the Multipart Alternative part. msg_body.add(MIME::Text.new(textbody,'plain')) msg_body.add(MIME::Text.new(htmlbody,'html')) # Add the Multipart Alternative part to the Multipart Mixed part. msg_mixed.add(msg_body) # Add the attachment to the Multipart Mixed part. msg_mixed.attach(file, 'filename' => attachment) # Create a new Mail object that contains the entire Multipart Mixed object. # This object also contains the message headers. msg = MIME::Mail.new(msg_mixed) msg.to = { recipient => nil } msg.from = { sender => sendername } msg.subject = subject msg.headers.set('X-SES-CONFIGURATION-SET',configsetname) # Create a new SES resource and specify a region ses = Aws::SES::Client.new(region: awsregion) # Try to send the email. begin # Provide the contents of the email. resp = ses.send_raw_email({ raw_message: { data: msg.to_s } }) # If the message was sent, show the message ID. puts "Email sent! Message ID: " + resp[0].to_s # If the message was not sent, show a message explaining what went wrong. rescue Aws::SES::Errors::ServiceError => error puts "Email not sent. Error message: #{error}" end