Send Email With Laravel

Send Email with Laravel

In this episode we’re going to take a look at sending email from a Laravel Application. There are a few ways to send email, but we’ll focus on using SMTP or Simple Mail Transfer Protocol using the SendGrid Service. SMTP is an open standard defined in RFC 821 which dates all the way back to 1982! It is the most common way to send email on the Internet and makes use of TCP ports 25 and 587. SendGrid is one of the biggest EiaaS, email infrastructure as a service provider. Some well known compaies making use of the SendGrid API include Uber, Spotify, and Pinterest. With Laravel, it’s easy to tie in to a SendGrid account and send email from our application as well. Let’s check it out!


Laravel Mail Configuration

In order to get our application ready to send some emails, we’ll need to take a look at the configuration file. Navigate to app/config/mail.php and find the following configuration options:

<?php

return array(

	/*
	|--------------------------------------------------------------------------
	| Mail Driver
	|--------------------------------------------------------------------------
	|
	| Laravel supports both SMTP and PHP's "mail" function as drivers for the
	| sending of e-mail. You may specify which one you're using throughout
	| your application here. By default, Laravel is setup for SMTP mail.
	|
	| Supported: "smtp", "mail", "sendmail", "mailgun", "mandrill", "log"
	|
	*/

	'driver' => 'smtp',

	/*
	|--------------------------------------------------------------------------
	| SMTP Host Address
	|--------------------------------------------------------------------------
	|
	| Here you may provide the host address of the SMTP server used by your
	| applications. A default option is provided that is compatible with
	| the Mailgun mail service which will provide reliable deliveries.
	|
	*/

	'host' => 'smtp.sendgrid.net',

	/*
	|--------------------------------------------------------------------------
	| SMTP Host Port
	|--------------------------------------------------------------------------
	|
	| This is the SMTP port used by your application to deliver e-mails to
	| users of the application. Like the host we have set this value to
	| stay compatible with the Mailgun e-mail application by default.
	|
	*/

	'port' => 587,

	/*
	|--------------------------------------------------------------------------
	| Global "From" Address
	|--------------------------------------------------------------------------
	|
	| You may wish for all e-mails sent by your application to be sent from
	| the same address. Here, you may specify a name and address that is
	| used globally for all e-mails that are sent by your application.
	|
	*/

	'from' => array('address' => 'mailtut@vegibit.com', 'name' => 'Laravel App'),

	/*
	|--------------------------------------------------------------------------
	| E-Mail Encryption Protocol
	|--------------------------------------------------------------------------
	|
	| Here you may specify the encryption protocol that should be used when
	| the application send e-mail messages. A sensible default using the
	| transport layer security protocol should provide great security.
	|
	*/

	'encryption' => 'tls',

	/*
	|--------------------------------------------------------------------------
	| SMTP Server Username
	|--------------------------------------------------------------------------
	|
	| If your SMTP server requires a username for authentication, you should
	| set it here. This will get used to authenticate with your server on
	| connection. You may also set the "password" value below this one.
	|
	*/

	'username' => 'SendGrid User Name Here',

	/*
	|--------------------------------------------------------------------------
	| SMTP Server Password
	|--------------------------------------------------------------------------
	|
	| Here you may set the password required by your SMTP server to send out
	| messages from your application. This will be given to the server on
	| connection so that the application will be able to send messages.
	|
	*/

	'password' => 'SendGrid Password Here',

	/*
	|--------------------------------------------------------------------------
	| Sendmail System Path
	|--------------------------------------------------------------------------
	|
	| When using the "sendmail" driver to send e-mails, we will need to know
	| the path to where Sendmail lives on this server. A default path has
	| been provided here, which will work well on most of your systems.
	|
	*/

	'sendmail' => '/usr/sbin/sendmail -bs',

	/*
	|--------------------------------------------------------------------------
	| Mail "Pretend"
	|--------------------------------------------------------------------------
	|
	| When this option is enabled, e-mail will not actually be sent over the
	| web and will instead be written to your application's logs files so
	| you may inspect the message. This is great for local development.
	|
	*/

	'pretend' => false,

);

By reading the comments, you can see exactly what all of these configuration options are used for. For the purposes of this demonstration, we’ll update four of the options. By default the host key of the mail configuration array is set to smtp.mailgun.org. We are going to swap that out for smtp.sendgrid.net as this is the address required when using SendGrid. Next, we’ll update the from field. Here we can specify the address from where our email will be sent from as well as setting the name. Last up, we’ll fill in the user name and password of our SendGrid account. If you happen to be using a different SMTP service provider, simply fill out your user name and password here, and it should be just as easy to get this configured and ready to send email.


Send an Email

After we have set up just a small array of configuration options, we’re ready to try to send an email with Laravel. We’ll add a sendmail route to our routes file like so:


Route::get('/sendmail', function() 
{
	$data = array('name' => 'Jordan');
	
	Mail::send('emails.welcome', $data, function($message)
	{
		$message->to('example@outlook.com')
		->subject('Hi there!  Laravel sent me!');
	});
});

In the snippet above, we have a few things to take note of. The main idea is that Mail::send() is the method we are interested in, but let’s take a look at the parameters that are passed to the method.

First Parameter: The first parameter that gets passed to the Mail::send() method is the view to be used for the email message. For example, your app may have a welcome email template, and possibly all kinds of other notification email templates. If you are familiar with Twitter, you’ll know that by default, they email you for almost anything and everything possible. If someone follows you, send an email to you. If someone mentions you, send a notification. Mentions and Notifications kind of go hand in hand. A new feature came out, send you an email. If you’re like me, you go and disable all of these notifications, but the idea here is that each scenario may represent a different template for the email that will get sent. In our case, we’re just going to send a welcome email.

Second Parameter: The second parameter is the data which will get passed to the view. Most times when we send an email, it would be nice to specify the user’s name so we can address them properly when we send the email. We’ll pretend the user’s name is Jordan so we can say hi when we send the welcome email.

Third Parameter: The third parameter to be passed to the Mail::send() method is a PHP Closure which specifies the various options available for sending the email. This Closure accepts a $message instance which makes use of the SwiftMailer message class, so it pays to be familiar with how SwiftMailer works by checking out their documentation. Of course the official Laravel Documentation will be your friend here as well.

Here is the view that we will use for our welcome email.

welcome.blade.php

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Mailer Demo</title>
</head>

<body>
Hi {{ $name }},
<br>
     Welcome to the Laravel and SendGrid SMTP tutorial.  This email was sent from Laravel using SendGrid as a service.
<br>
Best Regards
</body>
</html>

Send an Email!

Ok I think we’re ready to try to send an email. All we have to do is visit the sendmail route we specified. When visiting http://vegi.bit/sendmail in the local development environment, we’ll notice a small pause, then simply a white screen. Let’s go check our accounts and see if the mail was sent.

laravel email sent

Looks like the message is in our inbox, when we click it, we can see the message as well.

laravel email inbox

Cool! We’re successfully sending email with Laravel.

Conclusion

This was a quick overview of how to send an email using the great Laravel PHP framework. Now that we have this simple example down, it would make sense to dig in to the mailer pattern, mail queues, mail pretend, and many other great features of working with email in Laravel. Those will be topics for different episodes, but at least we have the basics under our belt to build upon further.