How to send mail in laravel using smtp
In Laravel, you can send mail using SMTP (Simple Mail Transfer Protocol) by configuring the mail settings in your config/mail.php
file and using the Mail
facade. Here's a step-by-step guide:
Step 1: Configure mail settings
In your config/mail.php
file, update the driver
and host
settings to use SMTP:
'driver' => env('MAIL_DRIVER', 'smtp'),
'host' => env('MAIL_HOST', 'smtp.gmail.com'),
'port' => env('MAIL_PORT', 587),
'from' => [
'address' => env('MAIL_FROM_ADDRESS', '[email protected]'),
'name' => env('MAIL_FROM_NAME', 'Your Name'),
],
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
Step 2: Set environment variables
In your .env
file, set the following environment variables:
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_FROM_NAME=Your Name
MAIL_ENCRYPTION=tls
MAIL_USERNAME=your-smtp-username
MAIL_PASSWORD=your-smtp-password
Step 3: Create a mail message
Create a new mail message using the Mail
facade:
use Illuminate\Support\Facades\Mail;
$mail = Mail::raw('Hello, this is a test email!', function ($message) {
$message->from('[email protected]', 'Your Name');
$message->to('[email protected]', 'Recipient Name');
});
Step 4: Send the mail
Send the mail using the send
method:
$mail->send();
Step 5: Verify the mail
Check your email inbox to verify that the mail was sent successfully.
Additional tips
- Make sure to replace
[email protected]
,your-smtp-username
, andyour-smtp-password
with your actual email address, SMTP username, and password. - If you're using Gmail, you may need to allow less secure apps to access your account. You can do this by going to your Google Account settings and enabling "Less secure app access".
- If you're using a self-hosted SMTP server, make sure to update the
host
andport
settings accordingly. - You can also use other SMTP providers like Sendgrid, Mailgun, or Amazon SES by updating the
host
andport
settings.
That's it! With these steps, you should be able to send mail using SMTP in Laravel.