SMTP方式发送邮件

创建SMTP credential

使用SMTP发送邮件前,需要先创建SMTP credential:

image-20231005072233377

点击Create SMTP credentials后跳转到IAM页面,可以使用默认的用户名:

image-20231005072341148

点击创建。保存下来SMTP user nameSMTP password:

image-20231005072427006

PHP发送邮件

使用SMTP方式发送时,不同编程语言都有对应的库,本节我们以世界上最好的语言PHP为例。
如果使用cloud9,默认已经安装好php。如果本地环境没有安装php需要提前安装

安装composer( 参考 https://getcomposer.org/download/ ) :

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === 'e21205b207c3ff031906575712edab6f13eb0b361f2085f1f1237b7126d785e826a450292b6cfd1d64d92e6563bbde02') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

sudo mv composer.phar /usr/local/bin/composer

确认安装成功:

image-20231005074622265

使用composer安装phpmailer依赖:

composer require phpmailer/phpmailer

image-20231005074719687

在当前目录下创建sendmail.php,内容如下,根据实际情况替换$sender / $recipient / $usernameSmtp/ $passwordSmtp

<?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 = 'test@sesworkshop.kpingfan.com';
$senderName = 'kunkun';

// Replace recipient@example.com with a "To" address. If your account
// is still in the sandbox, this address must be verified.
$recipient = 'kpfan@qq.com';

// Replace smtp_username with your Amazon SES SMTP user name.
$usernameSmtp = 'AKIxxxxxxxxxxxxxxxxSTWGE';

// Replace smtp_password with your Amazon SES SMTP password.
$passwordSmtp = 'BMlL9Oxxxxxxxxxxxxxxxxxxxxg1vDwPF9gcX0';

// 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-east-1.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.
}

?>

运行sendmail.php:

image-20231005074002697

成功收件:

image-20231005074253352

参考: https://docs.aws.amazon.com/zh_cn/ses/latest/DeveloperGuide/send-using-smtp-php.html


上一节我们如果解除了sandbox的限制,可以给任意收件人发邮件:

image-20231005075350146

Python SMTP发送邮件

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# AWS SES SMTP settings
smtp_server = 'email-smtp.us-east-1.amazonaws.com'
smtp_port = 587  # TLS port

# Your AWS SES SMTP credentials
smtp_username = 'AKIxxxxxxxxJOJT'
smtp_password = 'BD8gxxxxxxxxxxxxxxxxxxxxxxxx'

# Sender and recipient email addresses
sender_email = 'test@sesworkshop.kpingfan.com'
recipient_email = 'xxxx@gmail.com'

# Create a multipart message and set headers
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = recipient_email
message['Subject'] = 'Test Email via AWS SES SMTP'

# Add body to email
body = 'Hello, this is a test email sent via AWS SES SMTP.'
message.attach(MIMEText(body, 'plain'))

# Try to connect to the SMTP server and send the email
try:
    smtp_server = smtplib.SMTP(smtp_server, smtp_port)
    smtp_server.starttls()  # Start TLS encryption
    smtp_server.login(smtp_username, smtp_password)
    text = message.as_string()
    smtp_server.sendmail(sender_email, recipient_email, text)
    print('Email sent successfully!')
except Exception as e:
    print('Error: Unable to send email.')
    print(e)
finally:
    smtp_server.quit()  # Close the SMTP connection

效果:

image-20240720224442831