Amazon Simple Email Service
開發人員指南

使用 Amazon SES SMTP 界面來傳送電子郵件

多種程式設計語言,包含使用 SMTP 傳送電子郵件的標準程式庫。您可以使用這些程式庫來建立電子郵件傳送應用程式,不佔空間且具高度的可設定性。

在本節中,您可以找到以各種程式設計語言提供的程式碼範例,示範使用 SMTP 界面來透過 Amazon SES 傳送電子郵件的程序。如果可以,這些程式碼範例皆使用標準的程式庫。

C#GolangJavaPerlPHPPythonRuby
C#

以下程式碼範例為使用 C# 透過 Amazon SES SMTP 界面傳送電子郵件的完整解決方案。為執行此程式碼範例,需取得 SMTP 登入資料;如需更多資訊,請參閱 取得您的 Amazon SES SMTP 登入資料

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); } } } } }
Golang

下列程式碼範例是使用 Go 程式設計語言透過 Amazon SES SMTP 界面傳送電子郵件的完整解決方案。為執行此程式碼範例,需取得 SMTP 登入資料;如需更多資訊,請參閱 取得您的 Amazon SES SMTP 登入資料。您也必須安裝 Gomail 套件

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

以下程式碼範例為使用 Java 透過 Amazon SES SMTP 界面傳送電子郵件的完整解決方案。為執行此程式碼範例,需取得 SMTP 登入資料;如需更多資訊,請參閱 取得您的 Amazon SES SMTP 登入資料。您也必須下載 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(); } } }
Perl

以下程式碼範例為使用 Perl 透過 Amazon SES SMTP 界面傳送電子郵件的完整解決方案。為執行此程式碼範例,需取得 SMTP 登入資料;如需更多資訊,請參閱 取得您的 Amazon SES SMTP 登入資料。您也必須安裝來自 CPANEmail::SenderEmail::MIME、以及 Try::Tiny 模組。

#!/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

以下程式碼範例為使用 PHP 透過 Amazon SES SMTP 界面傳送電子郵件的完整解決方案。為執行此程式碼範例,需取得 SMTP 登入資料;如需更多資訊,請參閱 取得您的 Amazon SES SMTP 登入資料。您也必須使用 Composer 來安裝 PHPMailer 套件

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

以下程式碼範例為使用 Python 透過 Amazon SES SMTP 界面傳送電子郵件的完整解決方案。為執行此程式碼範例,需取得 SMTP 登入資料;如需更多資訊,請參閱 取得您的 Amazon SES SMTP 登入資料

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

以下程式碼範例為使用 Ruby 透過 Amazon SES SMTP 界面傳送電子郵件的完整解決方案。為執行此程式碼範例,需取得 SMTP 登入資料;如需更多資訊,請參閱 取得您的 Amazon SES SMTP 登入資料

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

如需 Amazon SES 相關主題的各種資訊與討論,請造訪 AWS 傳訊與目標部落格。若要瀏覽與張貼問題,請前往 Amazon SES 論壇