AWS SES Bulk Email: Send bulk email with AWS SES by PHP
AWS

AWS SES Bulk Email: Send bulk email with AWS SES by PHP

AWS SES Bulk Email: अगर आप email send करने के लिए AWS (Amazon Web Services) SES (Simple Email Service) का इस्तेमाल करते होंगे तो आपने शायद bulk email के बारे में सुना होगा| जैसे की अगर हमे बहुत सारे email एक साथ send करने हो तो हम CC (Carbon copy) field में बहुत सारे email को attach करके send कर सकते हैं|

लेकिन जब हमे अलग अलग email अलग अलग लोगो को एक साथ send करना हुआ तो क्या करेंगे? इस problem के solution के लिए AWS SES ने bulk email template की सुविधा प्रदान की है जिसके माध्यम से अलग अलग लोगो के पास unique मेल send कर सकते हैं|

AWS SES क्या है – What is AWS SES?

AWS का full फॉर्म Amazon web service होता है जिसका मतलब यह है की amazon के web application से related जितने भी services है वो AWS के category में आते हैं|

SES का full form होता है Simple Email Service. AWS email send करने की service भी provide करती है जिसके माध्यम से आप अपने application के द्वारा किसी को भी मेल send कर सकते हैं|

जैसे कई बार हमें अपने application से अपने customers को email के द्वारा किसी भी प्रकार की जानकारी जैसे Notice, Information, etc. भेजना हो तो हमे एक एक करके अलग से type ना करना पड़े| जैसे मान लीजिये आपके पास school की application है और आप चाहते हैं की जितने भी बच्चे हमारें स्कूल में हैं जिनका fee जमा नहीं है उन सब के parents को उसके total fee के साथ मेल चला जाये तो आप अपने application में bulk email की service add कर सकते हैं|

Template क्या होता है? Bulk email template क्या होता है?

AWS SES Bulk Email: Template एक predesigned file होता है जिसका इस्तेमाल किसी भी चीज को जल्दी से फॉर्मेट करने या बनाने के लिए किया जाता है| यहाँ भी template एक file होता है जो की AWS पर create होता है और वह यह बताता है की email को किस फॉर्मेट में भेजना है|

Bulk email template एक predesigned file होता है जिसका इस्तेमाल bulk email को send करने के लिए किया जाता है| Bulk का मतलब होता है बहुत सारा|

जैसे मान लीजिये आप कॉलेज में जाते हैं तो वहां आपको predesigned फॉर्म मिलता है जिसमे आपको form के अनुसार आपका data भरना होता है लेकिन सोचिये अगर form के जगह blank paper दे दिया जाये तो आप क्या करेंगे?

पहले तो यह सोचेंगे की इसमें क्या क्या लिखे और कैसे लिखें? दूसरा बात शायद लिखते समय कोई जानकारी इधर उधर हो जाये इसलिए template बनाया जाता है जो की कार्य को आसान कर देता है|

AWS SES Bulk Email: AWS SES में PHP के द्वारा bulk में email कैसे send करें?

अब हम PHP के द्वारा step by step bulk email create करने का process देखेंगे| हालाँकि मैंने आपके सुविधा के लिए bulk email के लिए एक library बना दी है जो की आपको implement करने में बहुत ही आसानी होगी|

इस tutorial को अपने project में implement करने से पहले मैं बता दूँ की आपके पास कुछ जानकारियाँ होनी चाहिए जो की इस प्रकार है:

  1. AWS console account
  2. Email service in your account
  3. Access key (AWS SES API जब आप purchase करेंगे तो ये जानकारी आपको मिलेगी)
  4. Secret key (AWS SES API जब आप purchase करेंगे तो ये जानकारी आपको मिलेगी)
  5. AWS region (आपके AWS account जिस region में setup है उसकी जानकारी जैसे की ap-south-1)
  6. AWS Version ( यह bydefault latest होता है लेकिन आप इसे अपने AWS version के हिसाब से set कर सकते हैं)
  7. AWS email from (वह email जो आपके AWS SES में setup है जिसके द्वारा user को मेल जायेगा)

Project में AWS SES bulk email service कैसे implement करें?

सबसे पहले आपको AWS का library download करना होगा| आप AWS की library इस page से download कर सकते हैं| (Click here to AWS SDK page)

अगर आपको ऊपर दिए गए link में कुछ समझ नही आ रहा है तो आप मेरे code से download कर सकते हैं जो की third_party folder के अन्दर पूरा setup मिल जायेगा| Github link

इसको project में copy paste करने के बाद दूसरा step होता है template create करना|

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

इसके बाद का step होता है bulk email destination create करना जो की निचे दिए गया फॉर्मेट होता है|

{
  "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\" }"
}

इसमें बताया गया है की multiple destinations कैसे create करना है| हो सकता है की यह देखने में आपको confusion लगे और समझ में ना आये इसलिए मैंने खुद का library create किया है जिसको आप अपने project में implement करके आसानी से इस्तेमाल कर सकते हैं|

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

ऊपर दिए गए file में मैंने सारा code जो हमें अपने अपने AWS account के अनुसार change करने है उसे constant file में रख दिया है ताकि आपको library में change करना ना पड़े|

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 Aws\Ses\SesClient;
use Aws\Exception\AwsException;

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;

आपको जितने भी changes करने हैं send_email file में ही करने है

  • इसमें सबसे पहले मैंने अपने library को include किया है|
  • एक बात का ध्यान रखना है की केवल 50 data ही एक बार में send करें अगर 50 से ज्यादा है तो आप array_chunks() का इस्तेमाल करके loop चला सकते हैं|
  • उसके बाद मैंने अपने bulk email data को array format में prepare किया है|
  • उसके बाद अपने library class का object बनाया है जिसके माध्यम से हम library के function को कॉल कर सकें|
  • उसके बाद मैंने checkBulkEmailTemplateExistsOnAws() function को कॉल किया है| यह function library में बना हुआ है जिसका काम होता है AWS पर template create करना लेकिन उससे पहले यह check करना की कही यह template already created तो नहीं है| अगर already created है तो वह नया template नहीं create करेगा जिससे की मेरा AWS का service ज्यादा उपयोग नही होगा|
  • उसके बाद मैंने sendEmail() function को कॉल किया है जिसमें array data को parameter के through pass किया है|

Note: इसमें जिस प्रकार data array को format किया गया है उसी प्रकार आप भी data भेजें तभी ये library कार्य करेगा|

अब आपको library के द्वारा response कुछ इस प्रकार का मिलेगा जिसके द्वारा आप ये जान सकते हैं की कितना email send success हुआ और कितना fail हुआ|

Array
(
    [response] => Aws\Result Object
        (
            [data:Aws\Result: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:Aws\Result:private] => Array
                (
                )

        )

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

)

इसमें sendingMailListId में वो id आता है जो आप data array में ID send करते हैं जिसके द्वारा आप अपने response data से status को match करके अपने अनुसार database में response रख सकते हैं|

Conclusion and Final Words

Bulk email template के द्वारा हम अलग अलग प्रकार के email एक साथ send कर सकते हैं जिससे हमारे application का performance भी बेहतर होगा और application का ज्यादा resources भी इस्तेमाल नहीं होंगे|

यहाँ पर हमें template इसलिए बनाना पड़ा क्योंकि हमें हर user को अलग अलग message send करने थें| अगर आपको भी अलग अलग user के अनुसार अलग अलग email send करना है तो आप अपने application में AWS SES का इस्तेमाल कर सकते हैं जहाँ पर आपको bulk email template create करना पड़ेगा|

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.