Coder Social home page Coder Social logo

laravel-sendgrid-driver's Introduction

Laravel SendGrid Driver

SymfonyInsight Build Status

A Mail Driver with support for Sendgrid Web API, using the original Laravel API. This library extends the original Laravel classes, so it uses exactly the same methods.

To use this package required your Sendgrid Api Key. Please make it Here.

Compatibility

Laravel laravel-sendgrid-driver
9, 10, 11 ^4.0
7, 8 ^3.0
5, 6 ^2.0

Install (for Laravel)

Add the package to your composer.json and run composer update.

"require": {
    "s-ichikawa/laravel-sendgrid-driver": "^4.0"
},

or installed with composer

$ composer require s-ichikawa/laravel-sendgrid-driver

Install (for Lumen)

Add the package to your composer.json and run composer update.

"require": {
    "s-ichikawa/laravel-sendgrid-driver": "^4.0"
},

or installed with composer

$ composer require "s-ichikawa/laravel-sendgrid-driver"

Add the sendgrid service provider in bootstrap/app.php

$app->configure('mail');
$app->configure('services');
$app->register(Sichikawa\LaravelSendgridDriver\MailServiceProvider::class);

unset($app->availableBindings['mailer']);

Create mail config files. config/mail.php

<?php
return [
    'driver' => env('MAIL_DRIVER', 'sendgrid'),
];

Configure

.env

MAIL_DRIVER=sendgrid
SENDGRID_API_KEY='YOUR_SENDGRID_API_KEY'
# Optional: for 7+ laravel projects
MAIL_MAILER=sendgrid 

config/services.php (In using lumen, require creating config directory and file.)

    'sendgrid' => [
        'api_key' => env('SENDGRID_API_KEY'),
    ],

config/mail.php

    'mailers' => [
        'sendgrid' => [
            'transport' => 'sendgrid',
        ],
    ],

endpoint config

If you need to set custom endpoint, you can set any endpoint by using endpoint key. For example, calls to SendGrid API through a proxy, call endpoint for confirming a request.

    'sendgrid' => [
        'api_key' => env('SENDGRID_API_KEY'),
        'endpoint' => 'https://custom.example.com/send',
    ],

How to use

Every request made to /v3/mail/send will require a request body formatted in JSON containing your email’s content and metadata. Required parameters are set by Laravel's usually mail sending, but you can also use useful features like "categories" and "send_at".

more info https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html#-Request-Body-Parameters

Laravel 10, 11:

<?
use Sichikawa\LaravelSendgridDriver\SendGrid;

class SendGridSample extends Mailable
{
    use SendGrid;
    
    public function envelope(): Envelope
    {
        $this->sendgrid([
                'personalizations' => [
                    [
                        'to' => [
                            ['email' => '[email protected]', 'name' => 'to1'],
                            ['email' => '[email protected]', 'name' => 'to2'],
                        ],
                        'cc' => [
                            ['email' => '[email protected]', 'name' => 'cc1'],
                            ['email' => '[email protected]', 'name' => 'cc2'],
                        ],
                        'bcc' => [
                            ['email' => '[email protected]', 'name' => 'bcc1'],
                            ['email' => '[email protected]', 'name' => 'bcc2'],
                        ],
                    ],
                ],
                'categories' => ['user_group1'],
            ]);
        return new Envelope(
            from:    '[email protected]',
            replyTo: '[email protected]',
            subject: 'example',
        );
    }
}

Laravel 9:

<?
use Sichikawa\LaravelSendgridDriver\SendGrid;

class SendGridSample extends Mailable
{
    use SendGrid;
    
    public function build():
    {
        return $this
            ->view('template name')
            ->subject('subject')
            ->from('[email protected]')
            ->to(['[email protected]'])
            ->sendgrid([
                'personalizations' => [
                    [
                        'to' => [
                            ['email' => '[email protected]', 'name' => 'to1'],
                            ['email' => '[email protected]', 'name' => 'to2'],
                        ],
                        'cc' => [
                            ['email' => '[email protected]', 'name' => 'cc1'],
                            ['email' => '[email protected]', 'name' => 'cc2'],
                        ],
                        'bcc' => [
                            ['email' => '[email protected]', 'name' => 'bcc1'],
                            ['email' => '[email protected]', 'name' => 'bcc2'],
                        ],
                    ],
                ],
                'categories' => ['user_group1'],
            ]);
    }
}

Using Template Id

Illuminate\Mailer has generally required a view file. But in case of using template id, set an empty array at view function.

Laravel 10, 11:

<?
    public function envelope(): Envelope
    {
        $this->sendgrid([
            'personalizations' => [
                [
                    'dynamic_template_data' => [
                        'title' => 'Subject',
                        'name'  => 's-ichikawa',
                    ],
                ],
            ],
            'template_id' => config('services.sendgrid.templates.dynamic_template_id'),
        ]);
        return new Envelope(
            from:    '[email protected]',
            replyTo: '[email protected]',
            subject: 'example',
        );
    }

Laravel 9:

<?
    public function build():
    {
        return $this
            ->view('template name')
            ->subject('subject')
            ->from('[email protected]')
            ->to(['[email protected]'])
            ->sendgrid([
                'personalizations' => [
                    [
                        'dynamic_template_data' => [
                            'title' => 'Subject',
                            'name'  => 's-ichikawa',
                        ],
                    ],
                ],
                'template_id' => config('services.sendgrid.templates.dynamic_template_id'),
            ]);
    }

laravel-sendgrid-driver's People

Contributors

amouillard avatar daisuke-fukuda avatar dmytro-skelia avatar elidrake avatar felipehertzer avatar foo99 avatar gableroux avatar gstpereira avatar iandenh avatar jasonlbeggs avatar johnpbloch avatar l-alexandrov avatar lavatoaster avatar matt-allan avatar parkourben99 avatar robertoandres24 avatar roerjo avatar s-ichikawa avatar sonnysantino avatar szepeviktor avatar vrajroham avatar ziming avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-sendgrid-driver's Issues

ErrorException: Undefined index: api_key

Undefined index: api_key in /home/vagrant/www/auth-server.dev/vendor/s-ichikawa/laravel-sendgrid-driver/src/SendgridTransportServiceProvider.php:35

Parts of my .env

SENDGRID_API_KEY='XXX'

My bootstrap/app.php

<?php

require_once __DIR__ . '/../vendor/autoload.php';

try {
    (new Dotenv\Dotenv(__DIR__ . '/../'))->load();
} catch (Dotenv\Exception\InvalidPathException $e) {
    //
}

/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/

$app = new Laravel\Lumen\Application(
    realpath(__DIR__ . '/../')
);

$app->withFacades();
$app->withEloquent();

/*
|--------------------------------------------------------------------------
| Register Container Bindings
|--------------------------------------------------------------------------
|
| Now we will register a few bindings in the service container. We will
| register the exception handler and the console kernel. You may add
| your own bindings here if you like or you can make another file.
|
*/

$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);

$app->singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);

/*
|--------------------------------------------------------------------------
| Register Middleware
|--------------------------------------------------------------------------
|
| Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a
| route or middleware that'll be assigned to some specific routes.
|
*/
$app->middleware([
    App\Http\Middleware\CaptureJsonInput::class,
    App\Http\Middleware\ThrottleRequests::class,
    \Barryvdh\Cors\HandleCors::class,
]);


/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application's service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not required to uncomment this line.
|
*/

$app->register(\Barryvdh\Cors\LumenServiceProvider::class);
$app->register(App\Providers\AppServiceProvider::class);

/*
|--------------------------------------------------------------------------
| Register Configuration Files
|--------------------------------------------------------------------------
*/
$app->configure('cors');

/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| Next we will include the routes file so that they can all be added to
| the application. This will provide all of the URLs the application
| can respond to, as well as the controllers that may handle them.
|
*/

$app->group(['namespace' => 'App\Http\Controllers'], function ($app) {
    require __DIR__ . '/../app/Http/routes.php';
});

$app->configure('mail');
$app->configure('services');
$app->register(Sichikawa\LaravelSendgridDriver\MailServiceProvider::class);

unset($app->availableBindings['mailer']);

return $app;

The code that triggers it:

        Mail::send('view', [], function (Message $message) {
            $message
              ->to('[email protected]', 'Robin Ebers')
              ->from('[email protected]', 'SamKnows.com')
              ->embedData([
//                'categories' => ['user_group1'],
//                'send_at'    => $send_at->getTimestamp(),
              ], 'sendgrid/x-smtpapi');
        });

What am I doing wrong?

undefined method App\Mail\SendTwenty::sendgrid()

I've been gettting this error

undefined method App\Mail\SendTwenty::sendgrid()

currently I'm just doing this:

public function build() { return $this->from($this->domain_data[0]->email) ->subject("Your report is ready!") ->view('emails.twentyemail') ->sendgrid(['custom_args' => ['user_id' => $this->car_data[0]->id]]); }

Now I'm not sure where I went wrong, I've followed the installation process but doesn't seem like it's working for some reason.

Attachments with api, Use in Mailable

I have ^1.2 set-up for a Laravel 5.4 app.

One thing that doesn't work are the attachments. This is the code:

return $this->from($this->fromEmail, $this->fromName)
          ->view('emails.attend-notification')
          ->with([
                'firstname' => $this->attendee->firstname,
                 'lastname' => $this->attendee->lastname,
                 'attendeeTickets' => $this->attendeeTickets,
             ])
          ->attachData($pdfData, $filename, [
                   'mime' => 'application/pdf',
            ])
           ->subject('subject')
           ->sendgrid([
                   'categories'  => ['pierrot'],
                    'unique_args' => [
                           'id'    =>  '123456789',
                           "section"       => "attendee_mail",
                   ]
          ]);

With MAIL_DRIVER=sendgrid it doesn't send the attachment,
With MAIL_DRIVER=smtp it doesn't send the unique_args

No errors in the logs...

SendGrid Categories: base64_encode() expects parameter 1 to be string, array given

public function build()
    {
        return $this
            ->view('mail.notifications.userassigned')
            ->subject('New task assigned')
            ->sendgrid([
                'categories' => [
                    env('SENDGRID_CATEGORY')
                ],
            ]);
    }

C:\inetpub\wwwroot\laravel\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Encoder\Base64Encoder.php

/**
  * Takes an unencoded string and produces a Base64 encoded string from it.
  *
  * Base64 encoded strings have a maximum line length of 76 characters.
  * If the first line needs to be shorter, indicate the difference with
  * $firstLineOffset.
  *
  * @param string $string          to encode
  * @param int    $firstLineOffset
  * @param int    $maxLineLength   optional, 0 indicates the default of 76 bytes
  *
  * @return string
  */
 public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0)
 {
     if (0 >= $maxLineLength || 76 < $maxLineLength) {
         $maxLineLength = 76;
     }

     $encodedString = base64_encode($string);
     $firstLine = '';

     if (0 != $firstLineOffset) {
         $firstLine = substr(
             $encodedString, 0, $maxLineLength - $firstLineOffset
             )."\r\n";
         $encodedString = substr(
             $encodedString, $maxLineLength - $firstLineOffset
             );
     }

     return $firstLine.trim(chunk_split($encodedString, $maxLineLength, "\r\n"));
 }

 /**
  * Does nothing.
  */
 public function charsetChanged($charset)
 {
 }

Arguments
array:1 [▼
"categories" => array:1 [▼
0 => "xxxxxx"
]
]`

Not check has driver is sendgrid

In local/development enviorment general using other way to send mail, for example https://mailtrap.io and install this package and using sendgrid method has a error:

[ErrorException]
  base64_encode() expects parameter 1 to be string, array given

Not able to send attachment with email.

Using extension on with laravel 5.2 and sendgrid free account.
Is there any example to send email with attachment using this extension.
Currently, sendgrid email service is working without attachment.

cannot install sendgrid driver v2 for laravel 5.4

I got errors below
Problem 1
- Conclusion: remove laravel/framework v5.4.36
- Conclusion: don't install laravel/framework v5.4.36
- s-ichikawa/laravel-sendgrid-driver 2.0.0 requires illuminate/mail ~5.5 -> satisfiable by illuminate/mail[v5.5.0, v5.5.16, v5.5.17, v5.5.2].
- s-ichikawa/laravel-sendgrid-driver 2.0.1 requires illuminate/mail ~5.5 -> satisfiable by illuminate/mail[v5.5.0, v5.5.16, v5.5.17, v5.5.2].
- don't install illuminate/mail v5.5.0|don't install laravel/framework v5.4.36
- don't install illuminate/mail v5.5.16|don't install laravel/framework v5.4.36
- don't install illuminate/mail v5.5.17|don't install laravel/framework v5.4.36
- don't install illuminate/mail v5.5.2|don't install laravel/framework v5.4.36
- Installation request for laravel/framework (locked at v5.4.36, required as 5.4.*) -> satisfiable by laravel/framework[v5.4.36].
- Installation request for s-ichikawa/laravel-sendgrid-driver ^2.0 -> satisfiable by s-ichikawa/laravel-sendgrid-driver[2.0.0, 2.0.1].

Method [embedData] does not exist on mailable.

Hi folks this driver is not compatible using the Mailable Method in Laravel 5.3 (see docs here)

The Laravel method uses its own build function which doesn't support the embedData.

Might be worth mentioning in the docs, or considering refactoring to extend the Mailable class?

ErrorException in LogTransport.php when using log driver in development

I want to use the log mail driver in development stage. I work with transactional email templates so i have to use the embedData array to include the template id.
When changing the mail driver to 'log' you get: Array to string conversion, ErrorException in LogTransport.php

My function

    Mail::raw('Test email', function ($message) {
        $message
            ->from('email', 'company | customer support')
            ->to('email', 'name')
            ->embedData([
                'template_id' => '485600a2-f7eb-41a2-a597-xxxxxxx',
            ],  'sendgrid/x-smtpapi');
    });

Full print laravel error

ErrorException in LogTransport.php line 47:
Array to string conversion

in LogTransport.php line 47
at HandleExceptions->handleError('8', 'Array to string conversion', '/home/vagrant/Httpdocs/ac-laravel/vendor/laravel/framework/src/Illuminate/Mail/Transport/LogTransport.php', '47', array('entity' => object(Swift_Image))) in LogTransport.php line 47
at LogTransport->getMimeEntityString(object(Swift_Image)) in LogTransport.php line 50
at LogTransport->getMimeEntityString(object(Swift_Message)) in LogTransport.php line 36
at LogTransport->send(object(Swift_Message), array()) in Mailer.php line 85
at Swift_Mailer->send(object(Swift_Message), array()) in Mailer.php line 385
at Mailer->sendSwiftMessage(object(Swift_Message)) in Mailer.php line 171
at Mailer->send(array('raw' => 'Test email'), array(), object(Closure)) in Mailer.php line 125
at Mailer->raw('Test email', object(Closure)) in Facade.php line 219
at Facade::__callStatic('raw', array('Test email', object(Closure))) in UserController.php line 185
at Mail::raw('Test email', object(Closure)) in UserController.php line 185
at UserController->testEmail()
at call_user_func_array(array(object(UserController), 'testEmail'), array()) in Controller.php line 80
at Controller->callAction('testEmail', array()) in ControllerDispatcher.php line 146
at ControllerDispatcher->call(object(UserController), object(Route), 'testEmail') in ControllerDispatcher.php line 94
at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 96
at ControllerDispatcher->callWithinStack(object(UserController), object(Route), object(Request), 'testEmail') in ControllerDispatcher.php line 54
at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\UserController', 'testEmail') in Route.php line 174
at Route->runController(object(Request)) in Route.php line 140
at Route->run(object(Request)) in Router.php line 724
at Router->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in HandleCors.php line 34
at HandleCors->handle(object(Request), object(Closure))
at call_user_func_array(array(object(HandleCors), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Router.php line 726
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 699
at Router->dispatchToRoute(object(Request)) in Router.php line 675
at Router->dispatch(object(Request)) in Kernel.php line 246
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103

400 Bad Request When Template Id is Provided

If I leave my view empty I get the below error message even though I am using SendGrid's template system.

Client error: POST https://api.sendgrid.com/v3/mail/send resulted in a 400 Bad Request response:\n {"errors":[{"message":"The content value must be a string at least one character in length.","field":"content.0.value"," (truncated...)

The template has all the content / html for the email and therefore I do not need to generate any body from the Laravel view. How can this be achieved?

Here is a sample of my code:

`
namespace App\Mail;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Sichikawa\LaravelSendgridDriver\SendGrid;

class PasswordReset extends Mailable {

use Queueable, SerializesModels, SendGrid;

public $user;
public $password_reset_url;
public $body = '';
public $view = 'emails.body';

public function __construct( $user, $token ) {
	$this->user               = $user;
	$this->password_reset_url = url( config( 'app.url' ) . route( 'password.reset', $token, false ) );
}

public function build() {

	return $this
		->to( [ $this->user->email ] )
		->sendgrid( [
			'template_id'      => "xxxx-xxxx-xxxx-xxxx-xxxx",
			'personalizations' => [
				[
					'substitutions' => [
						'%username%'           => $this->user->username,
						'%password_reset_url%' => $this->password_reset_url
					]
				],
			],
		] );

}

}
`

If I do not specify any view I get the error message "Invalid View"

Note: View file body.blade.php is just {{ $body }}

Thanks for any help

Substitutions

Hi! Thank you very much for package. It's very useful for me. But I have detected, that substitutions key doesn't work. It doesn't included in personalizations before sending. Could you please help me with it? Thank you!

Expected: object, given: array when ->from() is not specified

I got this error when attempting to send an email.

[2019-04-16 13:21:58] development.ERROR: Client error: `POST https://api.sendgrid.com/v3/mail/send` resulted in a `400 Bad Request` response:
{"errors":[{"message":"Invalid type. Expected: object, given: array.","field":"from","help":"http://sendgrid.com/docs/AP (truncated...)
 {"userId":1,"exception":"[object] (GuzzleHttp\\Exception\\ClientException(code: 400): Client error: `POST https://api.sendgrid.com/v3/mail/send` resulted in a `400 Bad Request` response:
{\"errors\":[{\"message\":\"Invalid type. Expected: object, given: array.\",\"field\":\"from\",\"help\":\"http://sendgrid.com/docs/AP (truncated...)
 at /Users/seb/git/attendize/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113)
[stacktrace]
#0 /Users/seb/git/attendize/vendor/guzzlehttp/guzzle/src/Middleware.php(66): GuzzleHttp\\Exception\\RequestException::create(Object(GuzzleHttp\\Psr7\\Request), Object(GuzzleHttp\\Psr7\\Response))
#1 /Users/seb/git/attendize/vendor/guzzlehttp/promises/src/Promise.php(203): GuzzleHttp\\Middleware::GuzzleHttp\\{closure}(Object(GuzzleHttp\\Psr7\\Response))
#2 /Users/seb/git/attendize/vendor/guzzlehttp/promises/src/Promise.php(156): GuzzleHttp\\Promise\\Promise::callHandler(1, Object(GuzzleHttp\\Psr7\\Response), Array)
#3 /Users/seb/git/attendize/vendor/guzzlehttp/promises/src/TaskQueue.php(47): GuzzleHttp\\Promise\\Promise::GuzzleHttp\\Promise\\{closure}()
#4 /Users/seb/git/attendize/vendor/guzzlehttp/promises/src/Promise.php(246): GuzzleHttp\\Promise\\TaskQueue->run(true)
#5 /Users/seb/git/attendize/vendor/guzzlehttp/promises/src/Promise.php(223): GuzzleHttp\\Promise\\Promise->invokeWaitFn()
#6 /Users/seb/git/attendize/vendor/guzzlehttp/promises/src/Promise.php(267): GuzzleHttp\\Promise\\Promise->waitIfPending()
#7 /Users/seb/git/attendize/vendor/guzzlehttp/promises/src/Promise.php(225): GuzzleHttp\\Promise\\Promise->invokeWaitList()
#8 /Users/seb/git/attendize/vendor/guzzlehttp/promises/src/Promise.php(62): GuzzleHttp\\Promise\\Promise->waitIfPending()
#9 /Users/seb/git/attendize/vendor/guzzlehttp/guzzle/src/Client.php(131): GuzzleHttp\\Promise\\Promise->wait()
#10 /Users/seb/git/attendize/vendor/guzzlehttp/guzzle/src/Client.php(89): GuzzleHttp\\Client->request('post', 'https://api.sen...', Array)
#11 /Users/seb/git/attendize/vendor/s-ichikawa/laravel-sendgrid-driver/src/Transport/SendgridTransport.php(310): GuzzleHttp\\Client->__call('post', Array)
#12 /Users/seb/git/attendize/vendor/s-ichikawa/laravel-sendgrid-driver/src/Transport/SendgridTransport.php(76): Sichikawa\\LaravelSendgridDriver\\Transport\\SendgridTransport->post(Array)
#13 /Users/seb/git/attendize/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer.php(71): Sichikawa\\LaravelSendgridDriver\\Transport\\SendgridTransport->send(Object(Swift_Message), Array)
#14 /Users/seb/git/attendize/vendor/laravel/framework/src/Illuminate/Mail/Mailer.php(484): Swift_Mailer->send(Object(Swift_Message), Array)
#15 /Users/seb/git/attendize/vendor/laravel/framework/src/Illuminate/Mail/Mailer.php(259): Illuminate\\Mail\\Mailer->sendSwiftMessage(Object(Swift_Message))
#16 /Users/seb/git/attendize/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php(237): Illuminate\\Mail\\Mailer->send('Emails.inviteUs...', Array, Object(Closure))
#17 /Users/seb/git/attendize/app/Http/Controllers/ManageAccountController.php(204): Illuminate\\Support\\Facades\\Facade::__callStatic('send', Array)
#18 [internal function]: App\\Http\\Controllers\\ManageAccountController->postInviteUser()

Substitutions not working

Hi, I added custom substitution
'substitutions' => [
'{{name}}' => 'test_name',
'{{email}}' => 'test_email'
],

but only email substitution worked. Why ? I need to add some custom substitutions.

Can’t send text mail with embed categories.

Hi, I have a problem unable to send text mail with embed categories.

Laravel 5.5.45
s-ichikawa/laravel-sendgrid-driver 2.0.5

This code was sending a mail as "text/html" , not "text/plain"

Mail::send(['text' => 'emails.order_received'], $data, function ($message) use ($data) {
    $message->subject('Order received');
    $message->from('[email protected]');
    $message->to('[email protected]');

    $message->embedData([
        'categories' => ['Order'],
    ], 'sendgrid/x-smtpapi');
});

Here is a work-around. Set a additional parameter to set content type "text/plain".

Mail::send(['text' => 'emails.order_received'], $data, function ($message) use ($data) {
    $message->subject('Order received');
    $message->from('[email protected]');
    $message->to('[email protected]');

    $message->embedData([
        // In the case of using categories, set content type "text/plain" to avoid to be "text/html"
        'content' => [
            ['type' => 'text/plain', 'value' => $message->getBody()]
        ],
        'categories' => ['Order'],
    ], 'sendgrid/x-smtpapi');
});

Apparently with embed data (categories etc.), $message->getContentType() is seem to be multipart/related.
https://github.com/s-ichikawa/laravel-sendgrid-driver/blob/master/src/Transport/SendgridTransport.php#L162

This is a reason. But, it's Swift_Mime_SimpleMessage behavior.
Sorry, I don't have a good pull request...

Cf. This is doesn't matter
#51

Laravel 5.4

I want to install laravel-sendgrid-driver on a Laravel 5.4 setup. What version of Laravel Sendgrid driver should i use or is there a way around?

abandon to support web API v2.

I think almost no one uses the v2 class.
so, I want to delete classes for v2 to keep more simple and be able to easy supporting.

If there are no problems, I'm going to do it in this summer.
and this version will be 2.0.*.

Laravel send mail via v3 api

I have an "base64_encode() expects parameter 1 to be string, array given" error after using v3 example.

\Mail::send('view', [], function (Message $message) {
$message
->to('...')
->from('...')
->replyTo('...')
->embedData([
'personalizations' => [
[
'to' => [
'email' => '...',
'name' => '...',
],
'substitutions' => [
'-name-' => '...',
'-body-' => '...',
],
],
],
], 'sendgrid/x-smtpapi');
});
(... - replaced real data)

and i have set sendgrid array in config/services.php

'sendgrid' => [
'api_key' => env('SENDGRID_API_KEY'),
'version' => 'v3',
],
env file has api key.

Also i have follow installation of package for Laravel 5.1~

Please help.

Update:
Tryed same code with 5.1. version of laravel and it is working

Markdown update

In Laravel 5.3 you need to edit config/services.php and add the sendgrid service.

'sendgrid' => [ 'api_key' => env('SENDGRID_API_KEY'), ],

Cheers,
Chris

Laravel 5.5

Updating to laravel 5.5 brings new swiftmailer dependency 6.0< and brings error:

Declaration of Sichikawa\LaravelSendgridDriver\Transport\SendgridV3Transport::send(Swift_Mime_Message $message, &$failedRecipients = NULL) must be compatible with Swift_Transport::send(Swift_Mime_SimpleMessage $message, &$failedRecipients = NULL)

Laravel 5.4.23 - Mailable Categories not In Sendgrid

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.password')
		->subject('Password Reset Request')
		->sendgrid([
			'categories'=>['passwordReset']
		]);
    }

I am using the guide in the readme for attaching the Sendgrid trait, but I'm finding that the above code does not actually attach the category for viewing in Sendgrid - as in, after sending off one of these emails, it doesn't actually have the category attached to it in the Sendgrid interface.

I am using the V3 API.

cc and bcc not working

I'm using the following method to call the method to send an email.

Mail::to($request->email_address)->cc('[email protected]')->send(new EmailMessage($request));

The email is sent correctly, but cc or bcc it doesn't work. I also don't get any errors so its hard to debug.

Can anyone help me out here?

Spam Filter

The email I am trying to send using this driver always ended up in spam folder in Gmail ?

How to send SendGrid templates cleanly in Mailables

Hello,

Thanks for this package.

I am using SendGrid templates exclusively, so I do not need views to be stores locally. If I do not pass a view to a Mailable class, I get a InvalidArgumentException. What I did is create a view with a HTML comment in it, but it feels like a hack.

Questions :

  1. Any cleaner what to do this ?
  2. According to Laravel's documentation, any public property defined in a Mailable will automatically be made available to the view. Would it be possible to automatically apply this to personalizations as well ?

For reference, here's some sample code I have in the build method :

$template_data = [
    'template_id' => $this->template_id,
    'personalizations' => [[
        'dynamic_template_data' => [
            'first_name' => $this->user->getFirstName(),
            'action_url' => route('password.reset', [
                'email' => $this->user->email,
                'token' => $this->token
            ]),
            'support_url' => route('support')
        ]
    ]]
];
return $this->view('emails.empty')->sendgrid($template_data);

Call to undefined method Swift_Message::embedData()

Hi,

I am using laravel 5.3 - my code works perfectly when I don't have "embedData()" tag inside but throws an error "Call to undefined method Swift_Message::embedData()" when I add this tag.

Below code works perfectly:

        \Mail::send('emails.invoices.invoice_created', [], function (Message $message) {
            $message
                ->subject('test')
                ->to('[email protected]', 'foo_name')
                ->from('[email protected]', 'bar_name')
                ->setReplyTo('[email protected]', 'foobar')
        });

Below code doesn't work:

        \Mail::send('emails.invoices.invoice_created', [], function (Message $message) {
            $message
                ->subject('test')
                ->to('[email protected]', 'foo_name')
                ->from('[email protected]', 'bar_name')
                ->setReplyTo('[email protected]', 'foobar')
                ->embedData([
                    'personalizations' => [
                        [
                            'to' => [
                                'email' => '[email protected]',
                                'name' => 'user1',
                            ],
                            'substitutions' => [
                                '-email-' => '[email protected]',
                            ],
                        ],
                        [
                            'to' => [
                                'email' => '[email protected]',
                                'name' => 'user2',
                            ],
                            'substitutions' => [
                                '-email-' => '[email protected]',
                            ],
                        ],
                    ],
                    'categories' => ['user_group1'],
                    'custom_args' => [
                        'user_id' => "123" // Make sure this is a string value
                    ]
                ], 'sendgrid/x-smtpapi');
        });

am I missing something?

Make the API base URI configurable

Hi There

https://github.com/s-ichikawa/laravel-sendgrid-driver/blob/master/src/Transport/SendgridTransport.php#L308 hardcodes the Sendgrid API. We are running this on Kubernetes nodes which have ephemeral IPs and IP whitelisting on our Sendgrid account.

As such we need to proxy calls to sendgrid through a proxy with a static IP. This is not possible however as the base URI is hard coded. If it were configurable we could use a proxy passthrough.

Incidentally there is a BASE_URL constant that appears not to be used.

Using log mail driver and embedding data in message results in Exception: Array to string conversion

Laravel 5.2

When setting the mail driver to 'log' and trying to send a mail that has embedded data like this:

$message->embedData([
                    'to' => $recipients,
                    'sub' => [
                        '-email-' => $recipients,
                    ],
                    'category' => ($this->test == true) ? Category::MAIL_CAMPAIGN_TEST : Category::MAIL_CAMPAIGN,
                    'unique_args' => [
                        'campaign_id' => $campaign->getId(),
                        'environment' => app('env'),
                    ]
                ], 'sendgrid/x-smtpapi');

There is an exception "Array to string conversion"

93. Illuminate\Foundation\Bootstrap\HandleExceptions->handleError() ==> new ErrorException(): {}
92. Illuminate\Mail\Transport\LogTransport->getMimeEntityString() ==> Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(): {}
91. Illuminate\Mail\Transport\LogTransport->getMimeEntityString() ==> Illuminate\Mail\Transport\LogTransport->getMimeEntityString(): {}
90. Illuminate\Mail\Transport\LogTransport->send() ==> Illuminate\Mail\Transport\LogTransport->getMimeEntityString(): {}
89. Swift_Mailer->send() ==> Illuminate\Mail\Transport\LogTransport->send(): {}
88. Illuminate\Mail\Mailer->sendSwiftMessage() ==> Swift_Mailer->send(): {}
87. Illuminate\Mail\Mailer->send() ==> Illuminate\Mail\Mailer->sendSwiftMessage(): {}
86. Illuminate\Mail\Mailer->raw() ==> Illuminate\Mail\Mailer->send(): {}

how to use transactional template in laravel

Hi first of all very nice plugin for use really very thankful for your efforts
i am facing challenge to use transnational template which exist on send-grid dashboard i want to send email by using these templates .i have integrated this plugin and sending default email mechanism . but unable to send template email . that will be great if you share a sample payload or example if possible
below is my mailable code

public function build()
{
return $this
->view('email.testemail')
->subject('subject')
->from('[email protected]')
->to(['[email protected]'])
->sendgrid([
'personalizations' => [
[
'substitutions' => [
':myname' => 's-ichikawa',
],
'templates' =>[
'settings' =>[
'enable' =>1,
'template_id'=> "template_id"

                        ]
                    ]
                ],
            ],
        ]);

}

SendGrid template_id not working.

Hi, thanks for the great package,

I have some issues about using SendGrid templates. In another client, everything works fine.

{ "personalizations": [ { "to" : [ { "email" : "[email protected]", "name": "Valeh Asadli" } ], "dynamic_template_data": { "branch_name": "Galiano" } } ], "from": { "email" : "[email protected]", "name" : "Compass Travel" }, "template_id" : "temp_idxxx" }

this JSON totally working fine postman client, variable passed and I get an email.
But I facing this problem LARAVEL code.

Mail::send([], [], function (Message $message) { $message ->to($this->data['to']) ->from('[email protected]') ->subject('Invoice') ->embedData( json_encode([ 'personalizations' => [ [ 'dynamic_template_data' => [ 'branch_name' => 'amk', ], ], ], 'template_id' => 'xxxx', ]), SendgridTransport::SMTP_API_NAME ); });

I got an email but SMTP type file and JSON structure. How can I fix

JOB FILE:

`<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Message;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Mail;
//use App\Mail\SendReservationInvoice as SendReservationInvoiceMail;
use Sichikawa\LaravelSendgridDriver\SendGrid;
use Sichikawa\LaravelSendgridDriver\Transport\SendgridTransport;

class SendReservationInvoice implements ShouldQueue
{
private $data;

use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, SendGrid;

/**
 * SendReservationInvoice constructor.
 * @param array $data
 */
public function __construct(array $data)
{
    $this->data = $data;
}

/**
 * Execute the job.
 *
 * @return void
 */
public function handle(): void
{

// Mail::to($this->data['to'])
// ->send(new SendReservationInvoiceMail($this->data));

    Mail::send([], [], function (Message $message) {
        $message
            ->to($this->data['to'])
            ->from('[email protected]')
            ->subject('Invoice')
            ->embedData(
                json_encode([
                    'personalizations' => [
                        [
                            'dynamic_template_data' => [
                                'branch_name' => 'amk',
                            ],
                        ],
                    ],
                    'template_id' => 'xxxx',
                ]),
                SendgridTransport::SMTP_API_NAME
            );
    });
}

}
`

ClientException on PasswordReset feature

When using laravel default password reset form to send notification for user email we get this ClientException error

image

Do we need to put additional configuration for it to work?

json_encode error: Malformed UTF-8 characters, possibly incorrectly encoded

Hello,

When I send email I receive this error :

exception 'InvalidArgumentException' with message 'json_encode error: Malformed UTF-8 characters, possibly incorrectly encoded' in vendor/guzzlehttp/guzzle/src/functions.php:324

My code is
Mail::queue('emails.job', [ 'bodyclass' => 'email job', 'emailContent' => $emailContent, ], function( $message ) use ( $retired ) { $message->to( "[email protected]", "Firstname Lastname"] ); $message->subject( __('Email Title') ); $message->embedData([ 'personalizations' => [ 0 => [ "to" => [ "email" => "[email protected]" "name" => "Firstname Lastname" ] ] 1 => array:1 [ "to" => array:2 [ "email" => "[email protected]" "name" => "Firstname Lastname" ] ] 2 => array:1 [ "to" => array:2 [ "email" => "[email protected]" "name" => "Firstname Lastname" ] ] ], 'send_at' => time(), ], 'sendgrid/x-smtpapi'); });

Why I do not recieve email with Sendgrid example?

Hello,
I installed Sendgrid support into my laravel 5.7
and looking at sample at https://github.com/s-ichikawa/laravel-sendgrid-driver I try to send email based on template with
several vars as parameters:

a small example :

        $to_name= 'me';

        \Mail::to($to)->send( new SendgridMail(), ['name' => "testdata"] );

works ok and I recieved email at my email

But running a bit more complicated example from plugin page does not work :

        $from_email= '[email protected]';
        $from_name= 'Support';
        $val1= ' $val1 lorem value';
        $val2= ' $val1 lorem value';
        $data= compact( [$val1, $val2] );

        \Mail::send(new SendgridMail(), $data, function (Message $message) use (
            $subject, $from_email, $from_name, $to, $to_name )  {
            $message
                ->to($to, $to_name)
                ->from($from_email, $from_name)
                ->replyTo('[email protected]', 'foobar')
            ->embedData([
/*                'personalizations' => [
                    [
                        'to' => [
                            'email' => '[email protected]',
                            'name'  => 'user1',
                        ],
                        'substitutions' => [
                            '-email-' => '[email protected]',
                        ],
                    ],
                    [
                        'to' => [
                            'email' => '[email protected]',
                            'name'  => 'user2',
                        ],
                        'substitutions' => [
                            '-email-' => '[email protected]',
                        ],
                    ],
                ],*/
                'categories' => ['user_group1'],
                'custom_args' => [
                    'user_id' => "123" // Make sure this is a string value
                ]
            ], 'sendgrid/x-smtpapi');
        });

It did not raise runtime error but I did not recieve email...

What is wrong ?

Call to undefined method GuzzleHttp\Message\Response::getHeaderLine()

I have this error using guzzle 5.3.1

Call to undefined method GuzzleHttp\Message\Response::getHeaderLine() in /.../vendor/s-ichikawa/laravel-sendgrid-driver/src/Transport/SendgridV3Transport.php:69

In your composer.json version 5.3 appears to be supported, right?

"require": {
        "illuminate/mail": "~5.1",
        "guzzlehttp/guzzle": "~5.3|~6.2"
},

Variables not getting passed to Mail?

Hello,
Why my variable $name and $email is not getting passed to Mail?
It throws: Undefined variable: name
Here is my code:

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Mail\Message;
use Sichikawa\LaravelSendgridDriver\SendGrid;
use Mail;

class MyController extends Controller
{
    public function testMail(Request $request) {
        $name = $request->name;
        $email = $request->email;
        
        Mail::send([], [], function (Message $message) {
            $message
                ->to($email)
                ->from(config('mail.from.address'), config('mail.from.name'))
                ->embedData([
                    'personalizations' => [
                        [
                            'dynamic_template_data' => [
                                'name' => $name,
                                'verificationid'  => 'XXX',
                            ],
                        ],
                    ],
                    'template_id' => 'XXX',
                ], SendgridTransport::SMTP_API_NAME);
        });
    }
}

If i try to hardcode Email and Name variable it throws:

Class 'App\Http\Controllers\SendgridTransport' not found

This is awesome!

I am the Developer Experience Product Manager at SendGrid. I noticed your video on Youtube and then found your repo!

Would you be interested in talking via a google hangout or skype call? I would love to learn more about your experience with SendGrid and how you came to building a Laravel plugin using our API. If you are interested, can you please grab a time on my calendar?

Message id

How can i retrieve the message id from Sendgrid after the mail is sent?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.