How to send a Laravel mail

Learn how to send mail in Laravel with an example. Understand how to customize mail layout & options for delivery, attachments & more.

Sending Mail with Laravel

Laravel makes sending emails very easy with its integrated mail services. Using the mail services, you can compose and send emails via SMTP, Sendmail, or Amazon SES. In this guide, we will discuss how to send a simple email using Laravel.

To get started, we need to configure the mail services in the config/mail.php file. The configuration file contains several options, but for this example, we will just set the default driver to SMTP.

'driver' => env('MAIL_DRIVER', 'smtp'),

Next, we need to add the SMTP configuration settings. These settings can be found in the .env file.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.example.com
MAIL_PORT=587
MAIL_USERNAME=username
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls

Now that the mail service is configured, we can start writing the code to send an email. We will use the Mail facade to send the email. First, we need to import the Mail facade using the following line of code.

use IlluminateSupportFacadesMail;

Then, we can use the Mail facade to send the email. We will define a message array that contains the email subject, body, and recipient information.

$message = [
    'subject' => 'Test Email',
    'body' => 'This is a test email from Laravel.',
    'to' => '[email protected]'
];

Once the message array is defined, we can call the Mail facade's send() method to send the email. The send() method takes two parameters. The first parameter is the view file that will be used to render the email body. The second parameter is the message array.

Mail::send('emails.test', $message);

The email will be sent after the send() method is called. That's all there is to sending emails with Laravel. You can also customize the email template and add attachments, cc, and bcc recipients.

Answers (0)