Skip to content

Instantly share code, notes, and snippets.

@adamcrampton
Last active November 12, 2024 01:02
Show Gist options
  • Save adamcrampton/671a1f305369daad06187793a63b6456 to your computer and use it in GitHub Desktop.
Save adamcrampton/671a1f305369daad06187793a63b6456 to your computer and use it in GitHub Desktop.
AWS PHP SDK v3 sendRawEmail with attachment
<?php
use Aws\Ses\SesClient;
use Aws\Exception\AwsException;
/**
* Send an email using the 'raw' version of the API.
* Use this when needing to send an attachment.
*
* @param array $addresses
* @param string $subject
* @param string $message
* @param string $sender
* @param array $replyTo
* @param string $attachment
* @return array
*/
public static function sendRawEmail(
array $addresses,
string $subject,
string $message,
string $sender = '[email protected]',
array $replyTo = ['[email protected]'],
string $attachment = ''
): array
{
$recipients = implode(',', $addresses);
$sesClient = new SesClient([
'version' => '2010-12-01',
'region' => 'ap-southeast-2',
'signatureVersion' => 'v4',
'credentials' => [
'key' => config('aws.key'), // Replace with wherever these are fetched from
'secret' => config('aws.secret') // Replace with wherever these are fetched from
]
]);
try {
$filename = basename($attachment);
$attachedData = chunk_split(
base64_encode(
file_get_contents($attachment)
)
);
$mimeType = finfo_file(
finfo_open(FILEINFO_MIME_TYPE),
$attachment
);
$separator = md5(time());
$separatorMultipart = md5($subject . time());
$raw = "MIME-Version: 1.0\n";
$raw .= "To: " . $recipients . "\n";
$raw .= "From:" . $sender . "\n";
$raw .= "Subject:" . $subject . "\n";
$raw .= "Content-Type: multipart/mixed; boundary=\"" . $separatorMultipart . "\"\n";
$raw .= "\n--" . $separatorMultipart . "\n";
$raw .= "Content-Type: multipart/alternative; boundary=\"" . $separator . "\"\n";
$raw .= "\n--" . $separator . "\n";
$raw .= "Content-Type: text/html; charset=\"UTF-8\"\n";
$raw .= "\n" . $message . "\n";
$raw .= "\n--" . $separator . "--\n";
$raw .= "--" . $separatorMultipart . "\n";
$raw .= "Content-Type: " . $mimeType . "; name=\"" . $filename . "\"\n";
$raw .= "Content-Disposition: attachment; filename=\"" . $filename . "\"\n";
$raw .= "Content-Transfer-Encoding: base64\n\n";
$raw .= $attachedData . "\n";
$raw .= "--" . $separatorMultipart . "--";
$result = $sesClient->sendRawEmail([
'Destinations' => $addresses,
'Source' => $sender,
'RawMessage' => [
'Data' => $raw
]
]);
return [
'result' => 'success',
'message' => $result['MessageId'] ?? 'Emails sent'
];
} catch (AwsException $e) {
error_log($e->getMessage());
error_log('The email was not sent. Error message: ' . $e->getAwsErrorMessage());
return [
'result' => 'error',
'message' => $e->getAwsErrorMessage()
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment