Send AWS SES Email attachments using Mail_Mime and AWS SDK PHAR for PHP

AWS SES allow AWS users to send emails with attachment using PEAR Mail_Mime, it will generate / manually chunking the raw message to pass it along to the AWS SDK for PHP PHAR “aws.phar”.

First you need to request Amazon Web Services Support to increase your email sending quota per day in some AWS Region. Then support will move your account out of the sandbox, so you no longer need to verify recipient addresses.

<?php
require_once 'aws.phar';  /// download from https://github.com/aws/aws-sdk-php/releases
require_once 'Mail/mime.php';  /// download from http://pear.php.net/package/Mail_Mime
use Aws\Ses\SesClient;

// Setup variables From & To Email

$from = "[email protected]";
$to[] = "[email protected]"; 

// Create email message with attachment using PEAR Mail_Mime

$mail_mime = new Mail_mime(array('eol' => "\n"));
$mail_mime->setTxtBody("Sample Text body...");
$mail_mime->setHTMLBody("Sample HTML body...");

//PDF File
$mail_mime->addAttachment(dirname(__FILE__)."/files/[FILE].pdf", "application/pdf");

//CSV File
//$mail_mime->addAttachment(dirname(__FILE__)."/files/[FILE].csv", "application/csv");


$body = $mail_mime->get();
$headers = $mail_mime->txtHeaders(array('From' => $from, 'Subject' => "Sample Test message"));

$message = $headers . "\r\n" . $body;

// Set up email using AWS SDK for PHP PHAR

$client = SesClient::factory(array(
    'key'    => 'XXXXXXXXXXXXXXXXXXX',
    'secret' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
    'region' => 'eu-west-1'
));

// Send RAW message

$r = $client->sendRawEmail(array(
    'Source' => $from,
    'Destinations' => $to,
    'RawMessage' => array( 'Data' => base64_encode($message) )
));

/*if ($r->isOK()) {
  print("Mail sent; message id is " . (string) $r->body->SendRawEmailResult->MessageId . "\n");
} else {
  print("Mail not sent; error is " . (string) $r->body->Error->Message . "\n");
} */


?>