In this example we are going to sent "text" emails with Amazon Simple Email Service (AWS SES).


Installation


Run composer require aws/aws-sdk-php to install AWS SDK for PHP library.


AWS SES configuration


Go to "Identity and Access Management" dashboard and add a new user by assigning "AmazonSESFullAccess" policy to it. The secret can be seen only once at the time of creating a new user so make sure you note it somewhere safe. Also make sure that the user cannot login to AWS like normal person would do so the "Group" should be "None" instead of something like "AdministratorAccess" so on.


Files


parameters.yml


parameters:
aws_sdk:
version: 'latest'
region: 'eu-west-1'
credentials:
key: 'USERS_AWS_KEY'
secret: 'USERS_AWS_SECRET'

services.yml


services:
app.aws.sdk:
class: Aws\Sdk
arguments:
- '%aws_sdk%'

AppBundle\Util\AwsUtil:
arguments:
$sdk: '@app.aws.sdk'

AwsUtil


declare(strict_types=1);

namespace AppBundle\Util;

use Aws\Sdk;
use Aws\Ses\Exception\SesException;
use Psr\Log\LoggerInterface;

class AwsUtil
{
private const CHARSET = 'UTF-8';

private $logger;
private $sdk;

public function __construct(
LoggerInterface $logger,
Sdk $sdk
) {
$this->logger = $logger;
$this->sdk = $sdk;
}

public function sendEmail(
iterable $toAddresses,
string $fromAddress,
string $subject,
string $body
): ?string {
$messageId = null;

try {
$result = $this->sdk->createSes()->sendEmail([
'Destination' => [
'ToAddresses' => $toAddresses,
],
'Source' => $fromAddress,
'Message' => [
'Subject' => [
'Charset' => self::CHARSET,
'Data' => $subject,
],
'Body' => [
'Text' => [
'Charset' => self::CHARSET,
'Data' => $body,
],
],
],
]);

$messageId = $result->get('MessageId');
} catch (SesException $e) {
$this->logger->error(sprintf('Email not sent. [%s]', $e->getAwsErrorMessage()));
}

return $messageId;
}
}