PHPackages                             creativecrafts/php-aws-send-email - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Mail &amp; Notifications](/categories/mail)
4. /
5. creativecrafts/php-aws-send-email

ActiveLibrary[Mail &amp; Notifications](/categories/mail)

creativecrafts/php-aws-send-email
=================================

This is a handy package the can send email via AWS SES

1.22.0(1y ago)21.9k↓33.3%[2 PRs](https://github.com/CreativeCrafts/php-aws-send-email/pulls)MITPHPPHP ^8.2CI passing

Since Nov 22Pushed 1y ago1 watchersCompare

[ Source](https://github.com/CreativeCrafts/php-aws-send-email)[ Packagist](https://packagist.org/packages/creativecrafts/php-aws-send-email)[ Docs](https://github.com/creativecrafts/php-aws-send-email)[ GitHub Sponsors](https://github.com/CreativeCrafts)[ RSS](/packages/creativecrafts-php-aws-send-email/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (13)Versions (38)Used By (0)

PHP AWS Send Email
==================

[](#php-aws-send-email)

[![Latest Version on Packagist](https://camo.githubusercontent.com/02e4cb98951b2fc25528ae122576a5481e46677eb27c14138764644a829d859f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f63726561746976656372616674732f7068702d6177732d73656e642d656d61696c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/creativecrafts/php-aws-send-email)[![Tests](https://camo.githubusercontent.com/9924df14d531f65aa97f8aea2f9a000673b87341a74f2848cf21e3ae5fd2a829/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f63726561746976656372616674732f7068702d6177732d73656e642d656d61696c2f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/creativecrafts/php-aws-send-email/actions/workflows/run-tests.yml)[![Total Downloads](https://camo.githubusercontent.com/9e50d0bf05bf683f74ac86e9f8c04e8c58ee6525dcf906d6e6bb3b557c92c6c6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f63726561746976656372616674732f7068702d6177732d73656e642d656d61696c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/creativecrafts/php-aws-send-email)

A powerful and flexible PHP package for sending emails via Amazon SES (Simple Email Service) with advanced features including templating, attachments, logging, and rate limiting. This package is designed to simplify email operations while providing robust controls and customization options.

Features
--------

[](#features)

- **Send Emails Using Amazon SES:** Leverage the scalability and reliability of AWS SES to send your emails.
- **Advanced Templating:** Utilize both Simple and Advanced template engines for dynamic and reusable email content.
- **Attachments Support:** Easily attach multiple files (PDFs, images, etc.) to your emails.
- **Logging Capabilities:** Track email operations with integrated logging for monitoring and troubleshooting.
- **Rate Limiting:** Control email sending frequency with In-Memory and Redis-based rate limiters.
- **Asynchronous Sending:** Improve application performance by sending emails asynchronously.
- **Partial Rendering:** Include shared components across multiple templates without compromising security.
- **Secure Variable Handling:** Avoid security vulnerabilities.

These features cater to a wide range of email sending needs, from simple transactional emails to complex, templated marketing campaigns with attachments.

Installation
------------

[](#installation)

You can install the package via Composer:

```
composer require creativecrafts/php-aws-send-email
```

Ensure you have Composer installed on your system before running this command. This package requires PHP 8.2 or higher.

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

The EmailService class is the core of this package, providing a simple interface to send emails via Amazon SES.

```
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('sender@example.com')
        ->setRecipientEmail('recipient@example.com')
        ->setSubject('Test Email')
        ->setBodyText('This is a test email.')
        ->sendEmail();

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

Use this for sending transactional emails, notifications, or any automated email communication. Remember to handle exceptions that might occur during the sending process.

### Using Optional Features

[](#using-optional-features)

This package offers additional features to enhance your email sending capabilities. By leveraging a logger, rate limiter, and template engine, you can create a more robust and flexible email service.

```
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('sender@example.com')
        ->setRecipientEmail('recipient@example.com')
        ->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();
}
```

By incorporating these optional features, you can log email activities, control sending rates, and use templates for consistent and dynamic email content. This approach is particularly useful for applications that send a high volume of emails or require detailed tracking and control over the email sending process.

### Advanced Usage

[](#advanced-usage)

The EmailService class provides advanced features to handle more complex email sending scenarios. Here are some examples of how you can leverage these capabilities:

#### Sending Emails with Attachments

[](#sending-emails-with-attachments)

You can easily add file attachments to your emails using the `addAttachment method`. This is useful for sending documents, images, or any other files along with your email content. To send emails with multiple attachments seamlessly, follow these steps:

1. Initialize the EmailService with Optional Features:

```
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);
```

2. Prepare the Email Data and Add Attachments:

```
// 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');
```

3. Send the Email:

```
