1. Code
  2. PHP
  3. Laravel

Sending Emails With Laravel 4 & Gmail

Scroll to top

Sending emails is crucial for any web application. Usually, an email is sent to notify the user of some kind of activity that has taken place on the site, for example, such as when updates have been made or when new friends have been found. In this short tutorial, I'll show you how to send emails with Gmail quickly from within a Laravel sample application by extending the functionality that we built in my last tutorial, Authentication With Laravel 4.

So, we'll take that authentication application (you can download the previous tutorial's source code on Github to give you a starting point) that we ended with last time and add in a new feature so that whenever a user registers for the site, we'll send them a confirmation email, welcoming them to the app!


Mail Configuration

Before we can send emails with Laravel 4 we need to configure the app/config/mail.php file. In this file we can set the following options:

Option Description
driver The mailing driver you'd like to use. By default, this is set to SMTP, but you can also change it to use PHPs mail feature or Sendmail instead.
host This is your SMTP server's host address.
port Your SMTPs port.
from This allows you to set the from field in your email, so that all emails are sent from the same address.
encryption This is the encryption protocol that will be used whenever emails are sent.
username This is your SMTP username.
password This is your SMTP password.
sendmail This is the path to where Sendmail can be found on the server, when using the sendmail driver.
pretend When set to true, emails will be logged to a log file, rather than actually sending a real email message.

Sending Mail With Gmail

For this tutorial I'm going to be using Gmail to send my email messages as it's super simple to use. All you need in order to send mail with Gmail is to have an active Gmail account, with a username and password. I'll provide you with everything else. Let's edit our app/config/mail.php file to look something like this (I removed the comments to make the code more compact):

1
2
return array(
3
4
	'driver' => 'smtp',
5
6
	'host' => 'smtp.gmail.com',
7
8
	'port' => 587,
9
10
	'from' => array('address' => 'authapp@awesomeauthapp. com', 'name' => 'Awesome Laravel 4 Auth App'),
11
12
	'encryption' => 'tls',
13
14
	'username' => 'your_gmail_username',
15
16
	'password' => 'your_gmail_password',
17
18
	'sendmail' => '/usr/sbin/sendmail -bs',
19
20
	'pretend' => false,
21
22
);

Here I've left the driver set to smtp. I set the host to use smtp.gmail.com which is Gmail's SMTP server. I set the port to 587, the from to a fake email address which sounds fitting for our application. I left the encryption set to tls and finally you'll then want to enter in your own Gmail username and password for your account and leave pretend set to false.


Sending Mail

Example Code

For this application, whenever a user successfully registers, we want to send them an email welcoming them to the site. Sending emails with Laravel is done by using the Mail::send() method. Here's a small snippet of code, for example purposes:

1
2
Mail::send('folder.view', $data, function($message) {
3
	$message->to('registered-user@gmail. com', 'Jon Doe')->subject('Welcome to the Laravel 4 Auth App!');
4
});

The first argument is the view file we'd like to use in order to format our email message. The second argument is any data that we'd like to pass to that view file. The third argument is a closure which accepts a $message object that we can use to tell the mailer who we're sending the email to and what the subject of this email will be. In this closure, you can also specify other options such as attachments, etc. This will then send out the email to the user.

Pretty easy right?

Sending Emails Upon Successful Registration

Let's now modify our UsersController's postCreate() action and take what we've learned about sending emails to send a welcome email message to our users, whenever they register for the app.

Within our postCreate() action's if statement, where we check if the validation has passed, right after where we save the user into the database, let's add in the following code:

1
2
if ($validator->passes()) {
3
	$user = new User;
4
	$user->firstname = Input::get('firstname');
5
	$user->lastname = Input::get('lastname');
6
	$user->email = Input::get('email');
7
	$user->password = Hash::make(Input::get('password'));
8
	$user->save();
9
10
	Mail::send('users.mails.welcome', array('firstname'=>Input::get('firstname')), function($message){
11
		$message->to(Input::get('email'), Input::get('firstname').' '.Input::get('lastname'))->subject('Welcome to the Laravel 4 Auth App!');
12
	});
13
14
	return Redirect::to('users/login')->with('message', 'Thanks for registering!');
15
} else {
16
	return Redirect::to('users/register')->with('message', 'The following errors occurred')->withErrors($validator)->withInput();
17
}

Here we've called the Mail::send() method and told it to use a users.mails.welcome view file. We then pass in an array as the data that should be available within the view file, in this case we just sent in the users first name, using the Input::get('firstname') method. Next, we create our closure and set this to send the email to the user's email address. We also set the name using the user's first and last name from the form. Lastly, we just give this a pretty generic subject(you can use whatever subject you'd like), so the user knows what all the fuss is about.

Creating the Email View File

Now we need to create our welcome email view file. Under app/views/users create a new folder named mails and inside of it create a new file named welcome.blade.php and add in the following code:

1
2
<h1>Hi, {{ $firstname }}!</h1>
3
4
<p>We'd like to personally welcome you to the Laravel 4 Authentication Application. Thank you for registering!</p>

In this view file we just have some basic HTML, using the $firstname variable that we passed as data from our controller to the view, welcoming the user to the application. There's not much to it, you can use your view files for emails just like you do for any other view.

Let's Try It Out

Make sure to start up your webserver using php artisan serve and we can visit localhost:8000/users/register, then create a new user:

laravel-auth-create-userlaravel-auth-create-userlaravel-auth-create-user

... and then check that user's email account to verify that the email was sent successfully:

laravel-auth-emai-sentlaravel-auth-emai-sentlaravel-auth-emai-sent

Perfect! Our email was sent.


In Conclusion

And that's all there is to sending email messages with Laravel 4 and Gmail. You can of course customize your email messages as much as you'd like to make the mail more appealing.

Now this is the most basic way to send mail with Laravel and it can slow your app down, as it sends the email, but you do have other options. You'll continue to use Laravel's mail class but instead of sending it immediately, you can queue up your emails to have them sent out in the background, without making your users wait. But this topic is best saved for a separate article.

For more information on sending email with Laravel check out the online documentation. Thanks for reading.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.