Hello folks, here we ‘ll know how to send emails using sendgrid in laravel. We have many ways to send emails in laravel, we can send emails using plain php or we can use email service providers like SendGrid, mailgun, mandrill and many more. As one of the follower of this site laravel.com has request me to post a tutorial on ‘sending emails using sendgrid’ am posting this here.
Follow these few simple steps,
Step 1 – Register SendGrid Account
Go to
https://sendgrid.com .
Click Try for Free button
Fill all the necessary details
Wait for a email from SendGrid conforming that your account is provisioned.
Cool,you are ready to go.
Step 2 – Change mail configurations in .env and mail.php files
Open .env located at root of the application, edit the file as below
| MAIL_DRIVER=smtp MAIL_HOST=smtp.sendgrid.net MAIL_PORT=587 MAIL_USERNAME=sendgridUsername MAIL_PASSWORD=sendgridPassword |
Now open mail.php located in /config/mail.php, (for further reference on folder/application structure look at previous post on Laravel application structure)
edit the file as below,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php return [ 'driver' => 'smtp', 'host' => 'smtp.sendgrid.net', 'port' => 587, 'encryption' => 'tls', 'username' => 'sendgridUsername', 'password' => 'sendgridPassword', 'sendmail' => '/usr/sbin/sendmail -bs' ]; |
if your website has ssl certificate, change the line
'encryption' => 'tls' to'encryption' => 'ssl' and 'port' => 465,
Step 3 – Send emails the way you want
We ‘ll create some textarea, and the text entered will be sent as a mail when an valid email is entered,
check the form below,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | Route::any ( 'sendemail', function () { if (Request::get ( 'message' ) != null) $data = array ( 'bodyMessage' => Request::get ( 'message' ) ); else $data [] = ''; Mail::send ( 'email', $data, function ($message) { $message->from ( 'donotreply@demo.com', 'Just Laravel' ); $message->to ( Request::get ( 'toEmail' ) )->subject ( 'Just Laravel demo email using SendGrid' ); } ); return Redirect::back ()->withErrors ( [ 'Your email has been sent successfully' ] ); } ); |