Sending Email with SES

Official Doc: https://docs.aws.amazon.com/ses/latest/DeveloperGuide/smtp-credentials.html

Steps:

  • Verify domain in SES
  • Create email address
  • Create an IAM for SES and obtain credentials.
  • Send email with SES credentials.
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

//因為phpmail的問題,sender & subject如果有中文要特別處理
public function send_ses($subject, $msg, $contact){
    $sender = $this->sender['email'];
    $senderName = "=?UTF-8?B?".base64_encode($this->sender['name'])."?=";
    $recipient = $contact['email'];
    $usernameSmtp = $this->sender['account'];
    $passwordSmtp = $this->sender['password'];
    //$configurationSet = 'ConfigSet';
    $host = $this->sender['host'];
    $port = 587;

    $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);
        $mail->Charset = 'UTF-8';

        // 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    = "=?UTF-8?B?".base64_encode($subject)."?=";
        $mail->Body       = $msg;
        //$mail->AltBody    = $bodyText;
        $mail->Send();
        //echo "Email sent!" , PHP_EOL;

        return true;
    } catch (phpmailerException $e) {
        //Catch errors from PHPMailer.
        $this->err = "An error occurred. {$e->errorMessage()}"; 
        return false;
    } catch (Exception $e) {
        //Catch errors from Amazon SES.
        $this->err = "Email not sent. {$mail->ErrorInfo}"; 
        return false;
    }
}