Sending email in Laravel is a simple and straightforward process. Laravel provides a clean and simple API for sending emails, making it easy for developers to send emails from their applications. In this article, we will take a look at how to send emails in Laravel, from setting up the email configuration to sending your first email.
How to send Email in Laravel (Step-by-Step Tutorial)
The first step in sending emails in Laravel is to configure your email settings. Laravel supports several mail drivers out of the box, including SMTP, Mailgun, and sendmail. To configure your email settings, you will need to open the .env file in the root of your Laravel application and update the mail driver and the mail server settings.
For example, if you are using the SMTP driver, you will need to set the MAIL_DRIVER, MAIL_HOST, MAIL_PORT, MAIL_USERNAME, MAIL_PASSWORD, and MAIL_ENCRYPTION settings in the .env file:
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=yourusername
MAIL_PASSWORD=yourpassword
MAIL_ENCRYPTION=tls
Once you have configured your email settings, you can send emails in Laravel using the Mail facade. The Mail facade provides several methods for sending emails, including the send method for sending plain text emails and the send method for sending HTML emails.
Related Articles : Laravel Tutorials: Task scheduling
For example, to send a plain text email, you can use the following code:
use Mail;
Mail::send('emails.welcome', $data, function ($message) {
$message->from('[email protected]', 'Admin');
$message->to('[email protected]');
$message->subject('Welcome to our website!');
});
In the above example, we are using the send method of the Mail facade to send an email to the [email protected] address, with a subject of “Welcome to our website!” and a plain text body. The first parameter of the send method is the name of the email template, and the second parameter is an array of data that will be passed to the template.
To send an HTML email, you can use the following code:
use Mail;
Mail::send(['html' => 'emails.welcome'], $data, function ($message) {
$message->from('[email protected]', 'Admin');
$message->to('[email protected]');
$message->subject('Welcome to our website!');
});
In the above example, we are using the same send method of the Mail facade but passing the parameter as an array with the key as ‘html’ and the value as the email template name.
By following these steps, you can easily send emails in Laravel. You can customize your email templates, add attachments, and even queue your emails to improve the performance of your application. Laravel makes it easy to send emails, and with a little bit of configuration, you can have your application sending emails in no time.