facebook google plus twitter
Webucator's Free PHP Tutorial

Lesson: Sending Email with PHP

Welcome to our free PHP tutorial. This tutorial is based on Webucator's Introduction to PHP Training course.

In this lesson, you will learn how to send emails with PHP using both the built-in mail() function and the PHPMailer extension.

Lesson Goals

  • Send emails using PHP's built-in mail() function.
  • Send email using PHPMailer, a PHP extension with more features than mail().

mail()

PHP has a built-in mail() function that makes it easy to send email.

Mail Parameters
Parameters Description
To The address to send the email to.
Subject The email's subject.
Message The body of the email.
Additional Headers Optional. Additional headers (e.g, From, Reply-To)
Additional Parameters Optional. Any additional parameters you may want to send to your mail server.

Note: when running any script that sends out emails, you will need a mail server and access credentials. Check with your System Administrator or with your Internet Hosting Service Provider to get the mail server information.

Code Sample:

Email/Demos/Mail.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Mail()</title>
</head>
<body>
<?php
	if (!array_key_exists('Submitted',$_POST))
	{
?>
		<form method="post" action="Mail.php">
		<input type="hidden" name="Submitted" value="true">
		Mail Server: <input type="text" name="Host" size="25"><br>
		To: <input type="text" name="To" size="25"><br>
		From: <input type="text" name="From" size="25"><br>
		Subject: <input type="text" name="Subject" size="25"><br>
		<textarea name="Message" cols="50" rows="10"></textarea><br>
		<input type="submit" value="Send Email">
		</form>
<?php
	}
	else
	{
		ini_set('SMTP',$_POST['Host']);
		$to = $_POST['To'];
		$from = 'From: ' . $_POST['From'];
		$subject = $_POST['Subject'];
		$message = $_POST['Message'];
	
		if(mail($to,$subject,$message,$from))
		{
			echo "Message Sent";
		}
		else
		{
			 echo "Message Not Sent";
		}
	}
?>
</body>
</html>

For this example to work, you will need to have a mail server set up on your server.

The first time a visitor hits the page, he'll be presented with a form. When the user fills out and submits that form, the mail() function will attempt to send an email to the address the user entered.

Note that the mail server is set with the ini_set() function, which is used to temporarily change configuration settings. You can set the default mail server in the php.ini file with the SMTP setting.

Shortcomings of mail()

The mail() function has many limitations.

  • No support for SMTP authentication.
  • Difficult to send HTML-formatted emails.
  • Difficult to add attachments.

Luckily, there are extensions that do provide these features.

PHPMailer

A very good email extension is PHPMailer, which is available for free at https://github.com/PHPMailer/PHPMailer. We will use PHPMailer in our examples and exercises. The following tables show some of the more common methods and properties of PHPMailer.

PHPMailer Methods
Method Description
AddAddress() Adds a "To" address.
AddAttachment() Adds an attachment from a path on the filesystem.
AddBCC() Adds a "bcc" address.
AddCC() Adds a "cc" address.
AddReplyTo() Adds a "Reply-to" address.
IsHTML() Sets message type to HTML.
IsSMTP() Sets Mailer to send message using SMTP.
Send() Creates message and assigns Mailer. If the message is not sent successfully then it returns false.
PHPMailer Properties
Property Description
AltBody Sets the text-only body of the message.
Body Sets the Body of the message. This can be either an HTML or text body.
ErrorInfo Holds the most recent mailer error message.
From Sets the From email address for the message.
FromName Sets the From name of the message.
Host Sets the SMTP hosts. All hosts must be separated by semicolons.
Password Sets SMTP password.
SMTPAuth Sets SMTP authentication. Utilizes the Username and Password properties.
Subject Sets the Subject of the message.
Username Sets SMTP username.
WordWrap Sets word wrapping on the body of the message to a given number of characters.

Note: when running any script that sends out emails, you will need a mail server and access credentials. Check with your System Administrator or with your Internet Hosting Service Provider to ge the mail server information.

Code Sample:

Email/Demos/PHPMailer.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>PHPMailer</title>
</head>
<body>
<?php
	if (!array_key_exists('Submitted',$_POST))
	{
?>
		<form method="post" action="PHPMailer.php">
		<input type="hidden" name="Submitted" value="true"><br>
		Mail Server: <input type="text" name="Host" size="25"><br>
		If authentication is required:<br>
		Username: <input type="text" name="Username" size="25"><br>
		Password: <input type="password" name="Password" size="10">
		<hr>
		To: <input type="text" name="To" size="25"><br>
		From Email: <input type="text" name="From" size="25"><br>
		From Name: <input type="text" name="FromName" size="25"><br>
		Subject: <input type="text" name="Subject" size="25"><br>
		<textarea name="Message" cols="50" rows="10"></textarea><br>
		Using HTML: <input type="checkbox" name="HTML">
		<input type="submit" value="Send Email">
		</form>
<?php
	}
	else
	{
		require("class.phpmailer.php");
		$to = $_POST['To'];
		$from = $_POST['From'];
		$fromName = $_POST['FromName'];
		$subject = $_POST['Subject'];
		$message = $_POST['Message'];
		$host = $_POST['Host'];
		
		if (array_key_exists('HTML',$_POST))
		{
			$html = true;
		}
		else
		{
			$html = false;
		}
		
		$mail = new PHPMailer();
					
		$mail->IsSMTP(); // send via SMTP
		$mail->Host = $host; //SMTP server
		
		if (strlen($_POST['Username']))
		{
			$mail->SMTPAuth=true;
            $mail->Username=$_POST['Username'];
			$mail->Password=$_POST['Password'];
		}
		else
		{
			$mail->SMTPAuth=false;
		} 
		
		$mail->From = $from;
		$mail->FromName = $fromName;
		$mail->AddAddress($to);
		$mail->AddReplyTo($from);
		
		$mail->WordWrap = 50; // set word wrap
		$mail->IsHTML($html);
		
		$mail->Subject  = $subject;
		$mail->Body = $message;
		
		if($mail->Send())
		{
			echo "Message Sent";
		}
		else
		{
			 echo "Message Not Sent<br>";
			 echo "Mailer Error: " . $mail->ErrorInfo;
		}
	}
?>
</body>
</html>

As you can see, PHPMailer comes with a full set of intuitive methods and properties that make sending emails very easy.

PEAR also provides an email package at PEAR::Mail_Mime. It has similar functionality to PHPMailer.

Sending a Password by Email

Duration: 20 to 30 minutes.

In this exercise, you will create a Password Reminder page that allows users to have their passwords sent to them by email.

  1. Open EMail/Exercises/PasswordReminder.php in your editor.
  2. This page contains a simple form that submits to the same page.
  3. In the else block of the if condition add code that sends the user her password, which you'll need to get from the Northwind database.
  4. BCC yourself on the email. You'll need this to check to see that your solution is working.
  5. Set the mail server to one to which you have access.
  6. If the email fails to send, output the error to the browser. Otherwise, let the user know the password has been sent.
  7. Test your solution in your browser.

Note: when running any script that sends out emails, you will need a mail server and access credentials. Check with your System Administrator or with your Internet Hosting Service Provider to ge the mail server information.

Solution:

Email/Solutions/PasswordReminder.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Password Reminder</title>
</head>
<body>
<?php
	if (!array_key_exists('Submitted',$_POST))
	{
?>
		Enter your email in the form below to have your password sent to you.
		<form method="post" action="PasswordReminder.php">
		<input type="hidden" name="Submitted" value="true"><br>
		Email: <input type="text" name="To" size="25"><br>
		<input type="submit" value="Send Password">
		</form>
<?php
	}
	else
	{
		$to = $_POST['To'];
		@$db = new mysqli('localhost','root','pwdpwd','Northwind');
		if (mysqli_connect_errno())
		{
		  echo 'Cannot connect to database: ' . mysqli_connect_error();
		}
		else
		{
		 	$query = "SELECT Password FROM Employees WHERE Email = '$to'";
		  	$result = $db->query($query);
		  	$row=$result->fetch_assoc();
			$password = $row['Password'];
			
			require("../class.phpmailer.php");
			
			$message = "Your password is <u>$password</u>.";
		
			$mail = new PHPMailer();
			$mail->IsSMTP(); // send via SMTP
			$mail->Host = 'mail.yourserver.com'; //SMTP server. You'll need to set this.
		
		  	//$mail->SMTPAuth=true;
		  	//$mail->Username='';
		  	//$mail->Password='';
		
		  	$mail->From = 'admin@northwind.com';
			$mail->FromName = 'Northwind Admin';
			$mail->AddAddress($to); //change it to your email address to actually get the email! 
			$mail->AddBCC('ndunn@webucator.com'); 
			$mail->AddReplyTo('admin@northwind.com');
		
			$mail->IsHTML(true); // send as HTML
		
			$mail->Subject  = 'Password Reminder';
			$mail->Body = $message;
		
			if($mail->Send())
			{
				echo "Your password has been sent.";
			}
			else
			{
			 echo "We could not send your password.<br>";
			 echo "Mailer Error: " . $mail->ErrorInfo;
			 }
		}
	}
?>
</body>
</html>