18.2 C
Jaipur
Thursday, October 29, 2020

Send Emails in Laravel Using SMTP – Linux Hint

Must read

Consumer tech app Streetbees raises $40 million from investors – Latest News

Streetbees, a startup that monitors the emotions of consumers and analyses their purchasing decisions, said on Wednesday it had raised $40 million from investors...

IT: Digitalisation to drive $6.8 trillion IT spending from 2020 to 2023: Report – Latest News

The global economy remains on its way to its "digital destiny" driving USD 6.8 trillion of IT spending from 2020 to 2023, according to...

Infosys: Infosys becomes carbon neutral; outlines ESG vision for 2030 – Latest News

India's second largest software services firm Infosys on Wednesday said it has turned carbon neutral, three decades ahead of the timeline set by the...

aarogya setu: No information about creation of Aarogya Setu app: MeitY; CIC issues show cause notice – Latest News

The Ministry of Electronics and Information Technology and the National Informatics Centre have said they do not have any information about the "creation" of...

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 AppMail 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 AppHttpControllers;
use IlluminateHttpRequest;
use IlluminateSupportFacadesMail;
use AppMailsendingEmail;

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 AppMail;

use IlluminateBusQueueable;
use IlluminateContractsQueueShouldQueue;
use IlluminateMailMailable;
use IlluminateQueueSerializesModels;

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’, [email protected]);
Route::post(‘/sendemail/send’, [email protected]);

  • 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.

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.

Source link

- Advertisement -

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest article

Consumer tech app Streetbees raises $40 million from investors – Latest News

Streetbees, a startup that monitors the emotions of consumers and analyses their purchasing decisions, said on Wednesday it had raised $40 million from investors...

IT: Digitalisation to drive $6.8 trillion IT spending from 2020 to 2023: Report – Latest News

The global economy remains on its way to its "digital destiny" driving USD 6.8 trillion of IT spending from 2020 to 2023, according to...

Infosys: Infosys becomes carbon neutral; outlines ESG vision for 2030 – Latest News

India's second largest software services firm Infosys on Wednesday said it has turned carbon neutral, three decades ahead of the timeline set by the...

aarogya setu: No information about creation of Aarogya Setu app: MeitY; CIC issues show cause notice – Latest News

The Ministry of Electronics and Information Technology and the National Informatics Centre have said they do not have any information about the "creation" of...

WHOOP: Whoop raises $100 million, valuing the fitness tracker startup at $1.2 billion – Latest News

Fitness tracker startup Whoop said on Wednesday it raised $100 million in Series E funding from investors including venture capital firm IVP and SoftBank...