PHPackages                             aliobeidat/yii2-sendgrid - 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. aliobeidat/yii2-sendgrid

ActiveYii2-extension[Mail &amp; Notifications](/categories/mail)

aliobeidat/yii2-sendgrid
========================

Yii2 Mailer extension for SendGrid with batch mailing support. This extension is designed to replace them all! The only Yii2 SendGrid extension you will need!

0265PHP

Since Dec 1Pushed 3y ago1 watchersCompare

[ Source](https://github.com/AliObeidat/yii2-sendgrid)[ Packagist](https://packagist.org/packages/aliobeidat/yii2-sendgrid)[ RSS](/packages/aliobeidat-yii2-sendgrid/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

yii2-sendgrid
=============

[](#yii2-sendgrid)

Yii2 Mailer extension for SendGrid with batch mailing support. This extension is designed to replace them all! The only Yii2 SendGrid extension you will need!

---

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

[](#installation)

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

```
php composer.phar require --prefer-dist aliobeidat/yii2-sendgrid

```

or add

```
"aliobeidat/yii2-sendgrid": "dev-master"
```

to the require section of your application's `composer.json` file.

Then configure your `mailer` component in your `main-local.php` (advanced) or `web.php` (basic) like so:

```
'mailer' => [
    'class' => 'aliobeidat\sendgrid\Mailer',
    'viewPath' => '@common/mail',
    // send all mails to a file by default. You have to set
    // 'useFileTransport' to false and configure a transport
    // for the mailer to send real emails.
    'useFileTransport' => false,
    'apiKey' => '[YOUR_SENDGRID_API_KEY]',
],

```

Do not forget to replace `apiKey` with your SendGrid API key. It must have permissions to send emails.

Usage
-----

[](#usage)

### Single Mailing

[](#single-mailing)

```
$user = \common\models\User::find()->select(['id', 'username', 'email'])->where(['id' => 1])->one();

$mailer = Yii::$app->mailer;
$message = $mailer->compose()
    ->setTo([$user->email => $user->username])      // or just $user->email
    ->setFrom(['alerts@example.com' => 'Alerts'])
    ->setReplyTo('noreply@example.com')
    ->setSubject('Hey -username-, Read This Email')
    ->setHtmlBody('Dear -username-,My HTML message here')
    ->setTextBody('Dear -username-,\n\nMy Text message here')
    //->setTemplateId('1234')
    //->addSection('%section1%', 'This is my section1')
    //->addHeader('X-Track-UserType', 'admin')
    //->addHeader('X-Track-UID', Yii::$app->user->id)
    //->addCategory('tests')
    //->addCustomArg('test_arg', 'my custom arg')
    //->setSendAt(time() + (5 * 60))
    //->setBatchId(Yii::$app->mailer->createBatchId())
    //->setIpPoolName('7')
    //->attach(Yii::getAlias('@webroot/files/attachment.pdf'))
    ->addSubstitution('-username-', $user->username)
    ->send();

if ($message === true) {
    echo 'Success!';
    echo '' . print_r($mailer->getRawResponses(), true) . '';
} else {
    echo 'Error!';
    echo '' . print_r($mailer->getErrors(), true) . '';
}

```

### Batch Mailing

[](#batch-mailing)

If you want to send to multiple recipients, you need to use the below method to batch send.

```
$mailer = Yii::$app->mailer;
//$batchId = Yii::$app->mailer->createBatchId();
//$sendTime = time() + (5 * 60);      // 5 minutes from now

foreach (User::find()->select(['id', 'username', 'email'])->batch(500) as $users)
{

    $message = $mailer->compose()
        ->setFrom(['alerts@example.com' => 'Alerts'])
        ->setReplyTo('noreply@example.com')
        ->setSubject('Hey -username-, Read This Email')
        ->setHtmlBody('Dear -username-,My HTML message here')
        ->setTextBody('Dear -username-,\n\nMy Text message here');
        //->setTemplateId('1234')
        //->addSection('%section1%', 'This is my section1')
        //->addHeader('X-Track-UserType', 'admin')
        //->addHeader('X-Track-UID', Yii::$app->user->id)
        //->addCategory('tests')
        //->addCustomArg('test_arg', 'my custom arg')
        //->setSendAt($sendTime)
        //->setBatchId($batchId)
        //->setIpPoolName('7')
        //->attach(Yii::getAlias('@webroot/files/attachment.pdf'));

    foreach ( $users as $user )
    {
        // A Personalization Object Helper would be nice here...
        $personalization = [
            'to' => [$user->email => $user->username],      // or just `email@example.com`
            //'cc' => 'cc@example.com',
            //'bcc' => 'bcc@example.com',
            //'subject' => 'Hey -username-, Custom message for you!',
            //'headers' => [
            //    'X-Track-RecipId' => $user->id,
            //],
            'substitutions' => [
                '-username-' => $user->username,
            ],
            //'custom_args' => [
            //    'user_id' => $user->id,
            //    'type' => 'marketing',
            //],
            //'send_at' => $sendTime,
        ];
        $message->addPersonalization($personalization);
    }

    $result = $message->send();
}

if ($result === true) {
    echo 'Success!';
    echo '' . print_r($mailer->getRawResponses(), true) . '';
} else {
    echo 'Error!';
    echo '' . print_r($mailer->getErrors(), true) . '';
}

```

**NOTE:** SendGrid supports a max of 1,000 recipients. This is a total of the to, bcc, and cc addresses. I recommend using `500` for the batch size. This should be large enough to process thousands of emails efficiently without risking getting errors by accidentally breaking the 1,000 recipients rule. If you are not using any bcc or cc addresses, you *could* raise the batch number a little higher. Theoretically, you should be able to do 1,000 but I would probably max at 950 to leave some wiggle room.

---

TODO
----

[](#todo)

There are a few things left that I didn't get to:

- ASM
- mail\_settings
- tracking\_settings

I plan to get to them at a later date. Feel free to help out if you can :)

###  Health Score

17

—

LowBetter than 6% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity12

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity24

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/b700e42529c3906d7fb2b1e232825eb2273f7388af8adc3ad9713cfdb518a0df?d=identicon)[AliObeidat](/maintainers/AliObeidat)

---

Top Contributors

[![AliObeidat](https://avatars.githubusercontent.com/u/29369893?v=4)](https://github.com/AliObeidat "AliObeidat (9 commits)")

### Embed Badge

![Health badge](/badges/aliobeidat-yii2-sendgrid/health.svg)

```
[![Health](https://phpackages.com/badges/aliobeidat-yii2-sendgrid/health.svg)](https://phpackages.com/packages/aliobeidat-yii2-sendgrid)
```

###  Alternatives

[tijsverkoyen/css-to-inline-styles

CssToInlineStyles is a class that enables you to convert HTML-pages/files into HTML-pages/files with inline styles. This is very useful when you're sending emails.

5.8k505.3M227](/packages/tijsverkoyen-css-to-inline-styles)[minishlink/web-push

Web Push library for PHP

1.9k12.0M53](/packages/minishlink-web-push)[laravel-notification-channels/twilio

Provides Twilio notification channel for Laravel

2587.7M12](/packages/laravel-notification-channels-twilio)[spatie/url-signer

Generate a url with an expiration date and signature to prevent unauthorized access

4422.3M16](/packages/spatie-url-signer)[mattketmo/email-checker

Throwaway email detection library

2742.0M5](/packages/mattketmo-email-checker)[laravel-notification-channels/discord

Laravel notification driver for Discord.

2371.3M11](/packages/laravel-notification-channels-discord)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
