Sending emails programmatically through the Amazon SES SMTP interface - Amazon Simple Email Service

Sending emails programmatically through the Amazon SES SMTP interface

To send an email using the Amazon SES SMTP interface, you can use an SMTP-enabled programming language, email server, or application. Before you start, complete the tasks in Setting up Amazon Simple Email Service. You also need to get the following information:

Code examples

You can access the Amazon SES SMTP interface by using an SMTP-enabled programming language. You provide the Amazon SES SMTP hostname and port number along with your SMTP credentials and then use the programming language's generic SMTP functions to send the email.

Amazon Elastic Compute Cloud (Amazon EC2) restricts email traffic over port 25 by default. To avoid timeouts when sending email through the SMTP endpoint from Amazon EC2, you can request that these restrictions be removed. For more information, see How do I remove the restriction on port 25 from my Amazon EC2 instance or AWS Lambda function? in the AWS Knowledge Center.

The code examples in this section for C#, Java, and PHP, use port 587 to avoid this issue.

Note

In these tutorials, you send an email to yourself so that you can check to see if you received it. For further experimentation or load testing, use the Amazon SES mailbox simulator. Emails that you send to the mailbox simulator do not count toward your sending quota or your bounce and complaint rates. For more information, see Using the mailbox simulator manually.

Select a programing language to view the example for that language:

C#

The following procedure shows how to use Microsoft Visual Studio to create a C# console application that sends an email through Amazon SES. The procedures in this section apply to Visual Studio 2017, but the process of creating C# console applications is similar across Microsoft Visual Studio editions.

Before you perform the following procedure, complete the tasks in Setting up Amazon Simple Email Service.

To send an email using the Amazon SES SMTP interface with C#

  1. Create a console project in Visual Studio by performing the following steps:

    1. Open Microsoft Visual Studio.

    2. On the File menu, choose New, Project.

    3. On the New Project window, in the left pane, expand Installed, expand Templates, and then expand Visual C#.

    4. Under Visual C#, choose Windows Classic Desktop.

    5. On the menu at the top of the window, choose .NET Framework 4.5, as shown in the following image.

      
                                            The .NET Framework selection menu on the New
                                                Project window.
      Note

      You can choose a later version of the .NET Framework if necessary.

    6. Choose Console App (.NET Framework).

    7. In the Name field, type AmazonSESSample.

    8. Choose OK.

  2. In your Visual Studio project, replace the entire contents of Program.cs with the following code:

    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 password. 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); } } } } }
  3. In Program.cs, replace the following email addresses with your own values:

    Important

    The email addresses are case-sensitive. Make sure that the addresses are exactly the same as the ones you verified.

    • SENDER@EXAMPLE.COM—Replace with your "From" email address. You must verify this address before you run this program. For more information, see Verified identities in Amazon SES.

    • RECIPIENT@EXAMPLE.COM—Replace with your "To" email address. If your account is still in the sandbox, you must verify this address before you use it. For more information, see Moving out of the Amazon SES sandbox.

  4. In Program.cs, replace the following SMTP credentials with the values that you obtained in Obtaining Amazon SES SMTP credentials:

    Important

    Your SMTP credentials are different from your AWS credentials. For more information about credentials, see Types of Amazon SES credentials.

    • YOUR_SMTP_USERNAME—Replace with your SMTP user name. Note that your SMTP user name credential is a 20-character string of letters and numbers, not an intelligible name.

    • YOUR_SMTP_PASSWORD—Replace with your SMTP password.

  5. (Optional) If you want to use an Amazon SES SMTP endpoint in a Region other than US West (Oregon), change the value of the variable HOST to the endpoint you want to use. For a list of SMTP endpoint URLs for the AWS Regions where Amazon SES is available, see Amazon Simple Email Service (Amazon SES) in the AWS General Reference.

  6. (Optional) If you want to use a configuration set when sending this email, change the value of the variable CONFIGSET to the name of the configuration set. For more information about configuration sets, see Using configuration sets in Amazon SES.

  7. Save Program.cs.

  8. To build the project, choose Build and then choose Build Solution.

  9. To run the program, choose Debug and then choose Start Debugging.

  10. Review the output. If the email was successfully sent, the console displays "Email sent!" Otherwise, it displays an error message.

  11. Sign in to the email client of the recipient address. You will see the message that you sent.

Java

This example uses the Eclipse IDE and the JavaMail API to send email through Amazon SES using the SMTP interface.

Before you perform the following procedure, complete the tasks in Setting up Amazon Simple Email Service.

To send an email using the Amazon SES SMTP interface with Java

  1. In a web browser, go to the JavaMail Github page. Under Downloads, choose javax.mail.jar to download the latest version of JavaMail.

    Important

    This tutorial requires JavaMail version 1.5 or later. These procedures were tested using JavaMail version 1.6.1.

  2. Create a project in Eclipse by performing the following steps:

    1. Start Eclipse.

    2. In Eclipse, choose File, choose New, and then choose Java Project.

    3. In the Create a Java Project dialog box, type a project name and then choose Next.

    4. In the Java Settings dialog box, choose the Libraries tab.

    5. Choose Add External JARs.

    6. Browse to the folder in which you downloaded JavaMail. Choose the file javax.mail.jar, and then choose Open.

    7. In the Java Settings dialog box, choose Finish.

  3. In Eclipse, in the Package Explorer window, expand your project.

  4. Under your project, right-click the src directory, choose New, and then choose Class.

  5. In the New Java Class dialog box, in the Name field, type AmazonSESSample and then choose Finish.

  6. Replace the entire contents of AmazonSESSample.java with the following code:

    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(); } } }
  7. In AmazonSESSample.java, replace the following email addresses with your own values:

    Important

    The email addresses are case-sensitive. Make sure that the addresses are exactly the same as the ones you verified.

    • SENDER@EXAMPLE.COM—Replace with your "From" email address. You must verify this address before you run this program. For more information, see Verified identities in Amazon SES.

    • RECIPIENT@EXAMPLE.COM—Replace with your "To" email address. If your account is still in the sandbox, you must verify this address before you use it. For more information, see Moving out of the Amazon SES sandbox.

  8. In AmazonSESSample.java, replace the following SMTP credentials with the values that you obtained in Obtaining Amazon SES SMTP credentials:

    Important

    Your SMTP credentials are different from your AWS credentials. For more information about credentials, see Types of Amazon SES credentials.

    • YOUR_SMTP_USERNAME—Replace with your SMTP user name credential. Note that your SMTP user name credential is a 20-character string of letters and numbers, not an intelligible name.

    • YOUR_SMTP_PASSWORD—Replace with your SMTP password.

  9. (Optional) If you want to use an Amazon SES SMTP endpoint in an AWS Region other than US West (Oregon), change the value of the variable HOST to the endpoint you want to use. For a list of regions where Amazon SES is available, see Amazon Simple Email Service (Amazon SES) in the AWS General Reference.

  10. (Optional) If you want to use a configuration set when sending this email, change the value of the variable CONFIGSET to the name of the configuration set. For more information about configuration sets, see Using configuration sets in Amazon SES.

  11. Save AmazonSESSample.java.

  12. To build the project, choose Project and then choose Build Project. (If this option is disabled, then you may have automatic building enabled.)

  13. To start the program and send the email, choose Run and then choose Run again.

  14. Review the output. If the email was successfully sent, the console displays "Email sent!" Otherwise, it displays an error message.

  15. Sign into the email client of the recipient address. You will see the message that you sent.

PHP

This example uses the PHPMailer class to send email through Amazon SES using the SMTP interface.

Before you perform the following procedure you must complete the tasks in Setting up Amazon Simple Email Service. In addition to setting up Amazon SES you must complete the following prerequisites to sending email with PHP:

Prerequisites:

  • Install PHP—PHP is available at http://php.net/downloads.php. After you install PHP, add the path to PHP in your environment variables so that you can run PHP from any command prompt.

  • Install the Composer dependency manager—After you install the Composer dependency manager, you can download and install the PHPMailer class and its dependencies. To install Composer, follow the installation instructions at https://getcomposer.org/download.

  • Install the PHPMailer class— After you install Composer, run the following command to install PHPMailer:

    path/to/composer require phpmailer/phpmailer

    In the preceding command, replace path/to/ with the path where you installed Composer.

To send an email using the Amazon SES SMTP interface with PHP

  1. Create a file named amazon-ses-smtp-sample.php. Open the file with a text editor and paste in the following code:

    <?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. } ?>
  2. In amazon-ses-smtp-sample.php, replace the following with your own values:

    • sender@example.com—Replace with an email address that you have verified with Amazon SES. For more information, see Verified identities. Email addresses in Amazon SES are case-sensitive. Make sure that the address you enter is exactly the same as the one you verified.

    • recipient@example.com—Replace with the address of the recipient. If your account is still in the sandbox, you must verify this address before you use it. For more information, see Moving out of the Amazon SES sandbox. Make sure that the address you enter is exactly the same as the one you verified.

    • smtp_username—Replace with your SMTP user name credential, which you obtained from the SMTP Settings page of the Amazon SES console. This is not the same as your AWS access key ID. Note that your SMTP user name credential is a 20-character string of letters and numbers, not an intelligible name.

    • smtp_password—Replace with your SMTP password, which you obtained from the SMTP Settings page of the Amazon SES console. This is not the same as your AWS secret access key.

    • (Optional) ConfigSet—If you want to use a configuration set when sending this email, replace this value with the name of the configuration set. For more information about configuration sets, see Using configuration sets in Amazon SES.

    • (Optional) email-smtp.us-west-2.amazonaws.com—If you want to use an Amazon SES SMTP endpoint in a Region other than US West (Oregon), replace this with the Amazon SES SMTP endpoint in the Region you want to use. For a list of SMTP endpoint URLs for the AWS Regions where Amazon SES is available, see Amazon Simple Email Service (Amazon SES) in the AWS General Reference.

  3. Save amazon-ses-smtp-sample.php.

  4. To run the program, open a command prompt in the same directory as amazon-ses-smtp-sample.php, and then type php amazon-ses-smtp-sample.php.

  5. Review the output. If the email was successfully sent, the console displays "Email sent!" Otherwise, it displays an error message.

  6. Sign in to the email client of the recipient address. You will see the message that you sent.