Problem
How do I set up outbound SMTP using Laravel?
How do I set up outbound SMTP using the email component from Laravel?
How do I use outMail in Laravel?
How do I use outMail with the PHP framework Laravel?
Solution
The following example of code assumes you have already got a fully functional webserver and the PHP framework Laravel installed and working.
Configure Laravel
Laravel uses config/mail.php file for storing details used in sending email. This file contains settings like MAIL_DRIVER, MAIL_HOST, MAIL_PORT, MAIL_USERNAME and MAIL_PASSWORD. In order to successfully send SMTP emails we need to configure these variables.
However, we don't edit the mail.php file directly. Instead we edit a file called .env placed in the root of your application.
Add the following lines to your .env file and edit accordingly (as per your welcome email)
MAIL_DRIVER=smtp
MAIL_HOST=mxXXXXXX.smtp-engine.com
MAIL_PORT=25
MAIL_USERNAME=outmail-username
MAIL_PASSWORD=outmail-password
MAIL_ENCRYPTION=ssl
Create an email template
Next we need to create an email template to use when sending the email.
Let's create a file called mytemplate.blade.php
We'll create the file in resources\views\emails\mytemplate.blade.php
<?php ?>
<P>Hello {{ name }},</P>
<P>{{ body }}</P>
Sending an email
In your code you can send email using the below example code snippet
<?php
$email['to_name'] = 'RECIPIENTS_NAME';
$email['to_email'] = 'RECIPIENTS_EMAIL_ADDRESS';
$email['from_name'] = 'SENDERS_NAME';
$email['from_email'] = 'SENDERS_EMAIL_ADDRESS';
$email['subject'] = 'Laravel Test SMTP Mail';
// Create an array of information to be used in our mytemplate.
$data = array('name' => "Fred Example",
'body' => "This is a test SMTP mail"
);
Mail::send('emails.mytemplate', $data, function($message) use ($email) {
$message->to($email['to_email'], $email['to_name']);
$message->subject($email['subject']);
$message->from($email['from_email'], $email['from_name']);
});
?>
Summary of server details
Outgoing server |
mxXXXXXX.smtp-engine.com As provided in your signup email. |
Outgoing server protocol |
SMTP |
Outgoing server port |
25, 465, 587, 2525 or 8025 |
Authentication Type |
Basic Authentication, SSL and TLS supported |
Username |
As provided |
Password |
As provided |