Sending email with PHP from an SMTP server

This article will cover the basics of sending email from PHP with an SMTP server. Sending email with PHP from an SMTP server is an easy process. It can be done in just a few lines of code. There are two options for the type of SMTP server you use. One is a simple SMTP server, which is available in most operating systems, and the other is a full-blown email server. The process of sending email with PHP from an SMTP server starts with a connection to the SMTP server. The SMTP server requires a username and password to be authenticated, which is sent in the form of a login string. After this, the "EHLO" command is sent to identify the server and its capabilities. The "MAIL FROM" command tells the server who the email is coming from, and the "RCPT TO" command tells the server who the email is going to. Finally, the "DATA" command tells the server that you are ready to send the email.

Sending email with PHP from an SMTP server
Writing the PHP Code to Send Email using Gmail SMTP
  1. Step 1: Download PHPMailer library from this github link. ...
  2. Step 2: Writing the PHP Code to make an SMTP connection. ...
  3. Step 3: Include packages and files for PHPMailer and SMTP protocol: ...
  4. Step 4: Initialize PHP Mailer and set SMTP as mailing protocol:

When you are sending an e-mail through a server that requires SMTP Auth, you really need to specify it, and set the host, username and password (and maybe the port if it is not the default one - 25).

For example, I usually use PHPMailer with similar settings to this ones:

$mail = new PHPMailer();

// Settings
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';

$mail->Host       = "mail.example.com";    // SMTP server example
$mail->SMTPDebug  = 0;                     // enables SMTP debug information (for testing)
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->Port       = 25;                    // set the SMTP port for the GMAIL server
$mail->Username   = "username";            // SMTP account username example
$mail->Password   = "password";            // SMTP account password example

// Content
$mail->isHTML(true);                       // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body in bold!';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

$mail->send();