Sending Emails using PHP Code

Send Email in Php code




Send Email in Easy Steps in PHP Code

Note: This article supports all programming languages PHP, ASP, VB, VBA, VC++, C++/CLI, C#, VB.NET, JavaScript, ASP.NET, Delphi.


When building a modern web experience, it's important that you take care of features like secure SMTP auto email alert, logging, and batch notification. 

This blog covers easy steps to send email using PHP code.

If you are new to PHP Laravel Framework find here more, for development.

I was like one of you reading more web articles on how to send email using PHP, couldn't find complete email guidance anywhere.

This is what made me write this article for you.

So, herewith I'm providing the ultimate guide step by step.

Let's begin,


How it starts? 

I have a PHP web project developed in (LAMP - Linux Apache MySQL and PHP) environment. Obviously, you know when you release a module or a feature, then CR (Change Request) comes on your way.

Yes, this happened in our daily scrum meeting updates, a customer wanted a feature to send a secure email alert to the administrator (who maintains the server) whenever the application failed to with-stand or network downtime issues.

Task - Send an email alert using SMTP 

To send emails via SMTP, Gmail, Outlook, Phpmailer, or mail() function, from localhost, page, PHP code, PHP script, with examples here.

 

How about Other Programming Languages? 

What if you are a developer from another programming language, I would suggest you may go through this section first,

You want to quickly complete the task, here is one

Sending emails via SMTP Server the easiest way to do implement with the help of EASendMail SMTP Component supports various programming.

Send email in ASP, VB, VBA, VC++, C++/CLI, C#, VB.NET, JavaScript, ASP.NET, Delphi, or other COM/.NET/.NET Core environment applications based on SMTP, Exchange Web Service (EWS), or WebDAV protocols. SSL, TLS, S/MIME, Gmail OAUTH, Live OAUTH, HTML and Embedded

If you want to know the complete guide on how it is done, you may read through the rest.


How it is done in PHP? 

Php mail (mail function) has been built in the PHP function that is used to send emails from PHP scripts. This way of sending has limited features you can not make use like third-party components.

A simple way of sending text email would be good enough.

The mail function accepts the following parameters; 

  • <?php 
  • mail($to_email,$subject,$message,[$headers],[$parameters]);
  • ?> 


How to Configure SMTP Details?

What is an SMTP?  

SMTP - Simple Mail Transfer Protocol 

"Simple Mail Transfer Protocol." This is the protocol used for sending e-mail over the Internet. Your e-mail client (such as Outlook, Eudora, or Mac OS X Mail) uses SMTP to send a message to the mail server, and the mail server uses SMTP to relay that message to the correct receiving mail server.

So, it is important that we configure SMTP earlier before coding.

What are the elements required to configure SMTP?

SMTP Elements are

1. Mail Driver

2. Mail Host

3. Mail Port

4. Mail  User Name

5. Mail Password

6. Mail Encryption


So, you may ask why I have to configure all? 

The answer is, "you must be an authorized user to send email" via email client or application interface.

If you would ask me, - how do I set-up SMTP Email configuration here is one. 

Why it is important to configure, because exposing email password to the public not recommended practice, you must generate an app password to replace in SMTP configuration in application code.

This is how I set-up my Outlook email App Password for sending email. Click here

This article covers connecting PHP code to Microsoft Outlook to send emails. 

When you prefer SMTP Gmail, SMTP Outlook service to send email from localhost and, SMTP configuration differs accordingly.


Gmail SMTP:

SMTP username: Your Gmail address

SMTP password: Your Gmail password

SMTP server address: smtp.gmail.com

Gmail SMTP port (TLS): 587

SMTP port (SSL): 465

SMTP TLS/SSL required: yes 


Outlook SMTP:

SMTP Driver: SMTP

SMTP Host: smtp-mail.outlook.com

SMTP user name: outlook email address

SMTP server password: outlook password

SMTP port (TLS): 587

SMTP Mail Encryption: tls 

Let's explore sending emails from SMTP Outlook in PHP code.



This is how Implemented in PHP for Outlook SMTP

The simple 4 steps below to do,

1. Add SMTP Configuration in .env file
2. Created command PHP file
3. Create a mail view template 
4. Send Email - Execute the program

1. Add SMTP configuration .env File

Go to your application .env File, and add below info

There are times, you may need to save a secret key or password, IP address in a configuration environment file, and later retrieve or access its other part of the application code. 

If you have worked in PHP it's quite a common way to do that, still not recommended to directly access the variable from the environment file .env

This is how I access variable value from - how to read the value from .env PHP  

Add SMTP Configuration to .env file


2. Create a Command PHP File

Let's now create a command PHP file that will be easy to execute the program.

If you are familiar with the PHP artisan command to create a file command line. 

Open your existing project or create a new project,

go to app\Console\Commands path and create a file (the name you like) maybe SendMailCommand.php  as below 


SendMailCommand.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail; 

class SendMailCommand extends Command
{
   
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'emails:send';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'sending email to Administrator';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }
   
    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $mail_data= array(
            'name'=>'Administrator',
            'type'=>'Automation', 
            'content'=>'your mail content',
            'errmsg'=>'An exception occurred sudden',
            'yourdate'=>'13/01/2021 10:30AM',
            'status'=>'Failed'
        );             
        
        Mail::send('emails.mail',$mail_data,function($message){
            $message->from('arjun.premier@outlook.com','Your Email Subject');
            $message->to('your_receiver@gmail.com');
            $message->subject('Email subject detailed');
        });
       
        $this->info('The email is sent successfully');         
    }    
}

If you notice the above code 'emails. mailresources\views\emails\   is the folder under views and mail is a file located in  resources\views\emails\mail.blade.php  

Register your command in Kernel 

Now, you need to add this SendMailCommand.php in kernel.php to schedule.

Go to app\Console\  find kernel.php file, go to function Schedule and add the following line


Protected function schedule (Schedule $schedule)
{
  $schedule->command('SendMail:everyday')
	   ->everyMinute();    
}

 SendMail  sendMail:everyday  is a command name you have created.


3. Create an email content view

Almost you have completed sending email function.

Let's create an email view page to display your content from an array of objects.

If you have noticed SendMailCommand.php file has an object which holds all the information to be sent via email. And it's important that you arrange it before sending an email.

You may ask how do I display an array of data in a view that I'm about to create?

First, let's create a view  mail.blade.php  in the folder path resources\views\emails\mail.blade.php 

mail.blade.php

<div>
<p>Dear {{$name}},</p>
  <h2> Alert for your application </h2>
  <p>We're sorry that it's getting in your way {{$content}}</p> 
  
  <h4>What you may need to do?</h4> 
  <p>You can investigate more on the below error details</p> 

  <p>Process Type:  {{$type}}</p> 
  <p>Reference No:  {{$referenceno}}</p> 
  <p>Status:  {{$status}}</p>  
  <p>Date :  {{$yourdate}}</p>  
  <p>Exception Message:</p><p>{{$errmsg}}</p> </br>

  <p>Please login to your app > Logs > more info</p> 

  <p>Thanks</p> 
  <p>The Dev Team</p>    
</div>

The variables {{$mail_data.variable}}  are declared in the object of SendMailCommand.phpfile.

Mail function Mail::send  supply array of objects to  mail.blade.php this is where the view gets displayed in the email received.


4. Send Email - Execute Program

We are at the final stage of executing send email program.

Well, you might wonder how it is going to be executed; It's simple as that.

One line of code to receive an email.

What's that look like?

At the beginning of this article mentioned Php artisan  commands, if you like to learn more about artisan commands here is one 

Let's begin our demo process, 

I used Visual Studio Code Tool Editor to develop this project in a Linux environment.  

If you already opened the project, use this shortcut key Ctrl + ~ Ctrl + ~  editor. 

PHP Artisan Command Line

Now that you opened the terminal, execute the PHP artisan command that's all.

How do I do that?

Type the artisan command below in the terminal.

If you're not sure what is emails: send   remember what command you created  in the signature  $protected $signature = 'emails:send';  


$ php artisan emails:send 


$ php artisan emails:send

If you're not sure about it - the image shown below explains clearly. 


php artisan send email

If you notice the message after the command executes The email is sent successfully ensures that you have received the email.

Tip 

It's possible that you might have changed the .env configuration file and executed the PHP artisan command send email quickly; then the program you execute produce a different result or may encounter an error, or empty result. It's important to clear the cache before executing it. 

How do I do that - it's the same PHP artisan command  $php artisan config:cache

Well, - open your emails to confirm what you have received.

This is obvious sometimes mail is hidden in  Junk Email or  spam  folder. 

This is how the email looks,  

PHP send email


What's that you get finally? 

This A simple and easy 3 steps to send any SMTP email in PHP Code. 

1. We defined Outlook SMTP configuration in the .env file

2. Created our SendEmailCommand.php, implemented email data array of objects

3. Created a mail.blade.php for email content display with dynamic properties

4. PHP Artisan commands, used PHP artisan send: email command to receive emails

Also, in step1 provided an easy way to access or retrieve configuration value from the .env file in any part of the application provided.

How to read a value from .env file?  - Here it is

How to Share/transfer a file or folder from Windows to Linux (Ubuntu) vice versa -Here is one 

Finally, if you have read the entire article - well done. 

As you know the purpose of this article is to get it done as quickly as possible, thus implemented in command.  

You may apply You may try to implement the SMTP configuration in other programming languages C#, C++, VB, Javascript, Controllers, API program.