PHP code example of creativecrafts / php-aws-send-email

1. Go to this page and download the library: Download creativecrafts/php-aws-send-email library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

creativecrafts / php-aws-send-email example snippets


use Aws\Ses\SesClient;
use CreativeCrafts\EmailService\Services\EmailService;

// Initialize the SES client
$sesClient = new SesClient([
    'version' => 'latest',
    'region'  => 'us-west-2',
    // Uncomment and fill in your AWS credentials if not using environment variables or IAM roles (Not Recommended)
    /*
    'credentials' => [
        'key'    => 'YOUR_AWS_ACCESS_KEY_ID',
        'secret' => 'YOUR_AWS_SECRET_ACCESS_KEY',
    ],
    */
]);

// Initialize the EmailService without optional features
$emailService = new EmailService($sesClient);

// Send a simple email
try {
    $emailService->setSenderEmail('[email protected]')
        ->setRecipientEmail('[email protected]')
        ->setSubject('Test Email')
        ->setBodyText('This is a test email.')
        ->sendEmail();

    echo "Email sent successfully!";
} catch (Exception $e) {
    echo "Error sending email: " . $e->getMessage();
}

use Aws\Ses\SesClient;
use CreativeCrafts\EmailService\Services\EmailService;
use Psr\Log\LoggerInterface;
use CreativeCrafts\EmailService\Interfaces\RateLimiterInterface;
use CreativeCrafts\EmailService\Interfaces\TemplateEngineInterface;

// Initialize the SES client
$sesClient = new SesClient([
    'version' => 'latest',
    'region'  => 'us-west-2',
    // Uncomment and fill in your AWS credentials if not using environment variables or IAM roles (Not Recommended)
    /*
    'credentials' => [
        'key'    => 'YOUR_AWS_ACCESS_KEY_ID',
        'secret' => 'YOUR_AWS_SECRET_ACCESS_KEY',
    ],
    */
]);

// Initialize Logger, RateLimiter, and TemplateEngine (implement these interfaces as needed)
$logger = new YourLoggerImplementation();
$rateLimiter = new YourRateLimiterImplementation();
$templateEngine = new YourTemplateEngineImplementation();

// Create the EmailService with optional features
$emailService = new EmailService($sesClient, $logger, $rateLimiter, $templateEngine);

// Send a templated email
try {
    $emailService->setSenderEmail('[email protected]')
        ->setRecipientEmail('[email protected]')
        ->setSenderName('Sender Name')
        ->setSubject('Welcome to Our Service')
        ->setEmailTemplate('welcome', ['name' => 'John Doe'])
        ->sendEmail();

    echo "Templated email sent successfully!";
} catch (Exception $e) {
    echo "Error sending templated email: " . $e->getMessage();
}

use Aws\Ses\SesClient;
use CreativeCrafts\EmailService\Services\EmailService;
use CreativeCrafts\EmailService\Services\Templates\Engines\AdvancedTemplateEngine;
use CreativeCrafts\EmailService\Services\Logger\Logger;

// Initialize the SES client
$sesClient = new SesClient([
    'version' => 'latest',
    'region'  => 'us-west-2',
]);

// Initialize the Logger
$logger = new Logger('/path/to/your/email.log');

// Initialize the AdvancedTemplateEngine with global variables
$templateEngine = new AdvancedTemplateEngine(
    '/path/to/templates',
    '/path/to/partials',
    'phtml',
    [
        'baseLight' => '#ed8b00',
        'baseMid'   => '#ed8b00',
        'baseDark'  => '#ed8b00',
        'greyLight' => '#dedede',
        'greyMid'   => '#bcbcbc',
        'greyDark'  => '#555555',
        'white'     => '#ffffff',
    ]
);

// Create the EmailService with the Logger and TemplateEngine
$emailService = new EmailService($sesClient, $logger, null, $templateEngine);
 
// Prepare email data with variables for the template
$emailData = [
    'etemplateheader' => 'Hej Jane Doe,', // Example header
    'etemplate' => "This is the sample content of the email template",
    'companydata' => [
        'name' => 'Your Company',
        'address' => '1234 Street Name',
        'areacode' => '12345',
        'city' => 'CityName',
        'country' => 'CountryName',
    ],
    'testid' => '136277',
];

// Add attachments
$emailService->addAttachment('/path/to/invoice.pdf')
    ->addAttachment('/path/to/image.jpg');



try {
    $emailService->setSenderEmail('[email protected]')
        ->setRecipientEmail('[email protected]')
        ->setSenderName('Your Company')
        ->setSubject('Order confirmation')
        ->setEmailTemplate('send-test', $emailData)
        ->sendEmail();

    echo "Email with attachments sent successfully!";
} catch (Exception $e) {
    echo "Error sending email with attachments: " . $e->getMessage();
}



// Send the email asynchronously
$promise = $emailService->sendEmailAsync();

$promise->then(
    function ($result) {
        echo "Email sent! Message ID: " . $result['MessageId'];
    },
    function ($error) {
        echo "An error occurred: " . $error->getMessage();
    }
);

// Continue with other tasks while the email is being sent
echo "Email is being sent asynchronously.";

// Prepare email data with variables for the template
$emailData = [
    'etemplateheader' => 'Hej Jane Doe,', // Example header
    'etemplate' => "This is the sample content of the email template",
    'companydata' => [
        'name' => 'Your Company',
        'address' => '1234 Street Name',
        'areacode' => '12345',
        'city' => 'CityName',
        'country' => 'CountryName',
    ],
    'testid' => '136277',
];

// Add attachments
$emailService->addAttachment('/path/to/invoice.pdf')
    ->addAttachment('/path/to/image.jpg');

// Send the templated email with attachments
try {
    $emailService->setSenderEmail('[email protected]')
        ->setRecipientEmail('[email protected]')
        ->setSenderName('Your Company')
        ->setSubject('Order confirmation')
        ->setEmailTemplate('send-test', $emailData)
        ->sendEmail();

    echo "Email with attachments sent successfully!";
} catch (Exception $e) {
    echo "Error sending email with attachments: " . $e->getMessage();
}

use CreativeCrafts\EmailService\Services\Templates\Engines\SimpleTemplateEngine;

// Initialize the SimpleTemplateEngine
$templateEngine = new SimpleTemplateEngine('/path/to/templates');

// Load a simple template
$template = $templateEngine->load('welcome');

// Render the template with variables
$renderedContent = $template->render(['name' => 'John Doe']);

Hello {name},

Welcome to our service! We're glad to have you on board.

Best regards,
Your Company Name



use CreativeCrafts\EmailService\Services\Templates\Engines\AdvancedTemplateEngine;

// Initialize the AdvancedTemplateEngine with global variables
$templateEngine = new AdvancedTemplateEngine(
    '/path/to/templates',
    '/path/to/partials',
    'phtml',
    [
        'baseLight' => '#ed8b00',
        'baseMid'   => '#ed8b00',
        'baseDark'  => '#ed8b00',
        'greyLight' => '#dedede',
        'greyMid'   => '#bcbcbc',
        'greyDark'  => '#555555',
        'white'     => '#ffffff',
    ]
);

// Load an advanced template
$template = $templateEngine->load('order_confirmation');

// Render the template with variables
$renderedContent = $template->render([
    'user' => [
        'name' => 'John Doe',
        'email' => '[email protected]',
    ],
    'order' => [
        'id' => '12345',
        'items' => [
            ['name' => 'Product A', 'price' => 19.99],
            ['name' => 'Product B', 'price' => 29.99],
        ],
        'total' => 49.98,
    ],
]);

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Order Confirmation</title>
    <style>
        table, h1, h2, p { font-family: Helvetica, Arial, Sans-Serif; }
        p { margin-top: 3px; margin-bottom: 6px; }
        a:link { color: <?= $this->baseLight; 

return [
    'baseLight' => '#ed8b00',
    'baseMid'   => '#ed8b00',
    'baseDark'  => '#ed8b00',
    'greyLight' => '#dedede',
    'greyMid'   => '#bcbcbc',
    'greyDark'  => '#555555',
    'white'     => '#ffffff',
];


// send-test.phtml

<?= $this->partial('snipplet-email-header'); 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Email Header</title>
    <style>
        table, h1, h2, p { font-family: Helvetica, Arial, Sans-Serif; }
        p { margin-top: 3px; margin-bottom: 6px; }
        a:link { color: <?= $this->baseLight; 

use CreativeCrafts\EmailService\Services\Templates\Engines\SimpleTemplateEngine;

// Optionally, you can specify the file extension if your templates use a different extension. default is .html
$templateExtension = '.phtml';
$engine = new SimpleTemplateEngine('/path/to/templates', $templateExtension);
$template = $engine->load('welcome');
$renderedContent = $template->render(['name' => 'John']);

use Aws\Ses\SesClient;
use CreativeCrafts\EmailService\Services\EmailService;
use CreativeCrafts\EmailService\Services\Templates\Engines\SimpleTemplateEngine;

// Set up the SES client
$sesClient = new SesClient([
    'version' => 'latest',
    'region'  => 'us-west-2',
    // Uncomment and fill in your AWS credentials if not using environment variables or IAM roles
    /* 'credentials' => [
        'key'    => 'YOUR_AWS_ACCESS_KEY_ID',
        'secret' => 'YOUR_AWS_SECRET_ACCESS_KEY',
    ],*/
]);

// Set up the SimpleTemplateEngine
$templateEngine = new SimpleTemplateEngine('/path/to/your/templates');

// Create the EmailService with the SimpleTemplateEngine
$emailService = new EmailService($sesClient, null, null, $templateEngine);

// Prepare the email data
$emailData = [
    'name' => 'John Doe',
    'order_id' => '12345',
    'total' => 49.98,
    'items' => [
        ['name' => 'Product A', 'price' => 19.99],
        ['name' => 'Product B', 'price' => 29.99],
    ],
];

/ Prepare the item list
$itemList = '';
foreach ($emailData['items'] as $item) {
    $itemList .= "- {$item['name']}: $" . number_format($item['price'], 2) . "\n";
}

// Prepare the free shipping message
$freeShippingMessage = $emailData['total'] > 100 
    ? "As a valued customer spending over $100, you've earned free shipping on this order!"
    : "";

// Prepare the final email data
$finalEmailData = [
    'name' => $emailData['name'],
    'order_id' => $emailData['order_id'],
    'total' => number_format($emailData['total'], 2),
    'item_list' => $itemList,
    'free_shipping_message' => $freeShippingMessage,
];

// Send the email using a template
try {
    $emailService->setSenderEmail('[email protected]')
        ->setRecipientEmail('[email protected]')
        ->setSubject('Your Order Confirmation')
        ->setEmailTemplate('order_confirmation', $finalEmailData)
        ->sendEmail();

    echo "Email sent successfully!";
} catch (Exception $e) {
    echo "Error sending email: " . $e->getMessage();
}

// order_confirmation.html or order_confirmation.php or order_confirmation.phtml
Hello {name},

Thank you for your order! Your order (ID: {order_id}) has been confirmed.

Order Details:
{item_list}

Total: ${total}

{free_shipping_message}

If you have any questions about your order, please don't hesitate to contact us.

Best regards,
Your Company Name

namespace CreativeCrafts\EmailService\Services\Logger;

use Psr\Log\AbstractLogger;

class Logger extends AbstractLogger
{
    private string $logFile;

    /**
     * Constructor.
     *
     * @param string $logFile The path to the log file.
     */
    public function __construct(string $logFile)
    {
        $this->logFile = $logFile;
    }

    /**
     * Logs with an arbitrary level.
     *
     * @param mixed  $level
     * @param string|\Stringable  $message
     * @param array $context
     *
     * @return void
     */
    public function log($level, $message, array $context = []): void
    {
        $date = date('Y-m-d H:i:s');
        $contextString = json_encode($context);
        $logEntry = "[{$date}] {$level}: {$message} {$contextString}\n";
        file_put_contents($this->logFile, $logEntry, FILE_APPEND);
    }
}

use Aws\Ses\SesClient;
use CreativeCrafts\EmailService\Services\EmailService;
use CreativeCrafts\EmailService\Services\Logger\Logger;

// Initialize the SES client
$sesClient = new SesClient([
    'version' => 'latest',
    'region'  => 'us-west-2',
]);

// Initialize the Logger
$logger = new Logger('/path/to/your/email.log');

// Create the EmailService with the Logger
$emailService = new EmailService($sesClient, $logger);

// Prepare and send the email
try {
    $emailService->setSenderEmail('[email protected]')
        ->setRecipientEmail('[email protected]')
        ->setSenderName('Your Company')
        ->setSubject('Test Email with Logging')
        ->setBodyText('This is a test email sent with logging enabled.')
        ->sendEmail();

    // Log additional activities if needed
    $logger->info('Email sent successfully', [
        'messageId' => '1234567890',
        'to' => '[email protected]',
        'subject' => 'Test Email with Logging'
    ]);

    echo "Email sent successfully!";
} catch (Exception $e) {
    // Log the error
    $logger->error('Failed to send email', [
        'error' => $e->getMessage(),
        'to' => '[email protected]',
        'subject' => 'Test Email with Logging'
    ]);

    echo "Error sending email: " . $e->getMessage();
}

// Example of logging other email-related activities
$logger->info('Email queue processed', ['queueSize' => 10, 'processTime' => '2.5s']);
$logger->warning('Rate limit approaching', ['currentRate' => 95, 'limit' => 100]);
$logger->error('Failed to connect to email server', ['server' => 'smtp.example.com']);

use Aws\Ses\SesClient;
use CreativeCrafts\EmailService\Services\EmailService;
use CreativeCrafts\EmailService\Services\RateLimiter\InMemoryRateLimiter;

// Initialize the SES client
$sesClient = new SesClient([
    'version' => 'latest',
    'region'  => 'us-west-2',
]);

// Initialize the InMemoryRateLimiter
// This example sets a limit of 100 emails per hour
$rateLimiter = new InMemoryRateLimiter(100, 3600);

// Create the EmailService with the InMemoryRateLimiter
$emailService = new EmailService($sesClient, null, $rateLimiter);

// Prepare and send the email
try {
    $emailService->setSenderEmail('[email protected]')
        ->setRecipientEmail('[email protected]')
        ->setSenderName('Sender Name')
        ->setSubject('Test Email with Rate Limiting')
        ->setBodyText('This is a test email sent with rate limiting enabled.')
        ->sendEmail();

    echo "Email sent successfully!";
} catch (Exception $e) {
    echo "Error sending email: " . $e->getMessage();
}



use Aws\Ses\SesClient;
use CreativeCrafts\EmailService\Services\EmailService;
use CreativeCrafts\EmailService\Services\RateLimiter\RedisRateLimiter;
use Redis;

// Initialize the SES client
$sesClient = new SesClient([
    'version' => 'latest',
    'region'  => 'us-west-2',
]);

// Initialize Redis connection
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

// Initialize the RedisRateLimiter
// This example sets a limit of 100 emails per hour
$rateLimiter = new RedisRateLimiter($redis, 'email_rate_limit', 100, 3600);

// Create the EmailService with the RedisRateLimiter
$emailService = new EmailService($sesClient, null, $rateLimiter);

// Prepare and send the email
try {
    $emailService->setSenderEmail('[email protected]')
        ->setRecipientEmail('[email protected]')
        ->setSenderName('Sender Name')
        ->setSubject('Test Email with Redis Rate Limiting')
        ->setBodyText('This is a test email sent with Redis rate limiting enabled.')
        ->sendEmail();

    echo "Email sent successfully!";
} catch (Exception $e) {
    echo "Error sending email: " . $e->getMessage();
}