Skip to content

Instantly share code, notes, and snippets.

@dev-jaydeep
Created September 29, 2023 06:55
Show Gist options
  • Save dev-jaydeep/43930b3812834a82c753e01cb2d85036 to your computer and use it in GitHub Desktop.
Save dev-jaydeep/43930b3812834a82c753e01cb2d85036 to your computer and use it in GitHub Desktop.
Send email with attachments using amazon ses
<?php
//required `phpmailer/phpmailer` and `aws/aws-sdk-php` PHP library
use Aws\Ses\Exception\SesException;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
$AWS_ACCESS_KEY_ID = 'xxxxxxxxxxxxx';
$AWS_SECRET_ACCESS_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxx';
$AWS_REGION = 'us-east-2';
$fromName = 'FROM_NAME';
$fromMail = 'from@email.com';
$replyName = 'REPLY_NAME';
$replyMail = 'reply@email.com';
$attachments = array(
array(
'fileName' => '',
'filePath' => '',
)
);
$subject = '';
$htmlBody = '';
$textBody = '';
$toAddresses = array(
'test@recipient.com'
);
$client = new SesClient([
'version' => 'latest',
'region' => $AWS_REGION,
'credentials' => [
'key' => $AWS_ACCESS_KEY_ID,
'secret' => $AWS_SECRET_ACCESS_KEY,
],
]);
$mail = new PHPMailer(true);
//To
foreach($toAddresses as $to ) {
$mail->addAddress($to);
}
//From
if( $fromName && $fromMail ) {
$mail->setFrom($fromMail, $fromName);
}
//Reply To
if( $replyName && $replyMail ) {
$mail->addReplyTo($replyMail, $replyName);
}
//Attachments
foreach($attachments as $attachment) {
$mail->addAttachment($attachment['filePath']);
}
//Content
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $htmlBody;
$mail->AltBody = $textBody;
$mail->preSend();
$rawMessage = $mail->getSentMIMEMessage();
//send raw email
$result = $client->sendRawEmail([
'RawMessage' => [
'Data' => $rawMessage
],
]);
$messageId = $result->get('MessageId');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment