Sending email using the Amazon SES SMTP Interface - Amazon Simple Email Service

Sending email using the Amazon SES SMTP Interface

Several programming languages include standard libraries for sending email using SMTP. You can use these libraries to create email sending applications that are lightweight and highly configurable.

In this section, you will find code examples in several programming languages that demonstrate the process of sending email through Amazon SES using the SMTP interface. Wherever possible, these code examples use standard libraries.

C#

The following code example is a complete solution for sending email through the Amazon SES SMTP interface using C#. In order to run this code example, you must obtain SMTP credentials; for more information, see Obtaining your Amazon SES SMTP credentials.

using System; using System.Net; using System.Net.Mail; namespace AmazonSESSample { class Program { static void Main(string[] args) { // Replace sender@example.com with your "From" address. // This address must be verified with Amazon SES. String FROM = "sender@example.com"; String FROMNAME = "Sender Name"; // Replace recipient@example.com with a "To" address. If your account // is still in the sandbox, this address must be verified. String TO = "recipient@amazon.com"; // Replace smtp_username with your Amazon SES SMTP user name. String SMTP_USERNAME = "smtp_username"; // Replace smtp_password with your Amazon SES SMTP user name. String SMTP_PASSWORD = "smtp_password"; // (Optional) the name of a configuration set to use for this message. // If you comment out this line, you also need to remove or comment out // the "X-SES-CONFIGURATION-SET" header below. String CONFIGSET = "ConfigSet"; // If you're using Amazon SES in a region other than US West (Oregon), // replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP // endpoint in the appropriate AWS Region. String HOST = "email-smtp.us-west-2.amazonaws.com"; // The port you will connect to on the Amazon SES SMTP endpoint. We // are choosing port 587 because we will use STARTTLS to encrypt // the connection. int PORT = 587; // The subject line of the email String SUBJECT = "Amazon SES test (SMTP interface accessed using C#)"; // The body of the email String BODY = "<h1>Amazon SES Test</h1>" + "<p>This email was sent through the " + "<a href='https://aws.amazon.com/ses'>Amazon SES</a> SMTP interface " + "using the .NET System.Net.Mail library.</p>"; // Create and build a new MailMessage object MailMessage message = new MailMessage(); message.IsBodyHtml = true; message.From = new MailAddress(FROM, FROMNAME); message.To.Add(new MailAddress(TO)); message.Subject = SUBJECT; message.Body = BODY; // Comment or delete the next line if you are not using a configuration set message.Headers.Add("X-SES-CONFIGURATION-SET", CONFIGSET); using (var client = new System.Net.Mail.SmtpClient(HOST, PORT)) { // Pass SMTP credentials client.Credentials = new NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD); // Enable SSL encryption client.EnableSsl = true; // Try to send the message. Show status in console. try { Console.WriteLine("Attempting to send email..."); client.Send(message); Console.WriteLine("Email sent!"); } catch (Exception ex) { Console.WriteLine("The email was not sent."); Console.WriteLine("Error message: " + ex.Message); } } } } }
Go

The following code example is a complete solution for sending email through the Amazon SES SMTP interface using the Go programming language. In order to run this code example, you must obtain SMTP credentials; for more information, see Obtaining your Amazon SES SMTP credentials. You must also install the Gomail package.

package main import ( "fmt" "gopkg.in/gomail.v2" //go get gopkg.in/gomail.v2 ) const ( // 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" // Replace SmtpUser with your Amazon SES SMTP user name. SmtpUser = "SmtpUser" // Replace SmtpPass with your Amazon SES SMTP password. SmtpPass = "SmtpPass" // The name of the configuration set to use for this message. // If you comment out or remove this variable, you will also need to // comment out or remove the header below. ConfigSet = "ConfigSet" // If you're using Amazon SES in an AWS Region other than US West (Oregon), // replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP // endpoint in the appropriate region. Host = "email-smtp.us-west-2.amazonaws.com" Port = 587 // The subject line for the email. Subject = "Amazon SES Test (Gomail)" // The HTML body for the email. HtmlBody = "<html><head><title>SES Sample Email</title></head><body>" + "<h1>Amazon SES Test Email (Gomail)</h1>" + "<p>This email was sent with " + "<a href='https://aws.amazon.com/ses/'>Amazon SES</a> using " + "the <a href='https://github.com/go-gomail/gomail/'>Gomail " + "package</a> for <a href='https://golang.org/'>Go</a>.</p>" + "</body></html>" //The email body for recipients with non-HTML email clients. TextBody = "This email was sent with Amazon SES using the Gomail package." // The tags to apply to this message. Separate multiple key-value pairs // with commas. // If you comment out or remove this variable, you will also need to // comment out or remove the header on line 80. Tags = "genre=test,genre2=test2" // The character encoding for the email. CharSet = "UTF-8" ) func main() { // Create a new message. m := gomail.NewMessage() // Set the main email part to use HTML. m.SetBody("text/html", HtmlBody) // Set the alternative part to plain text. m.AddAlternative("text/plain", TextBody) // Construct the message headers, including a Configuration Set and a Tag. m.SetHeaders(map[string][]string{ "From": {m.FormatAddress(Sender,SenderName)}, "To": {Recipient}, "Subject": {Subject}, // Comment or remove the next line if you are not using a configuration set "X-SES-CONFIGURATION-SET": {ConfigSet}, // Comment or remove the next line if you are not using custom tags "X-SES-MESSAGE-TAGS": {Tags}, }) // Send the email. d := gomail.NewPlainDialer(Host, Port, SmtpUser, SmtpPass) // Display an error message if something goes wrong; otherwise, // display a message confirming that the message was sent. if err := d.DialAndSend(m); err != nil { fmt.Println(err) } else { fmt.Println("Email sent!") } }
Java

The following code example is a complete solution for sending email through the Amazon SES SMTP interface using Java. In order to run this code example, you must obtain SMTP credentials; for more information, see Obtaining your Amazon SES SMTP credentials. You must also download the JavaMail API.

import java.util.Properties; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class AmazonSESSample { // Replace sender@example.com with your "From" address. // This address must be verified. static final String FROM = "sender@example.com"; static final String FROMNAME = "Sender Name"; // Replace recipient@example.com with a "To" address. If your account // is still in the sandbox, this address must be verified. static final String TO = "recipient@example.com"; // Replace smtp_username with your Amazon SES SMTP user name. static final String SMTP_USERNAME = "smtp_username"; // Replace smtp_password with your Amazon SES SMTP password. static final String SMTP_PASSWORD = "smtp_password"; // The name of the Configuration Set to use for this message. // If you comment out or remove this variable, you will also need to // comment out or remove the header below. static final String CONFIGSET = "ConfigSet"; // Amazon SES SMTP host name. This example uses the US West (Oregon) region. // See https://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html#region-endpoints // for more information. static final String HOST = "email-smtp.us-west-2.amazonaws.com"; // The port you will connect to on the Amazon SES SMTP endpoint. static final int PORT = 587; static final String SUBJECT = "Amazon SES test (SMTP interface accessed using Java)"; static final String BODY = String.join( System.getProperty("line.separator"), "<h1>Amazon SES SMTP Email Test</h1>", "<p>This email was sent with Amazon SES using the ", "<a href='https://github.com/javaee/javamail'>Javamail Package</a>", " for <a href='https://www.java.com'>Java</a>." ); public static void main(String[] args) throws Exception { // Create a Properties object to contain connection configuration information. Properties props = System.getProperties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.port", PORT); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.auth", "true"); // Create a Session object to represent a mail session with the specified properties. Session session = Session.getDefaultInstance(props); // Create a message with the specified information. MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(FROM,FROMNAME)); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(TO)); msg.setSubject(SUBJECT); msg.setContent(BODY,"text/html"); // Add a configuration set header. Comment or delete the // next line if you are not using a configuration set msg.setHeader("X-SES-CONFIGURATION-SET", CONFIGSET); // Create a transport. Transport transport = session.getTransport(); // Send the message. try { System.out.println("Sending..."); // Connect to Amazon SES using the SMTP username and password you specified above. transport.connect(HOST, SMTP_USERNAME, SMTP_PASSWORD); // Send the email. transport.sendMessage(msg, msg.getAllRecipients()); System.out.println("Email sent!"); } catch (Exception ex) { System.out.println("The email was not sent."); System.out.println("Error message: " + ex.getMessage()); } finally { // Close and terminate the connection. transport.close(); } } }
JavaScript

The following code example is a complete solution for sending email through the Amazon SES SMTP interface by using the NodeMailer module in Node.js.

In order to run this code example, you first have to obtain SMTP credentials. For more information, see Obtaining your Amazon SES SMTP credentials. You must also install the NodeMailer module.

/* This code uses callbacks to handle asynchronous function responses. It currently demonstrates using an async-await pattern. AWS supports both the async-await and promises patterns. For more information, see the following: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/calling-services-asynchronously.html https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html */ "use strict"; const nodemailer = require("nodemailer"); // If you're using Amazon SES in a region other than US West (Oregon), // replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP // endpoint in the appropriate AWS Region. const smtpEndpoint = "email-smtp.us-west-2.amazonaws.com"; // The port to use when connecting to the SMTP server. const port = 587; // Replace sender@example.com with your "From" address. // This address must be verified with Amazon SES. const senderAddress = "Mary Major <sender@example.com>"; // Replace recipient@example.com with a "To" address. If your account // is still in the sandbox, this address must be verified. To specify // multiple addresses, separate each address with a comma. var toAddresses = "recipient@example.com"; // CC and BCC addresses. If your account is in the sandbox, these // addresses have to be verified. To specify multiple addresses, separate // each address with a comma. var ccAddresses = "cc-recipient0@example.com,cc-recipient1@example.com"; var bccAddresses = "bcc-recipient@example.com"; // Replace smtp_username with your Amazon SES SMTP user name. const smtpUsername = "AKIAIOSFODNN7EXAMPLE"; // Replace smtp_password with your Amazon SES SMTP password. const smtpPassword = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"; // (Optional) the name of a configuration set to use for this message. var configurationSet = "ConfigSet"; // The subject line of the email var subject = "Amazon SES test (Nodemailer)"; // The email body for recipients with non-HTML email clients. var body_text = `Amazon SES Test (Nodemailer) --------------------------------- This email was sent through the Amazon SES SMTP interface using Nodemailer. `; // The body of the email for recipients whose email clients support HTML content. var body_html = `<html> <head></head> <body> <h1>Amazon SES Test (Nodemailer)</h1> <p>This email was sent with <a href='https://aws.amazon.com/ses/'>Amazon SES</a> using <a href='https://nodemailer.com'>Nodemailer</a> for Node.js.</p> </body> </html>`; // The message tags that you want to apply to the email. var tag0 = "key0=value0"; var tag1 = "key1=value1"; async function main(){ // Create the SMTP transport. let transporter = nodemailer.createTransport({ host: smtpEndpoint, port: port, secure: false, // true for 465, false for other ports auth: { user: smtpUsername, pass: smtpPassword } }); // Specify the fields in the email. let mailOptions = { from: senderAddress, to: toAddresses, subject: subject, cc: ccAddresses, bcc: bccAddresses, text: body_text, html: body_html, // Custom headers for configuration set and message tags. headers: { 'X-SES-CONFIGURATION-SET': configurationSet, 'X-SES-MESSAGE-TAGS': tag0, 'X-SES-MESSAGE-TAGS': tag1 } }; // Send the email. let info = await transporter.sendMail(mailOptions) console.log("Message sent! Message ID: ", info.messageId); } main().catch(console.error);
Perl

The following code example is a complete solution for sending email through the Amazon SES SMTP interface using Perl. In order to run this code example, you must obtain SMTP credentials; for more information, see Obtaining your Amazon SES SMTP credentials. You must also install the Email::Sender, Email::MIME, and Try::Tiny modules from CPAN.

#!/usr/bin/perl use warnings; use strict; use Email::Sender::Simple qw(sendmail); use Email::Sender::Transport::SMTP; use Email::MIME; use Try::Tiny; # Replace sender@example.com with your "From" address. # This address must be verified. my $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. my $recipient = 'recipient@example.com'; # Replace smtp_username with your Amazon SES SMTP user name. my $smtp_username = "smtp_username"; # Replace smtp_password with your Amazon SES SMTP password. my $smtp_password = "smtp_password"; # (Optional) the name of a configuration set to use for this message. # If you comment out this line, you also need to remove or comment out # the "X-SES-CONFIGURATION-SET:" header below. my $configset = "ConfigSet"; # If you're using Amazon SES in an AWS Region other than US West (Oregon), # replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP # endpoint in the appropriate region. my $host = "email-smtp.us-west-2.amazonaws.com"; my $port = 587; # The subject line of the email. my $subject = "Amazon SES Test (Perl)"; # The HTML body for the email. my $htmlbody = <<'END_HTML'; <html> <head></head> <body> <h1>Amazon SES SMTP Email Test</h1> <p>This email was sent with Amazon SES using the <a href='https://www.perl.org/'>Perl</a> <a href='http://search.cpan.org/~rjbs/Email-Sender-1.300031/'> Email::Sender</a> library.</p> </body> </html> END_HTML # The email body for recipients with non-HTML email clients. my $textbody = "Amazon SES Test\r\n" . "This message was sent with Amazon SES using the Perl " . "Email::Sender module."; # Create the SMTP transport. my $transport = Email::Sender::Transport::SMTP->new( host => "$host", port => "$port", ssl => 'starttls', sasl_username => "$smtp_username", sasl_password => "$smtp_password", ); # Build a multipart MIME message with an HTML part and a text part. my $message = Email::MIME->create( attributes => { content_type => 'multipart/alternative', charset => 'UTF-8', }, header_str => [ From => "$sender", To => "$recipient", Subject => "$subject", ], parts => [ Email::MIME->create( attributes => { content_type => 'text/plain' }, body => "$textbody", ), Email::MIME->create( attributes => { content_type => 'text/html' }, body => "$htmlbody", ) ], ); # Add the configuration set header to the MIME message. $message->header_str_set( 'X-SES-CONFIGURATION-SET' => "$configset" ); # Try to send the email using the sendmail function from # Email::Sender::Simple. try { sendmail($message, { transport => $transport }); # If something goes wrong, print an error message. } catch { die "Error sending email: $_"; };
PHP

The following code example is a complete solution for sending email through the Amazon SES SMTP interface using PHP. In order to run this code example, you must obtain SMTP credentials; for more information, see Obtaining your Amazon SES SMTP credentials. You must also install the PHPMailer package using Composer.

<?php // Import PHPMailer classes into the global namespace // These must be at the top of your script, not inside a function use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; // If necessary, modify the path in the require statement below to refer to the // location of your Composer autoload.php file. require 'vendor/autoload.php'; // 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'; // Replace smtp_username with your Amazon SES SMTP user name. $usernameSmtp = 'smtp_username'; // Replace smtp_password with your Amazon SES SMTP password. $passwordSmtp = 'smtp_password'; // Specify a configuration set. If you do not want to use a configuration // set, comment or remove the next line. $configurationSet = 'ConfigSet'; // If you're using Amazon SES in a region other than US West (Oregon), // replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP // endpoint in the appropriate region. $host = 'email-smtp.us-west-2.amazonaws.com'; $port = 587; // The subject line of the email $subject = 'Amazon SES test (SMTP interface accessed using PHP)'; // The plain-text body of the email $bodyText = "Email Test\r\nThis email was sent through the Amazon SES SMTP interface using the PHPMailer class."; // The HTML-formatted body of the email $bodyHtml = '<h1>Email Test</h1> <p>This email was sent through the <a href="https://aws.amazon.com/ses">Amazon SES</a> SMTP interface using the <a href="https://github.com/PHPMailer/PHPMailer"> PHPMailer</a> class.</p>'; $mail = new PHPMailer(true); try { // Specify the SMTP settings. $mail->isSMTP(); $mail->setFrom($sender, $senderName); $mail->Username = $usernameSmtp; $mail->Password = $passwordSmtp; $mail->Host = $host; $mail->Port = $port; $mail->SMTPAuth = true; $mail->SMTPSecure = 'tls'; $mail->addCustomHeader('X-SES-CONFIGURATION-SET', $configurationSet); // Specify the message recipients. $mail->addAddress($recipient); // You can also add CC, BCC, and additional To recipients here. // Specify the content of the message. $mail->isHTML(true); $mail->Subject = $subject; $mail->Body = $bodyHtml; $mail->AltBody = $bodyText; $mail->Send(); echo "Email sent!" , PHP_EOL; } catch (phpmailerException $e) { echo "An error occurred. {$e->errorMessage()}", PHP_EOL; //Catch errors from PHPMailer. } catch (Exception $e) { echo "Email not sent. {$mail->ErrorInfo}", PHP_EOL; //Catch errors from Amazon SES. } ?>
Python

The following code example is a complete solution for sending email through the Amazon SES SMTP interface using Python. In order to run this code example, you must obtain SMTP credentials; for more information, see Obtaining your Amazon SES SMTP credentials.

import smtplib import email.utils from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # Replace sender@example.com with your "From" address. # This address must be verified. 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' # Replace smtp_username with your Amazon SES SMTP user name. USERNAME_SMTP = "smtp_username" # Replace smtp_password with your Amazon SES SMTP password. PASSWORD_SMTP = "smtp_password" # (Optional) the name of a configuration set to use for this message. # If you comment out this line, you also need to remove or comment out # the "X-SES-CONFIGURATION-SET:" header below. CONFIGURATION_SET = "ConfigSet" # If you're using Amazon SES in an AWS Region other than US West (Oregon), # replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP # endpoint in the appropriate region. HOST = "email-smtp.us-west-2.amazonaws.com" PORT = 587 # The subject line of the email. SUBJECT = 'Amazon SES Test (Python smtplib)' # The email body for recipients with non-HTML email clients. BODY_TEXT = ("Amazon SES Test\r\n" "This email was sent through the Amazon SES SMTP " "Interface using the Python smtplib package." ) # The HTML body of the email. BODY_HTML = """<html> <head></head> <body> <h1>Amazon SES SMTP Email Test</h1> <p>This email was sent with Amazon SES using the <a href='https://www.python.org/'>Python</a> <a href='https://docs.python.org/3/library/smtplib.html'> smtplib</a> library.</p> </body> </html> """ # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = SUBJECT msg['From'] = email.utils.formataddr((SENDERNAME, SENDER)) msg['To'] = RECIPIENT # Comment or delete the next line if you are not using a configuration set msg.add_header('X-SES-CONFIGURATION-SET',CONFIGURATION_SET) # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(BODY_TEXT, 'plain') part2 = MIMEText(BODY_HTML, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) # Try to send the message. try: server = smtplib.SMTP(HOST, PORT) server.ehlo() server.starttls() #stmplib docs recommend calling ehlo() before & after starttls() server.ehlo() server.login(USERNAME_SMTP, PASSWORD_SMTP) server.sendmail(SENDER, RECIPIENT, msg.as_string()) server.close() # Display an error message if something goes wrong. except Exception as e: print ("Error: ", e) else: print ("Email sent!")
Ruby

The following code example is a complete solution for sending email through the Amazon SES SMTP interface using Ruby. In order to run this code example, you must obtain SMTP credentials; for more information, see Obtaining your Amazon SES SMTP credentials.

require 'net/smtp' # 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" # Replace smtp_username with your Amazon SES SMTP user name. smtp_username = "smtp_username" # Replace smtp_password with your Amazon SES SMTP password. smtp_password = "smtp_password" # (Optional) the name of a configuration set to use for this message. # If you comment out this line, you also need to remove or comment out # the "X-SES-CONFIGURATION-SET" header below. configSet = "ConfigSet" # If you're using Amazon SES in an AWS Region other than US West (Oregon), # replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP # endpoint in the appropriate region. server = "email-smtp.us-west-2.amazonaws.com" port = 587 # The subject line of the email. subject = "Amazon SES Test (Ruby Net::SMTP library)" # Specify the headers and body of the message as a variable. message = [ #Remove the next line if you are not using a configuration set "X-SES-CONFIGURATION-SET: #{configSet}", "Content-Type: text/html; charset=UTF-8", "Content-Transfer-Encoding: 7bit", "From: #{senderName} <#{sender}>", "To: #{recipient}", "Subject: #{subject}", "", "<h1>Amazon SES Test (Ruby Net::SMTP library)</h1>", "<p>This email was sent with \ <a href='https://aws.amazon.com/ses/'>\ Amazon SES</a> using the Ruby Net::SMTP library.</p>" ].join("\n") # Create a new SMTP object called "smtp." smtp = Net::SMTP.new(server, port) # Tell the smtp object to connect using TLS. smtp.enable_starttls # Open an SMTP session and log in to the server using SMTP authentication. smtp.start(server,smtp_username,smtp_password, :login) # Try to send the message. begin smtp.send_message(message, sender, recipient) puts "Email sent!" # Print an error message if something goes wrong. rescue => e puts e end

For information and discussions about a variety of topics related to Amazon SES, see the AWS Messaging and Targeting Blog. To browse and post questions, go to the Amazon SES Forum.