How to send welcome emails after user registration in Laravel?

In a recent project, we had a requirement to send a welcome email after user registration. So I started exploring on the internet and I stumbled upon sendgrid mail client. 

If you don’t have a Sendgrid account you can get it from here

Laravel provides a clean API over the popular SwiftMailer library with drivers for SMTP, PHP’s mail, send email and more. For this example, we’ll be sending an email with SendGrid using the SMTP Driver. For more information, check out the docs for Laravel’s Mail interface.

Before you begin you’ve to make some modifications in your .env file.

You can modify these depends on your requirements.

After modifying your .env file don’t forget to run following command as it’ll clear cache and your new configuration will apply to your application.

Let’s create a Mailable class

(WelcomeMail is Mailable class name)
Above command will create a new file under app/Mail/WelcomeEmail.php and it should look something like this

In Laravel, each mail sent by your application has a mailable class. These classes are stored in app/Mail directory. Don’t worry if you don’t see this folder. After typing following command, a mail folder will automatically create in the app directory. 

Creating email template

Since each email typically uses a Blade template to render its contents, you have the full power and convenience of the Blade templating engine when building your email’s HTML. 

So, let’s create an email template under app/resources/views/emails/welcome.blade.php

Sending an email

In my case I’ve used a UserController to store user details and also we are going to write the code for Mailable class.

Modifying our Mailable class

Now we have to modify our mailable classes to get the data from the controller. In my case, I’ve created $data array and we are passing the name, email, username, and phone (Here you can pass your desired values). 

Modifying our email template class

Now let’s get all the data into our view which is our welcome.blade.php file. Here I’m writing a normal HTML email template but you can get beautiful templates online. (If you want to know which website can create beautiful email templates just drop us a comment and will get back to you).

In the above code I have called {{$data[‘name’]}} to get the name from Mailable class and I have repeated the same process with username and phone as well. 

Conclusion

Sending an email with Laravel becomes easy if you have a mail service like Sendgrid. In fact, you can use Gmail to send email but then there are some steps you have to follow to achieve that. Anyway, hope you’ve learned something meaningful today. If you’ve any issue or query while setting this up just drop us a comment and will be right with you.

Sharing is caring!

2 thoughts on “How to send welcome emails after user registration in Laravel?”

Leave a Comment

Your email address will not be published. Required fields are marked *