How to send mail using PHP PEAR mail with SMTP authentication

There are several ways to send mail in PHP. Using PEAR (PHP Extension and Application Repository) package to send mail with SMTP authentication is one of them. It is always better to use one which has an option for server authentication. You can specify mail server name, port and userid/password for authentication while sending mail. If you are interested you can also read below two topics for sending mail in PHP.

  1. How to send mail using mail() function in PHP with example
  2. How to send mail from localhost using Gmail SMTP server in PHP

In this topic I will discuss how to code in PHP to send mail using PEAR package. Below code can be used for sending the mail. We will discuss about it.


// set path where Pear package is installed- in our case it is /home/user/php
	ini_set("include_path", '/home/user/php:' . ini_get("include_path") );
	require_once "Mail.php";
	
	$host = "mail server name"; // give your mail server name
	$username = "mail account userid";  // userid to access mail
	$password = "password";  // paassword of the mail account
	$port = "25";
	$from = "mail account userid";
	$headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject, 'MIME-Version' => 1,
    	'Content-type' => 'text/html;charset=iso-8859-1');

	$smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));
	$mail = $smtp->send($to, $headers, $mail_body);

Install PEAR Package Mail

The first step is to check if the server has already PEAR package installed. In most hosting servers it is usually installed. Verify in the Software section in your hosting server after login into cPanel. PEAR packages will be available, install one which is for the mail. Once it is installed you will see a folder available for the software installed. In my case it is under php folder. If you are not sure about the installation part, contact your admin and make sure it is installed properly. You need to know the path of Mail.php.

You can use PEAR classes for the mail. Let us just simply write a form with three input fields and a submit button to send the mail. When the form is submitted, we will call a function which will send mail using PEAR mail.

PEAR Mail in PHP

Let us look at the code below for the form in index.php


<div class="container">
	<h1>Send mail using PEAR mail in PHP</h1>
	<div class="row main">
		<div class="col-md-12"> 
			<form action="index.php" method="post">
				<p><?php echo $msg;?></p>
				<div class="form-group">
					<label for="to_email">To</label>
					<input type="text" id = "to_email" name="to_email" class="form-control" value="<?php echo $to_email ;?>" placeholder="Enter Email Id here">
					<div class="error"><?php echo $to_error;?></div>
				</div>
				<div class="form-group">
					<label for="subject">Subject</label>
					<input type="text" id = "subject" name="subject" class="form-control" value="<?php echo $subject ;?>" placeholder="Enter Subject here">
					<div class="error"><?php echo $subject_error;?></div>
				</div>
				<div class="form-group">
					<label for="message">Message</label>
					<textarea class="form-control" id = "message" name="message" rows="8" placeholder="Enter Your Message here"><?php echo $message ;?></textarea>
					<div class="error"><?php echo $body_error;?></div>
				</div>
				<input type="submit" class="btn btn-primary" name="submit" value="Send Mail">
			</form>
		</div>
	</div>
</div>

When form is submitted, I have written below code to process it and call send_mail() function to send the mail. Let us see the PHP code after form is submitted

PHP code to call send_mail() function

Once the form is submitted, below PHP code for sending mail is written:


<?php
include "lib/library.php";
$to_email = $subject = $message = $msg = "";
$to_error = $subject_error = $body_error = "";
$error = false;
if(isset($_POST['submit'])) {
	$to_email = trim($_POST['to_email']);
	$subject = trim($_POST['subject']);
	$message = trim($_POST['message']);
	if (empty($to_email)) {
		$to_error = "Email id must be entered";
		$error = true;
	}
	else {
		if (!filter_var($to_email, FILTER_VALIDATE_EMAIL)) {
			$to_error = "Invalid Email id entered";
			$error = true;
		}
	}
	if (empty($subject)) {
		$subject_error = "Enter something in the Subject ";
		$error = true;
	}
	if (empty($message)) {
		$body_error = "Some message must be entered";
		$error = true;
	}
	if (!$error) {  
	// format message in html
		$mail_body ='<!DOCTYPE html>';
		$mail_body .='<head>';
		$mail_body .='<style>';
		$mail_body .='p {white-space: pre-wrap;}';
		$mail_body .='</style>';
		$mail_body .='</head>';
		$mail_body .='<body>';
		$mail_body .='<p>'.$message.'</p>';
		$mail_body .='<body>';
		$mail_body .='</html>';

		$result = send_mail($to_email,$subject,$mail_body); // call to function to send mail
		if ($result)
			$msg = "<span class='success'>Mail Sent</span>";
		else
			$msg = "<span class='error'>Failed to send mail, please try after sometime</span>";
	}
}
?>	

library.php is included because our send_mail() function is written in the library.php. I kept library.php in 'lib' folder. You can see it takes three input values for to_email, subject and message, and if validations are successful, it calls send_mail() function.

send_mail() is a custom function written in library.php to have a common function to send mail. Let us see the send_mail() function.

Function to send mail using PEAR Package

If PEAR package is installed, you need to set the path of the folder where mail package is installed. Let's see the code:


<?php
function send_mail($to,$subject,$mail_body)
{
	// set path where Pear package is installed- in our case it is /home/user/php
	ini_set("include_path", '/home/user/php:' . ini_get("include_path") );
	require_once "Mail.php";
	
	$host = "mail server name"; // give your mail server name
	$username = "mail account userid";  // email account to access mail
	$password = "password";  // password of the mail account
	$port = "25";			// check the actual port number
	$from = "mail account userid";	// email id
	$headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject, 'MIME-Version' => 1,
    	'Content-type' => 'text/html;charset=iso-8859-1');

	$smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));
	$mail = $smtp->send($to, $headers, $mail_body);

	if (PEAR::isError($mail)) 
	   return false;
	 else 
	   return true;	
}
?>

In this case Pear package is installed in the path /home/user/php. We need to include Mail.php file which is actually in /home/user/php directory.

Then, we are setting the SMTP server name, port, userid and password of the mail account. Then we are creating a PEAR mail instance in line 16, passing an array of values for SMTP authentication. send() method is used to send the mail.

I have given index.php and custom stylesheet here.

index.php


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<meta name="description" content="">
    <title>Send Email using PEAR Mail in PHP</title>
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
		<link rel="stylesheet" href="css/style.css">
	</head>
<body>
<?php
include "lib/library.php";
$to_email = $subject = $message = $msg = "";
$to_error = $subject_error = $body_error = "";
$error = false;
if(isset($_POST['submit'])) {
	$to_email = trim($_POST['to_email']);
	$subject = trim($_POST['subject']);
	$message = trim($_POST['message']);
	if (empty($to_email)) {
		$to_error = "Email id must be entered";
		$error = true;
	}
	else {
		if (!filter_var($to_email, FILTER_VALIDATE_EMAIL)) {
			$to_error = "Invalid Email id entered";
			$error = true;
		}
	}
	if (empty($subject)) {
		$subject_error = "Enter something in the Subject ";
		$error = true;
	}
	if (empty($message)) {
		$body_error = "Some message must be entered";
		$error = true;
	}
	if (!$error) {  
	// format message in html
		$mail_body ='<!DOCTYPE html>';
		$mail_body .='<head>';
		$mail_body .='<style>';
		$mail_body .='p {white-space: pre-wrap;}';
		$mail_body .='</style>';
		$mail_body .='</head>';
		$mail_body .='<body>';
		$mail_body .='<p>'.$message.'</p>';
		$mail_body .='<body>';
		$mail_body .='</html>';

		$result = send_mail($to_email,$subject,$mail_body); // call to function to send mail
		if ($result)
			$msg = "<span class='success'>Mail Sent</span>";
		else
			$msg = "<span class='error'>Failed to send mail, please try after sometime</span>";
	}
}
?>	
<div class="container">
	<h1>Send mail using PEAR mail in PHP</h1>
	<div class="row main">
		<div class="col-md-12"> 
			<form action="index.php" method="post">
				<p><?php echo $msg;?></p>
				<div class="form-group">
					<label for="to_email">To</label>
					<input type="text" id = "to_email" name="to_email" class="form-control" value="<?php echo $to_email ;?>" placeholder="Enter Email Id here">
					<div class="error"><?php echo $to_error;?></div>
				</div>
				<div class="form-group">
					<label for="subject">Subject</label>
					<input type="text" id = "subject" name="subject" class="form-control" value="<?php echo $subject ;?>" placeholder="Enter Subject here">
					<div class="error"><?php echo $subject_error;?></div>
				</div>
				<div class="form-group">
					<label for="message">Message</label>
					<textarea class="form-control" id = "message" name="message" rows="8" placeholder="Enter Your Message here"><?php echo $message ;?></textarea>
					<div class="error"><?php echo $body_error;?></div>
				</div>
				<input type="submit" class="btn btn-primary" name="submit" value="Send Mail">
			</form>
		</div>
	</div>
</div>
</body>
</html>

style.css


h1{
	text-align:center;
}
.main{
	width:50%;
	margin:auto;}
p{
	text-align: center;
	color:#209512;
}
label{
	font-weight: bold;
}
.error{
	color: red;
}

send mail using PEAR mail in phpConclusion

In your project, depending on the requirement, you can trigger an email after a transaction is complete or after an activity is performed. You can write a routine for sending mail and call it from anywhere in the application with the parameters as it was shown above. PEAR mail is a secured mail with SMTP authentication. Refer to the related topics below for other ways to send mail in PHP.