AWS Simple Email Service (SES): Laravel PHP Code Examples

Using AWS Simple Email Service ( SES ) With Laravel from Start to Finish

In this article, we will be walking you step by step on how to use AWS SES with both a Laravel PHP app and a traditional PHP app. We’ll introduce the Laravel configuration. We will also learn what AWS Simple Email Service, commonly known as SES is and its setup and configuration. And then, we will discuss the methods used to send an email with AWS SES.

Table of Contents

In this article, we will cover the following topics.

  1. Laravel Introduction.
  2. Laravel’s configuration.
  3. What is AWS SES?
  4. AWS SES Setup & Configuration.
  5. Method used to send an email with AWS SES
  6. Prerequisites for Sending Emails via AWS SES.
  7. Send an Email Using Amazon SES Console.
  8. Send an Email using an AWS SDK.

Sending Email with Laravel is Easy

Sending an email doesn’t have to be complicated. Laravel makes it easy with its Mailer class and API. It’s powered by the popular Symfony Mailer component. Laravel and Symfony Mailer offer drivers to sending email via SMTP, Mailgun, Postmark, Amazon SES, and SendGrid, allowing you to quickly get started sending mail through a local or cloud-based service of your best choice.

Configuring Laravel to Send Emails

Laravel’s email services can be configured easily via your application’s config/mail.php configuration file. And each mailer configured within this file may have its unique configuration and even its unique “transport, ” allowing your application to use different email services to send specific email messages. For example, your application might use SparkPost to send transactional emails while using Amazon SES to send bulk emails.

And with your mail configuration file, you will also find a mailers configuration array. It contains a sample configuration entry for each of the significant mail drivers/transports supported by Laravel. In contrast, the default configuration value determines which mailer will be used by default when your application needs to send an email message.

What is AWS SES / Simple Email Service?

Amazon SES is a cloud-based email service provider that can integrate into any application for sending emails. With Amazon Simple Email Service, you can send transactional emails, marketing messages, or any other type of high-quality content to your customers, and you pay only for what you use. 

It also provides a variety of deployments, including dedicated, shared, or owned IP addresses. And also, reports on sender statistics and a deliverability dashboard help businesses make every email count.

One of the best features of Amazon SES is its low cost. The AWS SES service is chosen and used by companies such as Netflix, Reddit, and Duolingo.

Another important feature is the integration, through the console itself, API, or SMTP, it is possible to configure the sending of emails. In addition, Amazon SES not only allows sending of emails but also receiving them.

How to Setup & Configure Amazon SES in Console

Laravel allows using Amazon SES through the Amazon AWS SDK for PHP. If you cannot find any documentation after installing Amazon SES on Laravel for a client. 

The following 6 steps will help you setup & integrate AWS SES.

  1. Create AWS Account.

You can create an AWS account using this link: https://portal.aws.amazon.com/billing/signup#/start

  1. Add a new Domain. 

To create, add and verify a new domain, go here: https://eu-west-1.console.aws.amazon.com/ses/home?region=eu-west-1/verified-senders-domain

After creating a new domain, you need to complete your domain verification. You must add the TXT record to the domain’s DNS settings.

It normally includes

  • 1 TXT field
  • 3 CNAME fields
  • 1 MX field

You can find this information in your domain’s provider’s DNS settings.

When it’s done, you will receive an email telling you that your domain has been validated, and its “Verification Status” will change to “verified.”

3. Add an Email.

You can add the email address you would like to use to send emails using this link: https://eu-west-1.console.aws.amazon.com/ses/home?region=eu-west-1#verified-senders-email: 

You will also receive a confirmation email with a link to click to confirm that the email address belongs to you.

4. Create an IAM user and API Keys.

If you want to avoid using the API keys of your main account, then you can create an IAM user who will have rights only for Amazon SES.
Go to the link and click on add user: https://console.aws.amazon.com/iam/home?region=eu-west-1#/users

Now enter a name for your user, e.g., Test_SES, and click on next.

On the next screen, click on “Attach existing policies directly”, search for the “AmazonSESFullAccess” policy, and set your permission.

Now, click on create user, and your user will be created.

How to Setup Laravel with AWS SES

Setting up AWS SES with Laravel is really straightforward. Laravel comes with a built-in mailer service that you can easily tailor to your needs. Edit the config/services.php & config/mail.php classes and create a few sample mail classes and you are good to go.

Ok. Let’s get into the weeds and discuss the details.

Step 1: Install the AWS PHP SDK Into Your Laravel App with Composer

Open your terminal and in the root of Laravel project type:

composer require aws/aws-sdk-php

Step 2: Update Your Config & Environment Files

Open the config/services.php and make sure that the key called ses contains the following sub-array:

'ses' => [
    'key' => env('AWS_ACCESS_KEY_ID'),
    'secret' => env('AWS_SECRET_ACCESS_KEY'),
    'region' => env('AWS_DEFAULT_REGION'),
],

Edit the .env file now and also provide values for these environmental variables:

AWS_ACCESS_KEY_ID=""
AWS_SECRET_ACCESS_KEY=""
AWS_DEFAULT_REGION=eu-central-1

Make sure that changes are applied by clearing the application’s cache. Type php artisan cache:clear to clear any cached data. 

Now open the config/mail.php and after the following comment section:

/*
    |--------------------------------------------------------------------------
    | Global "From" Address
    |--------------------------------------------------------------------------
    |
    | You may wish for all e-mails sent by your application to be sent from
    | the same address. Here, you may specify a name and address that is
    | used globally for all e-mails that are sent by your application.
    |
*/

Add the following code:

'from' => [
    'address' => env('MAIL_FROM_ADDRESS', null),
    'name' => env('MAIL_FROM_NAME', null),
],


'contact' => [
    'address' => env('MAIL_CONTACT_ADDRESS', null),
],

Step 3: Create a Laravel Mailable Class

To send a test email, you need to generate a Laravel Mailable. First, create a file named “Test_email” using the following command.

php user make:mail TestEmail

You should now have an app/Mails/TestEmail.php file. Add the following PHP code to the file.

<?php


namespace App\Mail;
use App\Models\Customer;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;


class TestEmail extends Mailable
{
    use Queueable, SerializesModels;
   
    public $email_content;
   
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($email_content)
    {
        $this->email_content = $email_content;
    }
    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->from('address_added_on_aws')->view('emails.tpl');
    }
}

In the above code, as you can see with view(’emais.tpl’) it uses a view.

Using the above PHP code, you just have to send the email where you want. You will also need to create a route /test to ensure everything works fine.

Testing the Laravel Email with AWS SES

Ok phew. We have both Laravel and AWS configured. Now what? Well, let’s test it. I like to create a simple route whenever I just want to test a configuration. I have a get route in the below example. It calls the Laravel Mail Class and sends my TestEmail class.

Route::get('test', function () {
  Mail::to('user1@gmail.com)->send(new TestEmail('It works!'));
});

Method used to send an email with AWS SES

We send an email via AWS SES using the following methods.

  • Amazon SES Console
  • Using an AWS SDK

Prerequisites for Sending Emails via AWS SES

To send an email with AWS SES, you must complete the following prerequisites.

  • Sign up for AWS
  • Get your AWS access keys
  • Download an AWS SDK
  • Verify your email address
  • Create a shared credentials file

Sign Up For AWS

If you do not have an Amazon account, you need to complete the following steps.

  1. Open and visit the link https://portal.aws.amazon.com/billing/signup.
  2. Follow the online instructions.

The sign-up procedure also involves receiving a phone call and entering a verification code on the phone keypad. 

An AWS account root user is created when you sign up for an AWS account. The root user can access all AWS services and resources in the account. 

Get Your AWS Access Keys.

The AWS access keys contain an access key ID and a secret access key. When you sign up for AWS, you need to get your AWS access keys to access Amazon SES. You can get it through the AWS SES API, using the Query (HTTPS) interface directly or indirectly through an AWS SDK, the AWS Command Line Interface, or the AWS Tools for Windows PowerShell. 

Download an AWS SDK.

You can use an AWS SDK to call the Amazon SES API without having to handle low-level details like assembling raw HTTP requests. The AWS SDKs provide functions and data types that can encapsulate the functionality of Amazon SES and other AWS services. To download an AWS SDK, go to SDKs

After downloading the SDK, you must create a shared credentials file and specify your AWS access keys.

How to Setup AWS Access for Your PHP App.

There are a few ways to setup access from your PHP app into AWS. If you are also hosting your app inside of AWS then the recommended path is to use AWS IAM role based access. The second option is to setup a credentials file or work with environment variables. There are pros and cons to both options and it depends on how your host is currently setup.

We’ve written a few articles that may be helpful for you on this step.

Using AWS SDK & SES to Send Email with PHP

We can use an AWS SDK to send emails through Amazon SES. And the AWS SDKs are available for several programming languages including PHP. I like using the SDK because it feels like native code instead of worrying about rest APIS.

Ok, In the above examples we showed how to send emails in Laravel with AWS Simple Email Service. This turned out to be a piece of cake.

But what about standard PHP. How does that work?

Well Laravel does make it dead-simple to configure and send emails. The benefits with Laravel is that it is also easy to switch out services.

But it still isn’t terribly difficult to send emails in PHP with AWS Simple Email service if you don’t want the Laravel overhead.

Steps to Send an email using AWS SES with PHP

  1. Install the AWS SDK into your PHP app using Composer.
  2. Authenticate your app into AWS using role-based access or credentials
  3. Create a Mailer service class.
  4. Instantiate the PHP SESClient based on your config requirements
  5. Write your logic and business requirements in code.
  6. Use the sendMessage function to send the email.
  7. Test and check your email.

AWS SES + PHP CODE Examples

To send an email through AWS SES using AWS SDK for PHP, use the following code.

<?php


// Modify the path in the required statement below to refer to the
// And the location of your Composer autoload.php file.


require 'vendor/autoload.php';


use Aws\Ses\SesClient;
use Aws\Exception\AwsException;


//Now Create a SesClient. And also change the value of the region parameter i


//If you use an AWS Region other than US West (Oregon).


//Also, change the value of the profile parameter if you want to use a profile in your credentials file
//other than the default.


$SesClient = new SesClient([
    'profile' => 'default',
    'version' => '2010-12-01',
    'region'  => 'us-west-2'
]);


// Now replace the sender@example.com with your "From" address.
// And this address must be verified with your AWS SES.


$sender_email = 'sender@example.com';


// Now replace these sample addresses with the addresses of your recipients.
//And if your account is still in the sandbox, and these email addresses must be verified.


$recipient_emails = ['recipient_1@example.com','recipient_2@example.com'];


//Now, you need to specify the configuration set. And if you do not want to use a configuration.


// set, comment on the following variable, and the
// 'ConfigurationSetName' => $configuration_set argument below.


$configuration_set = 'ConfigSet';


$subject = 'Test Email';
$plaintext_body = 'The email was sent with Amazon SES using the AWS SDK for PHP.' ;
$html_body =  '<h1>Amazon Simple Email Service Test Email</h1>';
$char_set = 'UTF-8';


try {
    $result = $SesClient->sendEmail([
        'Destination' => [
            'ToAddresses' => $recipient_emails,
        ],
        'ReplyToAddresses' => [$sender_email],
        'Source' => $sender_email,
        'Message' => [
          'Body' => [
              'Html' => [
                  'Charset' => $char_set,
                  'Data' => $html_body,
              ],
              'Text' => [
                  'Charset' => $char_set,
                  'Data' => $plaintext_body,
              ],
          ],
          'Subject' => [
              'Charset' => $char_set,
              'Data' => $subject,
          ],
        ],
       
        // And if you aren't using a configuration set, comment or delete the
        // following line


        'ConfigurationSetName' => $configuration_set,
    ]);
    $messageId = $result['MessageId'];
    echo("Email sent! Message ID: $messageId"."\n");
} catch (AwsException $e) {


    // The output error message if it fails


    echo $e->getMessage();
    echo("The email was not sent. Error message: ".$e->getAwsErrorMessage()."\n");
    echo "\n";
}

Now, save the above code in a file named aws-ses-test.php. To run the program, open a command prompt in the same directory as aws-ses-test.php, and then type the following command.

$ php aws-ses-test.php

Now, review the output. If the email was successfully sent, the console displays “Email sent!” Otherwise, it displays an error message.

This article explains Laravel and its configuration in AWS SES. It also describes what AWS SES is and how to set up and configure AWS SES. 

This article also focuses on the methods used to send an email using AWS SES, and we hope you find this article helpful.

I hope you’ve enjoyed the article. Stay tuned for more at FuelingPHP

Dig Deeper with Our Email in PHP Examples and Guides


Article Categories

Article Tags

© 2023 Confident.Systems