Sending emails programmatically over SMTP
Use an SMTP-enabled programming language or application to send email through Amazon SES. Before you start, complete the tasks in Getting started with sending email.
Get the SMTP endpoint, user name, and password from one of the following credential topics:
The examples use STARTTLS on port 587, which both SMTP options
support. For other settings, see Choose SMTP connection settings.
Do not use your AWS access key ID and secret access key as SMTP credentials. For more information, see Types of Amazon SES credentials.
Code examples
Provide the SMTP endpoint, port, user name, and password to your programming language's SMTP library. The library connects and sends the email.
Amazon Elastic Compute Cloud (Amazon EC2) restricts email traffic over port 25 by default. To avoid
timeouts, request removal of the restriction or use port 587. For more
information, see How do I
remove the restriction on port 25 from my Amazon EC2 instance or AWS Lambda
function?
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:
Do not store SMTP credentials in your source code. Use secure storage such as AWS Secrets Manager. These examples are for testing in a non-production environment.
- Java
-
This example uses the Eclipse IDE
and the JavaMail API to send email through Amazon SES over SMTP. Before you perform the following procedure, complete the tasks in Getting started with sending email.
To send an email over SMTP with Java
-
In a web browser, go to the JavaMail GitHub page
. Under Assets, choose javax.mail.jar to download the latest version of JavaMail. ImportantThis tutorial requires JavaMail version 1.5 or later. These procedures were tested using JavaMail version 1.6.1.
-
In a web browser, go to the Jakarta Activation GitHub page
, and under JavaBeans Activation Framework 1.2.1 Final Release , download the jakarta.activation.jar -
Create a project in Eclipse by performing the following steps:
-
Start Eclipse.
-
In Eclipse, choose File, choose New, and then choose Java Project.
-
In the Create a Java Project dialog box, type a project name and then choose Next.
-
In the Java Settings dialog box, choose the Libraries tab.
-
Select Classpath and add the two external jar files javax.mail.jar and jakarta.activation.jar using the Add External JARs button.
-
Choose Add External JARs.
-
Browse to the folder in which you downloaded JavaMail. Choose the file
javax.mail.jar, and then choose Open. -
In the Java Settings dialog box, choose Finish.
-
-
In Eclipse, in the Package Explorer window, expand your project.
-
Under your project, right-click the src directory, choose New, and then choose Class.
-
In the New Java Class dialog box, in the Name field, type
AmazonSESSampleand then choose Finish. -
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 the user name from your SMTP credentials. static final String SMTP_USERNAME = "smtp_username"; // The name of the configuration set to use for this message. static final String CONFIGURATION_SET = "ConfigSet"; // Replace smtp_endpoint with the endpoint from your SMTP credentials. static final String HOST = "smtp_endpoint"; // Both SMTP credential types support STARTTLS on port 587. static final int PORT = 587; static final String SUBJECT = "Amazon SES test email sent over SMTP"; 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 the configuration set header. msg.setHeader("X-SES-CONFIGURATION-SET", CONFIGURATION_SET); // Create a transport. Transport transport = session.getTransport(); // Get the password String SMTP_PASSWORD = fetchSMTPPasswordFromSecureStorage(); // Send the message. try { System.out.println("Sending..."); // Connect using the SMTP endpoint, user name, and password 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(); } } static String fetchSMTPPasswordFromSecureStorage() { /* IMPLEMENT THIS METHOD */ // For example, you might fetch it from a secure location or AWS Secrets Manager: https://aws.amazon.com/secrets-manager/ } } -
In AmazonSESSample.java, replace the following email addresses with your own values:
ImportantThe 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 Request production access (Moving out of the Amazon SES sandbox).
-
-
In AmazonSESSample.java replace the following with your own values:
-
smtp_username– Replace with the user name from your SMTP credentials. -
smtp_password– Implement`fetchSMTPPasswordFromSecureStorage`to fetch the password.
-
-
Replace
smtp_endpointwith the endpoint from your SMTP credentials. -
(Optional) To use a configuration set, set
CONFIGURATION_SETto its name. For more information, see Specifying a configuration set when you send email. -
Save AmazonSESSample.java.
-
To build the project, choose Project and then choose Build Project. (If this option is disabled, then you may have automatic building enabled.)
-
To start the program and send the email, choose Run and then choose Run again.
-
Review the output. If the email was successfully sent, the console displays "Email sent!" Otherwise, it displays an error message.
-
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 over SMTP.
Before you perform the following procedure you must complete the tasks in Getting started with sending email. 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/phpmailerIn the preceding command, replace
path/to/with the path where you installed Composer.
To send an email over SMTP with PHP
-
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 the user name from your SMTP credentials. $usernameSmtp = 'smtp_username'; // The name of the configuration set to use for this message. $configurationSet = 'ConfigSet'; // Replace smtp_endpoint with the endpoint from your SMTP credentials. $host = 'smtp_endpoint'; // Both SMTP credential types support STARTTLS on port 587. $port = 587; // The subject line of the email $subject = 'Amazon SES test email sent over SMTP'; // The plain-text body of the email $bodyText = "Email Test\r\nThis email was sent to Amazon SES over SMTP using the PHPMailer class."; // The HTML-formatted body of the email $bodyHtml = '<h1>Email Test</h1> <p>This email was sent to <a href="https://aws.amazon.com/ses">Amazon SES</a> over SMTP 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 = fetchSMTPPasswordFromSecureStorage(); $mail->Host = $host; $mail->Port = $port; $mail->SMTPAuth = true; $mail->SMTPSecure = 'tls'; // Add the configuration set header. $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. } function fetchSMTPPasswordFromSecureStorage() { /* IMPLEMENT THIS METHOD */ // For example, you might fetch it from a secure location or AWS Secrets Manager: https://aws.amazon.com/secrets-manager/ } ?> -
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 Request production access (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 the user name from your SMTP credentials. -
smtp_password– Implement`fetchSMTPPasswordFromSecureStorage`to fetch the password. -
smtp_endpoint– Replace with the endpoint from your SMTP credentials. -
(Optional)
configurationSet– To use a configuration set, set this value to its name. For more information, see Specifying a configuration set when you send email.
-
-
Save amazon-ses-smtp-sample.php.
-
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.
-
Review the output. If the email was successfully sent, the console displays "Email sent!" Otherwise, it displays an error message.
-
Sign in to the email client of the recipient address. You will see the message that you sent.
-