E-mail configuration in Laravel

No image preview
Tutorials /
PHP Programming/

#laravel

#php

#dev


 

Set up Laravel email logic for your clients in five minutes or less. 

 

 

 

This is an introduction to basic email setup, if you look at Laravel documentation you will find more resources on the topic, but non the less this is a good starting point to see how it all works together.

 

 

 

Select SMTP server you want to use

 

 

You can choose from smtp.google, Mailgun to your hosting email server, it does not matter the setup is the same.

Just pick one and get all the necessary data as username, password, port, security protocol, and SMTP server name.

 

 

 

Configure .env file

 

 

Open your serving .env file and find the section dedicated to email, it will look something like this.

 

 

 

MAIL_MAILER=smtp
MAIL_HOST=smtp.xyzserver.com
MAIL_PORT=465
MAIL_USERNAME="server.mymail@mail.com"
MAIL_PASSWORD="Mypassword"
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS="server.mymail@mail.com"

 

 

 

III. Configure config files

 


Find config/mail.php and edit it to take values from your .env file. It will define all your backend settings and make it easy to edit them if necessary.

 

 

 


'default' => env('MAIL_MAILER', 'smtp'),
'mailers' => [
	'smtp' => [
		'transport' => 'smtp',
		'host' => env('MAIL_HOST', 'smtp.xyzserver.com'),
		'port' => env('MAIL_PORT', 587),
		'encryption' => env('MAIL_ENCRYPTION', 'tls'),
		'username' => env('MAIL_USERNAME', 'optionalusername'),
		'password' => env('MAIL_PASSWORD'),
		'timeout' => null,
		'local_domain' => env('MAIL_EHLO_DOMAIN'),
	],
	//...
]

 

 

 

Create Controllers/Mail  and Mail/Mail class files

 

 

Execute these two commands in the console to create the necessary files.

php artisan make:controller MailxController

php artisan make:mail Mailx

 

 

In Controllers/MailxController.php add the following lines.

 

 

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

class MailxController extends Controller
{
    function send(Request $request){  
    	//can be any method you add to route on email form
		Mail::to("server.mymail@mail.com")->send(new Mailx($request));

 

 

 

And edit Mail/Mailx.php like this to include all data from the $request into the email.

 

 

 

public function __construct($data){
   $this->data = $data;    
   $this->sender = env("MAIL_FROM_ADDRESS");
   }
        
public function build(){
	return $this->subject('Message from Visitor')
	->view('email_template')
	->from($this->sender)
    ->with('data', $this->data);
}

 

 


In your email_template you can include all necessary data like sender email, name, message, etc. using simple Laravel blade templating. You are ready to receive emails from your users.
 

 

From techtoapes.com
 

 

 

 

[root@techtoapes]$ whoami
[root@techtoapes]$ Author Luka

Login to comment.