Sending Email in Laravel

Last updated on Oct 05 2022
Harish Chopra

Table of Contents

Sending Email in Laravel

Laravel uses free feature-rich library SwiftMailer to send emails. Using the library function, we can easily send emails without too many hassles. The e-mail templates are loaded in the same way as views, which means you can use the Blade syntax and inject data into your templates.

The following table shows the syntax and attributes of send function −

Syntax void send(string|array $view, array $data, Closure|string $callback)
Parameters ·      $view(string|array) − name of the view that contains email message

·      $data(array) − array of data to pass to view

·      $callback − a Closure callback which receives a message instance, allowing you to customize the recipients, subject, and other aspects of the mail message

Returns nothing
Description Sends email.

In the third argument, the $callback closure received message instance and with that instance we can also call the following functions and alter the message as shown below.

  • $message → subject(‘Welcome to the Tecklearn’);
  • $message → from(’email@example.com’, ‘Mr. Example’);
  • $message → to(’email@example.com’, ‘Mr. Example’);

Some of the less common methods include −

  • $message → sender(’email@example.com’, ‘Mr. Example’);
  • $message → returnPath(’email@example.com’);
  • $message → cc(’email@example.com’, ‘Mr. Example’);
  • $message → bcc(’email@example.com’, ‘Mr. Example’);
  • $message → replyTo(’email@example.com’, ‘Mr. Example’);
  • $message → priority(2);

To attach or embed files, you can use the following methods −

  • $message → attach(‘path/to/attachment.txt’);
  • $message → embed(‘path/to/attachment.jpg’);

Mail can be sent as HTML or text. You can indicate the type of mail that you want to send in the first argument by passing an array as shown below. The default type is HTML. If you want to send plain text mail then use the following syntax.

Syntax

Mail::send([‘text’=>’text.view’], $data, $callback);

In this syntax, the first argument takes an array. Use text as the key name of the view as value of the key.

Example

Step 1 − We will now send an email from Gmail account and for that you need to configure your Gmail account in Laravel environment file – .env file. Enable 2-step verification in your Gmail account and create an application specific password followed by changing the .env parameters as shown below.

.env

MAIL_DRIVER = smtpMAIL_HOST = smtp.gmail.comMAIL_PORT = 587MAIL_USERNAME = your-gmail-usernameMAIL_PASSWORD = your-application-specific-passwordMAIL_ENCRYPTION = tls

Step 2 − After changing the .env file execute the below two commands to clear the cache and restart the Laravel server.

php artisan config:cache

Step 3 − Create a controller called MailController by executing the following command.

php artisan make:controller MailController --plain

Step 4 − After successful execution, you will receive the following output −

la 12

Step 5 − Copy the following code in

app/Http/Controllers/MailController.php file.

app/Http/Controllers/MailController.php
<?php namespace App\Http\Controllers;use Illuminate\Http\Request;use Mail; use App\Http\Requests;use App\Http\Controllers\Controller; class MailController extends Controller {   public function basic_email() {      $data = array('name'=>"Virat Gandhi");         Mail::send(['text'=>'mail'], $data, function($message) {         $message->to('abc@gmail.com', 'Tecklearn')->subject            ('Laravel Basic Testing Mail');         $message->from('xyz@gmail.com','Virat Gandhi');      });      echo "Basic Email Sent. Check your inbox.";   }   public function html_email() {      $data = array('name'=>"Virat Gandhi");      Mail::send('mail', $data, function($message) {         $message->to('abc@gmail.com', 'Tecklearn')->subject            ('Laravel HTML Testing Mail');         $message->from('xyz@gmail.com','Virat Gandhi');      });      echo "HTML Email Sent. Check your inbox.";   }   public function attachment_email() {      $data = array('name'=>"Virat Gandhi");      Mail::send('mail', $data, function($message) {         $message->to('abc@gmail.com', 'Tecklearn')->subject            ('Laravel Testing Mail with Attachment');         $message->attach('C:\laravel-master\laravel\public\uploads\image.png');         $message->attach('C:\laravel-master\laravel\public\uploads\test.txt');         $message->from('xyz@gmail.com','Virat Gandhi');      });      echo "Email Sent with attachment. Check your inbox.";   }}

Step 6 − Copy the following code in resources/views/mail.blade.php file.

resources/views/mail.blade.php

<h1>Hi, {{ $name }}</h1>l<p>Sending Mail from Laravel.</p>

Step 7 − Add the following lines in app/Http/routes.php.

app/Http/routes.php

Route::get('sendbasicemail','MailController@basic_email');Route::get('sendhtmlemail','MailController@html_email');Route::get('sendattachmentemail','MailController@attachment_email');

Step 8 − Visit the following URL to test basic email.

http://localhost:8000/sendbasicemail

Step 9 − The output screen will look something like this. Check your inbox to see the basic email output.

la 13

Step 10 − Visit the following URL to test the HTML email.

http://localhost:8000/sendhtmlemail

Step 11 − The output screen will look something like this. Check your inbox to see the html email output.

la 14

Step 12 − Visit the following URL to test the HTML email with attachment.

http://localhost:8000/sendattachmentemail

Step 13 − You can see the following output

la 15

Note − In the MailController.php file the email address in the from method should be the email address from which you can send email address. Generally, it should be the email address configured on your server.

So, this brings us to the end of blog. This Tecklearn ‘Sending Email in Laravel’ blog helps you with commonly asked questions if you are looking out for a job in Laravel Programming. If you wish to learn Laravel and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

https://www.tecklearn.com/course/java-and-jee-training/

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

  • Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
  • Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
  • Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

 

What you will Learn in this Course?

Introduction to Java

  • Java Fundamentals
  • Introduction to Java Basics
  • Features of Java
  • Various components of Java language
  • Benefits of Java over other programming languages
  • Key Benefits of Java

Installation and IDE’s for Java Programming Language

  • Installation of Java
  • Setting up of Eclipse IDE
  • Components of Java Program
  • Editors and IDEs used for Java Programming
  • Writing a Simple Java Program

Data Handling and Functions

  • Data types, Operations, Compilation process, Class files, Loops, Conditions
  • Using Loop Constructs
  • Arrays- Single Dimensional and Multi-Dimensional
  • Functions
  • Functions with Arguments

OOPS in Java: Concept of Object Orientation

  • Object Oriented Programming in Java
  • Implement classes and objects in Java
  • Create Class Constructors
  • Overload Constructors
  • Inheritance
  • Inherit Classes and create sub-classes
  • Implement abstract classes and methods
  • Use static keyword
  • Implement Interfaces and use it

Polymorphism, Packages and String Handling

  • Concept of Static and Run time Polymorphism
  • Function Overloading
  • String Handling –String Class
  • Java Packages

Exception Handling and Multi-Threading

  • Exception handling
  • Various Types of Exception Handling
  • Introduction to multi-threading in Java
  • Extending the thread class
  • Synchronizing the thread

File Handling in Java

  • Input Output Streams
  • io Package
  • File Handling in Java

Java Collections

  • Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
  • Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
  • Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

  • Introduction to SQL: Connect, Insert, Update, Delete, Select
  • Introduction to JDBC and Architecture of JDBC
  • Insert/Update/Delete/Select Operations using JDBC
  • Batch Processing Transaction
  • Management: Commit and Rollback

Java Enterprise Edition – Servlets

  • Introduction to J2EE
  • Client Server architecture
  • URL, Port Number, Request, Response
  • Need for servlets
  • Servlet fundamentals
  • Setting up a web project in Eclipse
  • Configuring and running the web app with servlets
  • GET and POST request in web application with demo
  • Servlet lifecycle
  • Servlets Continued
  • Session tracking and filter
  • Forward and include Servlet request dispatchers

Java Server Pages (JSP)

  • Fundamentals of Java Server Page
  • Writing a code using JSP
  • The architecture of JSP
  • JSP Continued
  • JSP elements: Scriptlets, expressions, declaration
  • JSP standard actions
  • JSP directives
  • Introduction to JavaBeans
  • ServletConfig and ServletContext
  • Servlet Chaining
  • Cookies Management
  • Session Management

Hibernate

  • Introduction to Hibernate
  • Introduction to ORM
  • ORM features
  • Hibernate as an ORM framework
  • Hibernate features
  • Setting up a project with Hibernate framework
  • Basic APIs needed to do CRUD operations with Hibernate
  • Hibernate Architecture

POJO (Plain Old Java Object)

  • POJO (Plain Old Java Object)
  • Persistent Objects
  • Lifecycle of Persistent Object

Spring

  • Introduction to Spring
  • Spring Fundamentals
  • Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

 

0 responses on "Sending Email in Laravel"

Leave a Message

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