Created
September 29, 2023 06:55
-
-
Save dev-jaydeep/43930b3812834a82c753e01cb2d85036 to your computer and use it in GitHub Desktop.
Send email with attachments using amazon ses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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