Saturday 24 August 2019

Send Email with Amazon SES



 This creates IAM user and credentials





Ten go to https://console.aws.amazon.com/iam/home?#/users  ans select specific user




you can view access key, you can also create new


again go to permission tab




add send email permission












Then go to code

first download AWS php sdk 

https://docs.aws.amazon.com/aws-sdk-php/v3/download/aws.zip

this will have autoloader just call that


require_once 'aws/aws-autoloader.php';

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


$SesClient = new SesClient([
    'region' => 'us-west-2',
    'version' => '2010-12-01',
    'credentials' => [
        'key' => 'key from smtp credential key',
        'secret' => 'pasword'
  ]
]);

$sender_email = 'gunabalans@gmail.com';
$recipient_emails = ['gunabalans@yahoo.com', 'gunabalans@gmail.com'];


$subject = 'Amazon SES test (AWS SDK for PHP)';
$plaintext_body = 'This email was sent with Amazon SES using the AWS SDK for PHP.' ;
$html_body =  '<h1>AWS Amazon Simple Email Service Test Email</h1>'.
              '<p>This email was sent with <a href="https://aws.amazon.com/ses/">'.
              'Amazon SES</a> using the <a href="https://aws.amazon.com/sdk-for-php/">'.
              'AWS SDK for PHP</a>.</p>';
$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,
          ],
        ],

       
    ]);
   
   

   
    $messageId = $result['MessageId'];
   
   
    echo("Email sent! Message ID: $messageId"."\n");
} catch (AwsException $e) {
    // output error message if fails
    //echo $e->getMessage();
    echo("The email was not sent. Error message: ".$e->getAwsErrorMessage()."\n");
    echo "\n";
}





4 comments:

  1. Sender email 'Source' => $sender_email,


    cant be a yahoo mail - throws error

    ReplyDelete
  2. $SesClient = new SesClient([
    'region' => 'us-west-2',
    'version' => '2010-12-01',
    'credentials' => [
    'key' => 'key from smtp credential key',
    'secret' => 'pasword'
    ]
    ]);


    HERE

    'version' => '2010-12-01',
    is from

    https://docs.aws.amazon.com/aws-sdk-php/v3/api/index.html

    ReplyDelete
  3. us-west-2 - this is hosted region

    ReplyDelete
  4. domain and from email need to be verified with AWS


    AWS SES Home

    ReplyDelete