AWS SES Bulk Email: If you were using AWS (Amazon Web Services) SES (Simple Email Service) to send email, then you have probably heard of bulk email. Like if we want to send a lot of emails simultaneously, then we CC (Carbon copy) You can attach and send many emails in the field.

But what will we do when we have to send different emails to different people simultaneously? To solve this problem, AWS SES has provided the facility of bulk email template through which you can send unique mail to different people.

What is AWS SES – What is AWS SES?

Full form of AWS Amazon web service Which means that all the services related to the web application of amazon are in the category of AWS.

SES has a full form Simple Email Service. AWS also provides email sending service through which you can send mail to anyone through your application.

Like many times we have to send any type of information like notice, information, etc. from our application to our customers through email. If you want to send, we do not have to type separately one by one. For example, if you have a school application and you want that all the children in our school who do not have a fee are matched with their total fee to their parents, then you can add bulk email service to your application. Can

What is a template? What is a Bulk email template?

AWS SES Bulk Email: Template is a predesigned file that is used to quickly format or create anything. Here also the template is a file that is created on AWS and it tells in which format the email has to be sent.

Bulk email template is a predesigned file which is used to send bulk email. Bulk means a lot.

For example, if you go to college, then you get a predesigned form in which you have to fill your data according to the form, but think what will you do if blank paper is given in place of the form?

First you will think what to write and how to write in it. The second thing is that while writing, some information may be moved here and there, so a template is made which makes the work easier.

AWS SES Bulk Email: How to send email in bulk via PHP in AWS SES?

Now through PHP step by step bulk email create Will see the process of doing. However I have made a library for bulk email for your convenience, which will be very easy for you to implement.

Before implementing this tutorial in your project, let me tell you that you must have some information which is as follows:

  1. AWS console account
  2. Email service in your account
  3. Access key (AWS SES API you will get this information when you purchase)
  4. Secret key (you will get this information when you purchase AWS SES API)
  5. AWS region (information about the region in which your AWS account is setup such as ap-south-1)
  6. AWS Version (this bydefault latest But you can set it according to your AWS version)
  7. AWS email from (email that is setup in your AWS SES by which mail will be sent to the user)

How to implement AWS SES bulk email service in Project?

First of all, you have to download AWS library. You can download AWS library from this page. (Click here to AWS SDK page)

If you do not understand anything in the link given above, then you can download from my code which third_party The complete setup will be found inside the folder. Github link

After copy paste it into the project, the second step is to create a template.

$result = $client->createTemplate([
                 'Template' => [
                    'TemplateName' => 'Template Name', //Required
                    'SubjectPart'  => "{{subject}}",
                    'TextPart'      => "{{message}}",
                    'HtmlPart'     => "{{message}}"
                ],
            ]);

The next step is to create bulk email destination which is the below given format.

{
  "Source":"sender@example.com",
  "ConfigurationSetName":"ConfigSet",
  "Template":"MyTemplate",
  "Destinations":[
    {
      "Destination":{
        "ToAddresses":[
          "anaya.iyengar@example.com"
        ]
      },
      "ReplacementTemplateData":"{ "name":"Anaya", "favoriteanimal":"yak" }"
    },
    {
      "Destination":{ 
        "ToAddresses":[
          "liu.jie@example.com"
        ]
      },
      "ReplacementTemplateData":"{ "name":"Liu", "favoriteanimal":"water buffalo" }"
    },
    {
      "Destination":{
        "ToAddresses":[
          "shirley.rodriguez@example.com"
        ]
      },
      "ReplacementTemplateData":"{ "name":"Shirley", "favoriteanimal":"vulture" }"
    },
    {
      "Destination":{
        "ToAddresses":[
          "richard.roe@example.com"
        ]
      },
      "ReplacementTemplateData":"{}"
    }
  ],
  "DefaultTemplateData":"{ "name":"friend", "favoriteanimal":"unknown" }"
}

It describes how to create multiple destinations. You may find it confusing to see and do not understand, so I have created my own library, which you can easily implement by implementing it in your project.

email_constant.php

<?php

define('ACCESS_KEY', 'Your access key here'); //change
define('SECRET_KEY', 'Your secret key here'); //chang
define('AWS_REGION', 'AWS region like ap-south-1'); //change
define('AWS_VERSION', 'latest'); //you can change it but default Latest
define('AWS_EMAIL_FROM', 'Your from email'); //change


define('EMAIL_TEMPLATE_NAME', 'BULK_EMAIL'); //MUST BE UNIQUE

In the file above, I have put all the code that we have to change according to our AWS account in a constant file so that you do not have to change in the library.

Aws_bulk_email.php

<?php

/*
 * @class Aws_bulk_email
 * @author Sumit Kumar Gupta
 * @purpose send bulk email via amazon AWS SES
 */

 
require_once ('email_constant.php');
require_once ('third_party/Aws/aws-autoloader.php');

use AwsSesSesClient;
use AwsExceptionAwsException;

class Aws_bulk_email {

    /**
     * function helps to send email in bulk with SES
     * @param  array $data 
     *         receipients,
     *         subject,
     *         message
     *  data must be multidimensional array like 
     *      [
     *          [
     *              'id' => '1',
     *              'receipients' => 'firstemail@email.com',
     *              'subject' => 'Subject 1 here',
     *              'message' => 'message 1 here'
     *          ],
     *          [
     *              'id' => '2',
     *              'receipients' => 'secondemail@email.com',
     *              'subject' => 'Subject2 here',
     *              'message' => 'message2 here'
     *          ]
     *      ]
     * @return array
     */
    public function sendEmail($data) {

        try {
            if(!is_array($data) && empty($data)){
                return;
            }

            $destinations = $sendingMessageData = array();
            $index = -1; //we can't take foreach key here

            foreach ($data as $key => $value) {

                $index = $index + 1;
               
                $replacementData = [
                    'subject' => $value['subject'],
                    'message' => $value['message']
                ];

                $destinations[] = [
                        'Destination'  => [
                            'ToAddresses'  => [$value['receipients']],
                        ],
                        'ReplacementTemplateData' => json_encode($replacementData)
                    ];

                $sendingMessageData[$index] = $value['id'];
            }
            
            $client = new SesClient([
                'credentials' => array(
                        'key' => ACCESS_KEY,
                        'secret'  => SECRET_KEY
                    ),
                'region'      => AWS_REGION,
                'version'     => AWS_VERSION
            ]);

            $sentResponse = $client->sendBulkTemplatedEmail([
                'DefaultTemplateData'  => "{"subject":"unknown", "message":"unknown"}",             
                'Destinations'  => $destinations,
                'Source'  => AWS_EMAIL_FROM,
                'Template'  => EMAIL_TEMPLATE_NAME,
            ]);

            return [
                'response' => $sentResponse,
                'send_mail_ids' => $sendingMessageData
            ];
        } catch (AwsException $ex) {
            return [
                'response' => $ex->getMessage()
            ];
        }
    }

    /**
     * function helps to check that email template is available or not
     * if not available then create a new one
     * @return boolean
     */
    public function checkBulkEmailTemplateExistsOnAws(){

        $client = new SesClient([
            'credentials' => array(
                    'key' => ACCESS_KEY,
                    'secret'  => SECRET_KEY
                ),
            'region'      => AWS_REGION,
            'version'     => AWS_VERSION,
        ]);

        //get list of 10 email templates
        $templateLists = $client->listTemplates([
            'MaxItems' => 10
        ]);
        
        if(!isset($templateLists['TemplatesMetadata'])){
            $this->createBulkEmailTemplate($client);
            return true;
        }

        $templateNameColumn = array_column($templateLists['TemplatesMetadata'], 'Name');
        $templateNameSearch = array_search(EMAIL_TEMPLATE_NAME, $templateNameColumn);

        if($templateNameSearch === false){
            $this->createBulkEmailTemplate($client);
            return true;
        }
        return true;
    }

    /**
     * function helps to create email template
     * @param  ses client object $client [in this new SesClient() function data]
     * @return boolean
     */
    private function createBulkEmailTemplate($client){
        
        try{
            $result = $client->createTemplate([
                 'Template' => [
                    'TemplateName' => EMAIL_TEMPLATE_NAME,
                    'SubjectPart'  => "{{subject}}",
                    'TextPart'      => "{{message}}",
                    'HtmlPart'     => "{{message}}"
                ],
            ]);
            return true;
        }catch(AwsException $e) {
            return false;
        }
    }
}

send_email.php

<?php

require_once ('Aws_bulk_email.php');

//only 50 index at a time
$data = [
	[
		'id'	=> 1,
		'receipients'	=> 'test1@yopmail.com',
		'subject' => 'Test1 subject here',
		'message' => 'Test1 message here'
	],
	[
		'id'	=> 2,
		'receipients'	=> 'test2@yopmail.com',
		'subject' => 'Test2 subject here',
		'message' => 'Test2 message here'
	]
];

$obj = new Aws_bulk_email();

//first check or create email template
$obj->checkBulkEmailTemplateExistsOnAws();

//send email
$response = $obj->sendEmail($data);
echo "<pre>";
print_r($response);exit;

All the changes you have to make have to be made in the send_email file.

  • I have included my library first of all.
  • One thing to keep in mind is that only send 50 data at a time, if there is more than 50 then you array_chunks () Using loop Can run
  • After that I have prepared my bulk email data in array format.
  • After that, we have created an object of our library class through which we can call the function of library.
  • After that i checkBulkEmailTemplateExistsOnAws () function is called. It is made in the function library, whose job is to create a template on AWS, but before that check that this template is not already created. If already created, it will not create a new template so that my AWS service will not be of much use.
  • After that i sendEmail () has called a function in which array data is passed through the parameter.

Note: In this way the library will work only if you send data in the same way as the data array is formatted.

Now you will get some kind of response through the library, through which you can know how much email send was successful and how much failed.

Array
(
    [response] => AwsResult Object
        (
            [data:AwsResult:private] => Array
                (
                    [Status] => Array
                        (
                            [0] => Array
                                (
                                    [Status] => Success
                                    [MessageId] => 01000175c7320989-0084ac8b-7c66-444d-9b38-956fce6784e9-000000
                                )

                            [1] => Array
                                (
                                    [Status] => Success
                                    [MessageId] => 01000175c7320991-2e74ae9a-3078-4499-a608-8893ac91d522-000000
                                )

                        )

                    [@metadata] => Array
                        (
                            [statusCode] => 200
                            [effectiveUri] => https://email.us-east-1.amazonaws.com
                            [headers] => Array
                                (
                                    [x-amzn-requestid] => 6f678823-868b-444a-b945-9e7a6a8ad800
                                    [content-type] => text/xml
                                    [content-length] => 629
                                    [date] => Sat, 14 Nov 2020 14:39:06 GMT
                                )

                            [transferStats] => Array
                                (
                                    [http] => Array
                                        (
                                            [0] => Array
                                                (
                                                )

                                        )

                                )

                        )

                )

            [monitoringEvents:AwsResult:private] => Array
                (
                )

        )

    [sendingMailListId] => Array
        (
            [0] => 10055
            [1] => 10556
        )

)

In this, the sendingMailListId contains the ID that you send the ID to the data array, by which you can match the status from your response data and keep the response in the database as per your requirement.

Conclusion and Final Words

Bulk email template Through this, we can send different types of emails simultaneously, so that the performance of our application will be better and more resources of the application will not be used.

Here we had to create a template because we had to send different messages to each user. If you also have to send different emails according to different users, then you can use AWS SES in your application, where you will have to create bulk email template.