AWS SES寄信,使用smtp+phpmailer

以下是使用AWS SES的步驟:

1.進入AWS CONSOLE,我個人選US East (N. Virginia),EC2則選東京。

2.進入SES後,點選Domain,然後會要你到Route53填一串TXT,填好即可。

3.點選Email Addresses,然後將你在Workmail使用的email填寫進來。Workmail怎麼用可以參考這篇文章

4.之後點選smtp setting,之後download credentials,會有smtp user 跟smtp secret。

5.一開始使用SES,都是在sandbox運作,也就是要經過認證的信箱才能被寄送,這可以到Support center去寫個信即可跳離sandbox模式。

6.用composer安裝好phpmailer

7.寫code。

<?php 
require 'PHPMailerAutoload.php'; 
$mail = new PHPMailer; 
//$mail->SMTPDebug = 3;                               // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'user@example.com';                 // SMTP username (就是SES smtp username)
$mail->Password = 'secret';                           // SMTP password(SES smtp password)
$mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;                                    // TCP port to connect to

$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
$mail->addAddress('ellen@example.com');               // Name is optional
$mail->addReplyTo('info@example.com', 'Information');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');

$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body in bold!';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

以上應該已經可以成功寄信囉。然後記得EC2的機器Security group outbound 要打開,否則會連不上amazon的smtp。