Menu
Amazon Simple Email Service
Developer Guide

Sending Raw Email using AWS SDKs

The AWS SDKs contain built-in methods for interacting with Amazon SES and several other AWS services. If you plan to use Amazon SES along with other AWS services, we recommend that you use an SDK. To learn more about the AWS SDKs, see Tools for Amazon Web Services

In this section, you will find code examples in several programming languages that demonstrate the process of sending raw email through Amazon SES using the AWS SDKs.

JavaPHPPythonRuby
Java

The following code example shows how to use the JavaMail library and the AWS SDK for Java to compose and send a raw email that contains an HTML part, a text part, and an attachment.

This code example assumes you have installed the AWS SDK for Java, and that you have created a shared credentials file. For more information about creating a shared credentials file, see Create a Shared Credentials File.

Important

You use a shared credentials file to pass your AWS access key ID and secret access key. As an alternative to using a shared credentials file, you can specify your AWS access key ID and secret access key by setting two environment variables (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, respectively). This example doesn't function unless you specify your credentials using one of these methods.

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

The following code example shows how to use the PHPMailer package and the AWS SDK for PHP to compose and send a raw email that contains an HTML part, a text part, and an attachment.

This code example assumes that you have installed the PHPMailer package using Composer. It also assumes that you have installed the AWS SDK for PHP, and that you have created a shared credentials file. For more information about creating a shared credentials file, see Create a Shared Credentials File.

Important

You use a shared credentials file to pass your AWS access key ID and secret access key. As an alternative to using a shared credentials file, you can specify your AWS access key ID and secret access key by setting two environment variables (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, respectively). This example doesn't function unless you specify your credentials using one of these methods.

<?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

The following code example shows how to use the Python email package and the AWS SDK for Python (Boto) to compose and send a raw email that contains an HTML part, a text part, and an attachment.

This code example assumes that you have installed the AWS SDK for Python (Boto), and that you have created a shared credentials file. For more information about creating a shared credentials file, see Create a Shared Credentials File.

Important

You use a shared credentials file to pass your AWS access key ID and secret access key. As an alternative to using a shared credentials file, you can specify your AWS access key ID and secret access key by setting two environment variables (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, respectively). This example doesn't function unless you specify your credentials using one of these methods.

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

The following code example shows how to use the Ruby MIME gem and the AWS SDK for Ruby to compose and send a raw email that contains an HTML part, a text part, and an attachment.

This code example assumes that you have installed the AWS SDK for Ruby and the MIME gem, and that you have created a shared credentials file. For more information about creating a shared credentials file, see Create a Shared Credentials File.

Important

You use a shared credentials file to pass your AWS access key ID and secret access key. As an alternative to using a shared credentials file, you can specify your AWS access key ID and secret access key by setting two environment variables (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, respectively). This example doesn't function unless you specify your credentials using one of these methods.

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