Menu
Amazon Simple Email Service
Developer Guide

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.

Use the Filter View menu above to select a programming language.

C#

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

Copy
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. const String FROM = "sender@example.com"; // Replace recipient@example.com with a "To" address. If your account // is still in the sandbox, this address must be verified. const String TO = "recipient@example.com"; // Replace smtp_username with your Amazon SES SMTP user name. const String SMTP_USERNAME = "smtp_username"; // Replace smtp_password with your Amazon SES SMTP user name. const 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 on line 59, below. const 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 Region. const 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. const int PORT = 587; // The subject line of the email const String SUBJECT = "Amazon SES test (SMTP interface accessed using C#)"; // The body of the email const 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); 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); // Create and configure a new SmtpClient SmtpClient client = new SmtpClient(HOST, PORT); // Pass SMTP credentials client.Credentials = new NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD); // Enable SSL encryption client.EnableSsl = true; // Send the email. 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); } // Wait for a key press so that you can see the console output Console.Write("Press any key to continue..."); Console.ReadKey(); } } }

Go

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

Copy
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 on line 78. 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 = 465 // 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 sample code is a complete solution for sending email through the Amazon SES SMTP interface using Java. In order to run this sample code, you must obtain SMTP credentials; for more information, see Obtaining Your Amazon SES SMTP Credentials. You must also download the JavaMail API.

Copy
package AmazonSESSample; import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class AmazonSESSample { // Replace recipient@example.com with a "To" address. If your account // is still in the sandbox, this address must be verified. static final String FROM = "recipient@example.com"; // Replace sender@example.com with your "From" address. // This address must be verified. static final String TO = "sender@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 on line 65. static final String CONFIGSET = "ConfigSet"; // Amazon SES SMTP host name. This example uses the US West (Oregon) Region. 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 = 465; 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.ssl.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)); 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(); } } }

PHP

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

Copy
<?php // Modify the path in the require statement below to refer to the // location of your Composer autoload.php file. require 'path_to_sdk_inclusion'; // Instantiate a new PHPMailer $mail = new PHPMailer; // Tell PHPMailer to use SMTP $mail->isSMTP(); // Replace sender@example.com with your "From" address. // This address must be verified with Amazon SES. $mail->setFrom('sender@example.com', 'Sender Name'); // Replace recipient@example.com with a "To" address. If your account // is still in the sandbox, this address must be verified. // Also note that you can include several addAddress() lines to send // email to multiple recipients. $mail->addAddress('recipient@example.com', 'Recipient Name'); // Replace smtp_username with your Amazon SES SMTP user name. $mail->Username = 'smtp_username'; // Replace smtp_password with your Amazon SES SMTP password. $mail->Password = 'smtp_password'; // Specify a configuration set. If you do not want to use a configuration // set, comment or remove the next line. $mail->addCustomHeader('X-SES-CONFIGURATION-SET', '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. $mail->Host = 'email-smtp.us-west-2.amazonaws.com'; // The port you will connect to on the Amazon SES SMTP endpoint. $mail->Port = 465; // The subject line of the email $mail->Subject = 'Amazon SES test (SMTP interface accessed using PHP)'; // The HTML-formatted body of the email $mail->Body = '<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>'; // Tells PHPMailer to use SMTP authentication $mail->SMTPAuth = true; // Enable SSL encryption $mail->SMTPSecure = 'ssl'; // Tells PHPMailer to send HTML-formatted email $mail->isHTML(true); // The alternative email body; this is only displayed when a recipient // opens the email in a non-HTML email client. The \r\n represents a // line break. $mail->AltBody = "Email Test\r\nThis email was sent through the Amazon SES SMTP interface using the PHPMailer class."; if(!$mail->send()) { echo "Email not sent. " , $mail->ErrorInfo , PHP_EOL; } else { echo "Email sent!" , PHP_EOL; } ?>

Python

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

Copy
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. 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 on line 61, 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 = 465 # The subject line of the email. subject = 'Amazon SES Test (Python smtplib)' # Create the body of the message (a plain-text and an HTML version). text = '\r\n'.join([ "AWS SES Test", """This email was sent through the Amazon SES SMTP Interface using the Python smtplib package.""" ]) html = '\n'.join([ "<html>", "<head></head>", "<body>", "<h1>AWS 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',configSet) # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') part2 = MIMEText(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. If it fails, show the error message. try: server = smtplib.SMTP_SSL(host, port) server.ehlo() server.login(smtp_username, smtp_password) server.sendmail(sender, recipient, msg.as_string()) server.close() except Exception as e: print ("Error: ", e) else: print ("Email sent!")

Ruby

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

Copy
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 on line 35, 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 = 465 # 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 SSL. smtp.enable_ssl # 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 technical discussions about various Amazon SES topics, visit the Amazon SES Blog. To browse and post questions, go to the Amazon SES Forum.

On this page: