Laravel: Sending Email(Electronic Mail)

 76
Laravel: Sending Email(Electronic Mail)

Introduction
How to send emails from a Laravel application using Laravel's built-in email features.

Setting Up Email Configuration:

  • Open the .env file in your Laravel project.
  • Configure the MAIL_DRIVER, MAIL_HOST, MAIL_PORT, MAIL_USERNAME, and MAIL_PASSWORD variables with your email service provider's SMTP details. 
  • Optionally, you can configure other email settings such as MAIL_FROM_ADDRESS and MAIL_FROM_NAME

1. The raw Method for Sending Plain Text Emails
      The raw method in Laravel's Mail facade allows you to send plain text emails by passing the desired text as an argument. The following example demonstrates its usage: 

use Illuminate\Support\Facades\Mail;

Route::get('/send-email', function(){
    Mail::raw('Hello laravel this is test mail', function ($message) {
        $message->to('krp@example.com', 'John Doe');
        $message->subject('Hello mail raw');
    });
});


2. Send HTML View as an Email Body
      Let's add the email-sending functionality to our Laravel application. Run the below command in the terminal.

php artisan make:mail LaravelEmail

Running this command will create a file named LaraveEmail.php in the app/Mail directory. The generated file will have some pre-generated code and we will add some code to the generated file.

<?PHP
namespace App\Mail;

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

class LaravelEmail extends Mailable
{
    use Queueable, SerializesModels;
    protected $mailData;
    
    /**
     * Create a new message instance.
     */
    public function __construct($mailData)
    {
        $this->mailData = $mailData;
    }

    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            to: $this->mailData['to'],
            subject: $this->mailData['subject'],
            cc: $this->mailData['cc'],
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            view: 'mail.test-email',
            with: ['mailMessage' => $this->mailData],
        );
    }

    /**
     * Get the attachments for the message.
     *
     * @return array<int, \Illuminate\Mail\Mailables\Attachment>
     */
    public function attachments(): array
    {
        return [];
    }
}

The above code is straightforward and can be understood easily. But still, let's see the code of the content and envelope function.
We have passed the mailData array to the laravelEmail class, this array contains all the information that is needed to send the email. Now let's create files that hold the HTML view of email.
 

Create a new one .blade file under the mail/test-mail.blade.php where you can create HTML template for email. 

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        Dear {{$mailMessage['name'] }} !
        <p>Thank You for contacting us. We will revert back on your query within 24 Hours.</p>
        Thank You
    </body>
</html>


Now let's write a test route for the sending email template and you can create a controller and send email. Here we used a simple route for the testing.

Route::get('/send-email', function(){
    $mailData = [
    				'to' => 'krp@abc.email', 
    			 	'subject' => 'Test mail', 
    			 	'name' => 'Krunal', 
    			 	'cc' => 'cc@example.com'
    			];
    Mail::send(new LaravelEmail($mailData));  
});


The email will look like the following:

 

3. Send an Attachment file.

 We have added image files in the storage directory and we will send this image with email in Laravel 10. attachments() method which returns an attachment array for sending with email. we will use this attachment method to Laravel send an email with PDF attachments.
 

use Illuminate\Support\Facades\Mail;
use App\Mail\LaravelEmail;

Route::get('/send-email', function(){
    $mailData = [
    			'to' => 'krp@narola.email', 
    			'subject' => 'Test mail', 
    			'name' => 'Krunal',
    			'cc' => 'cc@example.com', 
    			'attachmentPath' => public_path('storage/uploads/krp.jpeg')
    			];
    Mail::send(new LaravelEmail($mailData));  
});



You can use fromPath like below:

public function attachments(): array    
{
        return [
            Attachment::fromPath($this->mailData['attachmentPath'])
        ];
}

 

The below image is an email with an attachment file


 
     


Post a Comment

0Comments

* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Post a Comment (0)