How to send an email with php

How to send an email with php

In today’s digital era, the ability to send emails programmatically is a skill every web developer should have in their toolkit. If you’re looking to add email functionality to your web applications or automate notifications, you’re in the right place. Welcome to our comprehensive guide on how to send an email with PHP.

PHP, a popular server-side scripting language, provides robust tools and libraries for sending emails effortlessly. Whether you’re a beginner taking your first steps into the world of PHP or an experienced developer seeking to enhance your email capabilities, this guide will empower you.

Here are some methods for sending emails using PHP.

  • Using PHP built-in mail function ()
  • How to send emails with PHPMailer

How to send an email using PHP built-in mail function ()

The PHP function mail() is a built-in function for sending emails in PHP, Let’s see how to send an email in php using PHP built-in mail function ().

The PHP mail syntax is pretty simple:

mail(to,subject,message,[headers],[parameters]);
  • to : Specifies the receiver / receivers of the email
  • subject : Specifies the subject of the email.
  • message:  the body of your message,(Each line should be separated with n ).
  • headers (Optional ): Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a n .
  • parameters (Optional ):  for specifying the additional parameters defined in the sendmail_path configuration setting.

Example 1 :

<?php
$to="msaisandeep@gmail.com";
$subject="Appreciation Note for Sai Sandeep"; // Subject
// the message
$msg = "Hola Sandeep, Congratulations for all your ...";
// send email
mail($to,$subject,$msg)
?>

Example 2 (With Headers ):

<?php
$to="msaisandeep@gmail.com";
$subject="Appreciation Note for Sai Sandeep"; // Subject
// the message
$msg = "Hola Sandeep, Congratulations for all your ...";
$headers="From: no-reply@rahulvijayam.com" . "rn" .
"CC: team@btao.in";
// send email
mail($to,$subject,$msg,$headers)
?>

Example 3 (Sending HTML Email ):

In this example will see how to sent an email for more than one recipient and also will cover how to send an html email using php mail() function:

<?php
$to="bharath@gmail.com, msaisandeep@gmail.com,prashanth@gmail.com,umer@gmail.com";
$subject="Appreciation Note for Team"; // Subject
// the message
$msg = "
<html>
<head>
<title>HTML Email </title>
</head>
<body>
<h3>Hello Team,</h3>
<p>
Congratulations for all your efforts towards...
</p>
<p>
Thanks,<br>BTAO Team.
</p>";
// Always set content-type when sending HTML email
$mime_version = "MIME-Version: 1.0" . "rn";
$content_type "Content-type:text/html;charset=UTF-8" . "rn";
$headers=$mime_version.$content_type."From: no-reply@rahulvijayam.com" . "rn" .
"CC: team@btao.in";
// send email
mail($to,$subject,$msg,$headers)
?>

Limitations for php mail() Function

“Here are reasons why mail() is not usually used for sending emails in PHP.”

  • Deliverability issues : The mail() function depends on the local mail server configuration,which can result in emails being flagged as spam or rejected by some email providers. This can cause deliverability issues and make it difficult to ensure that emails are being delivered to recipients.
  • Lack of features: The mail() function does not support many advanced features such as SMTP authentication, email tracking, and attachments. So, This can limit the functionality of your email sending application.
  • Security concerns: The mail() function can be vulnerable to email injection attacks, where an attacker can inject additional headers into the email message, potentially compromising the security of the email system.

While the mail() function can be a simple and lightweight option for sending emails in some cases, it is not recommended for production use and is generally considered less robust than other email sending options available in PHP.

How to send emails with PHPMailer

PHPMailer is a library to send emails safely and easily via PHP code from a web server, PHPMailer is protected against header injection attacks and automatically validates emails.

What you can do with PHPMailer ?

  • Create complex HTML/multipart templates
  • Add attachments and embedded images.
  • Send email from authenticated SMTP.

Now, Lets see how to install it and how to use it:

Installing PHPMailer :

The best way to install PHPMailer is by using composer.

  • Open the Command prompt and go to the directory of the project in which you want to use PHPMailer.
  • Run the following command:
composer require phpmailer/phpmailer
  • Wait for the installation to complete. It will download all the necessary classes to your project folder.

Now, lets see how to use it…

Using PHPMailer :

Step 1: Importing PHPMailer Classes

<?php 
use PHPMailerPHPMailerPHPMailer; 
use PHPMailerPHPMailerException;
?>

Note: Make sure that these lines are at the top of the script not inside any function

Step 2: Load the composer’s autoloader,

Autoload is a method to load and use classes. Using Autoload, we can load and call classes everywhere instead of including classes at the beginning of each PHP file. Therefore, we don’t need to load all classes in the library for all PHP files.

require 'vendor/autoload.php';

Step 3: Create a PHPMailer class object.

<?php 
use PHPMailerPHPMailerPHPMailer; 
use PHPMailerPHPMailerException;
$mail = PHPMailer();
?>

Step 4: Configure the server settings:

We can configure the following server settings.

  • SMTPDebug : Used to display messages regarding problems in connectivity and sending emails. It has following values:
    • 0: It is default value. Disable debugging.
    • 1: Display output messages sent by the client.
    • 2: As 1, plus display responses received from the server.
    • 3: As 2, plus more information about the initial connection – this level can help diagnose STARTTLS failures.
    • 4: As 3, plus display even lower-level information
  • isSMTP() : Set mailer to use SMTP.
  • isMail() : Set mailer to use PHP’s mail function.
  • Host : Specifies the servers.
  • SMTPAuth : Enable/Disable SMTP Authentication.
  • Username : Specify the username.
  • Password : Specify the password.
  • SMTPSecure : Specify encryption technique. Accepted values ‘tls’ or ‘ssl’.
  • Port : Specify the TCP port which is to be connected.
<?php 
use PHPMailerPHPMailerPHPMailer; 
use PHPMailerPHPMailerException;
$mail = PHPMailer();
$mail->SMTPDebug = 2;                   // Enable verbose debug output
$mail->isSMTP();                        // Set mailer to use SMTP
$mail->Host       = 'smtp.rahulvijayam.com;';    // Specify main SMTP server
$mail->SMTPAuth   = true;               // Enable SMTP authentication
$mail->Username   = 'admin@rahulvijayam.com';     // SMTP username
$mail->Password   = 'password';         // SMTP password
$mail->SMTPSecure = 'tls';              // Enable TLS encryption, 'ssl' also accepted
$mail->Port       = 587;                // TCP port to connect to
?>

Step 5:  Lets Add the recipients emails, Attachment (if any) and Content of the mail.

<?php 
use PHPMailerPHPMailerPHPMailer; 
use PHPMailerPHPMailerException;
$mail = PHPMailer();
$mail->setFrom('contact@rahulvijayam.com', 'Name');           // Set sender of the mail
$mail->addAddress('sandeep@btao.in');           // Add a recipient
$mail->addAddress('bharath@btao.in', 'Name');   // Name is optional
?>

Add attachments (if any).

<?php 
use PHPMailerPHPMailerPHPMailer; 
use PHPMailerPHPMailerException;
$mail = PHPMailer();
$mail->addAttachment('url', 'filename');    // filename is optional
?>

Lets, Add the content..

  • isHTML(): If passed true, sets the email format to HTML.
  • Subject: Set the subject of the Mail.
  • Body: Set the contents of the Mail.
  • AltBody: Alternate body in case the e-mail client doesn’t support HTML.
<?php 
use PHPMailerPHPMailerPHPMailer; 
use PHPMailerPHPMailerException;
$mail = PHPMailer();
$mail->isHTML(true);                                  
$mail->Subject = 'Appreciation Notes to ... ';
$mail->Body    = '<h3>Hello Sandy</h3> <b>Congratulations,</b>for all your success...';
$mail->AltBody = 'Hello Sandy, Congratulations,for all your success...';
?>

Finally, send the email.

<?php 
use PHPMailerPHPMailerPHPMailer; 
use PHPMailerPHPMailerException;
$mail = PHPMailer();
$mail->send();
?>

And Your e-mail would be sent, Successfully

Complete PHP Code for Sending Mails using PHPMailer :

<?php 
use PHPMailerPHPMailerPHPMailer; 
use PHPMailerPHPMailerException;
$mail = PHPMailer();
// Configure the server settings:
$mail->SMTPDebug = 2;                   // Enable verbose debug output
$mail->isSMTP();                        // Set mailer to use SMTP
$mail->Host       = 'smtp.rahulvijayam.com;';    // Specify main SMTP server
$mail->SMTPAuth   = true;               // Enable SMTP authentication
$mail->Username   = 'admin@rahulvijayam.com';     // SMTP username
$mail->Password   = 'password';         // SMTP password
$mail->SMTPSecure = 'tls';              // Enable TLS encryption, 'ssl' also accepted
$mail->Port       = 587;                // TCP port to connect to
//Add the recipients emails
$mail->setFrom('contact@rahulvijayam.com', 'Name');           // Set sender of the mail
$mail->addAddress('sandeep@btao.in');           // Add a recipient
$mail->addAddress('bharath@btao.in', 'Name');   // Name is optional
//Adding Attachment (if any) 
$mail->addAttachment('url', 'filename');    // filename is optional
//Adding Content of the mail.
$mail->Subject = 'Appreciation Notes to ... ';
$mail->Body    = '<h3>Hello Sandy</h3> <b>Congratulations,</b>for all your success...';
$mail->AltBody = 'Hello Sandy, Congratulations,for all your success...';
//Send email
$mail->send();
?>

If you have any questions or suggestions, please feel free to leave a comment below.

Also, Check https://rahulvijayam.com/category/scripts/