Email laravel

Send Emails in Laravel Using SMTP

Sending an email is a common requirement for any web application. Some general uses of sending emails include verifying user registration, getting feedback from users, providing options to contact the site administrator, etc. The Laravel framework contains several packages to send emails from the Laravel project. SMTP, Mailgun, Postmark, and Amazon SES are used in Laravel for sending simple, transactional, and bulk emails. Laravel has an email-sending library named SwiftMailer to send an email with an email template. This tutorial shows you how to send a simple email using SMTP.

SMTP Setup and Configuration

Open the .env file from the root folder of the Laravel project and set up the configuration according to your Gmail account. You must enable the “Less secure app” option of your Gmail account to send an email using the Gmail SMTP server.

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=YOUR_EMAIL_ADDRESS
MAIL_PASSWORD=YOUR_PASSWORD
MAIL_ENCRYPTION=ssl

***Note:

You may receive the SMTP authentication error while sending emails using the SMTP Gmail account server. Open the StreamBuffer.php file from the following location.

/var/www/html/laravelpro/vendor/swiftmailer/swiftmailer/
lib/classes/Swift/Transport/StreamBuffer.php

Find and replace line 259 with the following line to authenticate the Gmail SMTP server.

$options['ssl'] = array('verify_peer' => false, 'verify_peer_name' => false,
'allow_self_signed' => true);

Sending Emails Using SMTP

Perform the following steps to send email using the contact form by creating a controller, view, and mail class.

Steps:

Run the following command from the terminal to create EmailController to show the contact form and send an email using Laravel mail class.

$ php artisan make:controller EmailController

Run the following command to create a mail class named sendingEmail. This will create the class under the App\Mail folder.

$ php artisan make:mail sendingEmail

Create a view file named emailsend.blade.php with the following code to display the contact form.

<!DOCTYPE html>
<html>
<head>
<title>Contact Us Form</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/
css/bootstrap.min.css" >

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" >
</script>
<style>
.div_border{
width:60%;
margin:0 auto;
border:1px solid #ccc;
}
.has-error
{
border-color:#cc0000;a
background-color:#ffff99;
}
</style>
</head>
<body>
<br />
<br />
<br />
<h3 align="center">Contact Us</h3><br />
<div class="container" style="width:65%">
@if (count($errors) > 0)
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert">×</button>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
@if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
@endif
</div>

<div class="container div_border">
<form method="post" action="{{url('sendemail/send')}}">
{{ csrf_field() }}
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" value="" />
</div>
<div class="form-group">
<label>Email</label>
<input type="text" name="email" class="form-control" value="" />
</div>
<div class="form-group">
<label>Message</label>
<textarea name="message" class="form-control"></textarea>
</div>
<div class="form-group" align="center">
<input type="submit" name="send" class="btn btn-success" value="Send Message" />
</div>
</form>
</div>
</body>
</html>

Open EmailController and modify the code with the following code. The Mail facade and sendingEmail mail classes are imported at the beginning of the file. Here, the index() method will load the view file in the browser to display the contact form. After submitting the form, the send() method will be called. This method will validate the form by using the validation rules. The $data array is used to send the values of the name and message fields into the sendingEmail class. Next, the email is sent using the Mail facade. You must set a valid email address of the receiver in the to() function before executing the code. If the email sends successfully, then a success message will print.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\sendingEmail;

class EmailController extends Controller
{
    function index()
    {
        return view('emailsend');
    }

    function send(Request $request)
    {
        $this->validate($request, [
        'name' => 'required',
        'email' => 'required|email',
        'message' => 'required'
        ]);

        $data = array(
            'name' => $request->name,
            'message' => $request->message
        );

        Mail::to('Receiver Email Address')->send(new sendingEmail($data));
        return back()->with('success', 'Thanks for contacting us!');
    }

}

Open the sendingEmail class and modify the code with the following code. The email subject is defined inside the build() method and the email_template view is used to format the email content, created in the next step. The values passed from the EmailController are stored in the $email object and are passed in the email_template view.

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class sendingEmail extends Mailable
{
    use Queueable, SerializesModels;

/**
* Create a new message instance.
*
* @return void
*/


    public $emails;

    public function __construct($emails)
    {
        $this->emails = $emails;
    }

/**
* Build the message.s
*
* @return $this
*/

    public function build()
    {
        return $this->subject('Message from Visitor')
                    ->view('email_template')
                    ->with('emails', $this->emails);
}
}

Create the template view file named email_template.blade.php with the following code to send the formatted email to the sender. The values passed from the sendingEmail class are used in this template.

<p>Hello, <br/>I am <b>{{ $emails['name'] }}</b></p>
<p>My query is about the following topic:</p>
<p>{{ $emails['message'] }}.</p>
<p>It will be helpful if you give me response soon.Thank you.</p>

Now, open the web.php file and add the following route code to open the contact form and send the email.

Route::get('/contact', 'EmailController@index');
Route::post('/sendemail/send', 'EmailController@send');

Run the following URL from the browser to load the contact form.

http://localhost/laravelpro/public/contact

Fill the form and click on the Send Message button to send the content of the form to the send() method of the EmailController class.

If the email is sent successfully, then you will obtain the success message, as shown in the following image.

Now, open the Gmail account that you used to send an email in the send() method of the EmailController class. If you open the email, then you will get the following email content, generated by using an email_template view file.

Video Tutorial

Conclusion

Multiple ways exist in the Laravel framework to send an email. The most simple and easiest way to send email in Laravel is shown in this tutorial. If you have a Gmail account, then you can easily send an email by following the steps shown in this tutorial. The Gmail SMTP server is used here to send an email, and the email sending task is tested by running the code from the local server. This tutorial shows HTML-formatted email sending tasks only. You can also perform other tasks, like file attachment, sender name, etc., by using other methods of the Mail class.

About the author

Fahmida Yesmin

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.