fbpx
tailor made software
Mariusz Interewicz Updated: 28 Nov 2022 4 min to read

Laravel Sending Email – Explanation with Code Example

Laravel has been popular amongst developers for the last ten years. And since web applications often require sending emails − whether transactional, marketing or newsletters − let’s figure out how to set up sending emails in Laravel.

 

Why should you Choose Laravel for Email Sending?

Laravel is a PHP framework made popular by its simplicity and connectivity.  Many developers choose to use Laravel due to its API Support for Mobile Developers, secure and built-in authentication, ease of maintenance, development, and overall process simplicity. 9gag, Pfizer, BBC, Gitlab, and other major companies use Laravel for their web apps.

Setting up sending emails in Laravel while creating a web app is usually an essential part  − you’d want to register new users or notify old ones of any changes or promotions.

Laravel provides an email API powered by the Symfony Mailer component. Laravel and Symfony Mailer provide drivers for sending emails via SMTP, Mailgun, Postmark, Amazon SES, and sendmail. This allows you to send emails through a local or cloud-based service of your choice.

 

Laravel offers significant advantages for business solutions, notably its streamlined development process and robust security features. Our experience shows that Laravel’s efficient ORM and built-in functionalities allow for rapid deployment and easy scalability. For our clients, this means quicker market entry and enhanced performance, crucial for maintaining competitive edge in dynamic markets. Mike Jackowski COO, ASPER BROTHERS Contact Me

 

Creating the Mailable Class and Building Email

In Laravel, each type of email sent by your app is represented as a “mailable” class. They are responsible for collecting data. These classes are stored in the app/Mail directory − but don’t worry if you don’t see this directory in your application before creating a mailable, it will be created for you when you generate your first mailable class.

Laravel has its own command-line interface called Artisan. It provides numerous useful commands that assist you while building an application and can be especially helpful for creating emails.

To get all available commands, type:

php artisan list

Now, let’s create our first mailable class. We will use an example of an email class for a new user joining your web app − a Welcome email.

In that case, you will type:

php artisan make:mail NewUserNotification

This command then generates a class, which you’ll now be able to find at app/Mail/NewUserNotification.php. All of the mailable class configurations are done using the build() method:

 

public function build()

{

return $this->from('[email protected]')

->view('emails.newuser');

}

Within this method, to configure the email’s presentation and delivery, you may call different other methods such as: from, subject, view, and attach.

In the Form Method, you would define the email address that you’ll use to send the Welcome email.

In the Subject Method, you would define the email subject.

Also, use Attach to define attachments – if you send emails with attachments, etc.

Then, you would use the view method to specify the template that should be used for mailing when presenting the content of the email.

After you’ve created the mailable class, the next time you need to send the Welcome email again, you will just type:

Mail::to($emailAddress)->send(new NewUserNotification);

 

Sending an email

Once you’ve created mailable classes (remember, one will be created for each type of email), you’ll need to send them out.

Luckily, to send an email, you have plenty of options to choose from. Laravel’s creators recommend using one of the API-based drivers: Mailgun, SparkPost, or Amazon SES.

All of the API drivers require the Guzzle HTTP library, which may be installed via the Composer package manager:

 

composer require guzzlehttp/guzzle

You may also choose to use an SMTP server, such as Gmail, for example.

 

Sending through API-based drivers

Laravel 7.0 introduced multiple drivers.

That means you’re not limited to a single driver for each configuration. You could set one of the drivers as a default one in your mail configuration file (let’s say, Mailgun), but configure sending particular types of messages (for example, notifications) with SparkPost.

 

Mail::mailer('sparkpost')

->to($emailAddress())

->send(new NewUserNotification));

 

Laravel supports these three providers by default:

  • Mailgun
  • Sparkpost
  • Amazon SES

 

If you decide to go with one of those, the next step is to get some credentials from them and put them into the .env file. Then, you use the default Laravel Mail::send() functionality – and you’re done.

 

Sending emails using the SMTP server

SMTP servers are cost-efficient and made to ensure optimal and fast email delivery. It also minimizes the chances of spam transferring from a server or mass emails you send being mislabeled as spam.

Let’s start by defining an SMTP server and setting the mailing configuration. In this example, we’ll use Mailtrap.

In this case, all you need to do is just type in your credentials. You will find your credentials in the SMTP Settings tab of your Inbox. You may also use Integrations data from the same tab. Choose Laravel from the list, copy the following details, and paste them into your .env file:

 

MAIL_MAILER=smtp

MAIL_HOST=smtp.mailtrap.io

MAIL_PORT=2525

MAIL_USERNAME=1a2b3c4d5e6f7g //your username

MAIL_PASSWORD=1a2b3c4d5e6f7g // your password

[email protected]

MAIL_FROM_NAME=Example

 

Then, you need to look for the mailable that we created earlier:

php artisan make:mail NewUserNotification

Add a sender, a subject, and a body massage, and introduce the Markdown support. Then, Specify the route in the routes/web.php:

 

<?php

use App\Mail\MailtrapExample;

use Illuminate\Support\Facades\Mail;

Route::get('/send-mail', function () {

Mail::to('[email protected]')->send(new MailtrapExample());

return 'A message has been sent to Mailtrap!';

});

 

Run the application. That’s it!

 

To Sum Up

To send emails in Laravel, you must create a mailable class, and every type of email will be a separate one. When you want to send one of them, you’ll be able to find them in app/Mail/THATEMAILYOUCHOSE.php. Choose if you want to send emails through API-based drivers or an SMTP server relay, and send your emails quickly and easily by using Laravel.

 

Call to action
If you are looking for Laravel engineering support, schedule a free consultation and we’ll be happy to listen to your needs and present the best solutions.
default avatar asper brothers

Share

SUBSCRIBE our NEWSLETTER

Are you interested in news from the world of software development? Subscribe to our newsletter and receive a list of the most interesting information.

    ADD COMMENT

    Download our Free MVP Prompt Template

    Discover the perfect Laravel framework for your app with our ChatGPT Prompt.

      RELATED articles