Sending emails with PHP using mail() function
  John Mwaniki /   18 Aug 2021

Sending emails with PHP using mail() function

PHP mail() function is a built-in function in PHP that allows sending email using a local sendmail program.

Whenever you call the mail() function, it invokes a local sendmail program. If your website is hosted on an online server, the sendmail program is usually configured by default by the system administrator.

The sendmail package is also in-built in local servers (eg. XAMPP, WAMPP, easyPHP etc). However, it is not enabled by default and it will need to be configured in order to work.

The mail() function allows you to send emails directly from a script.

Syntax

This is what you need to start sending emails via the mail() function:

mail(to,subject,message,headers,parameters);

 

Breaking it Down

 

to

This is a required parameter specifying the email recipient. It should be a valid email address to which the email is sent eg. john@webdevsplanet.com.

Ways in which you can set the to parameter:

$to= "user@example.com";  //Specifying only one recipient email
$to = "user@example.com, anotheruser@example.com";  //Specifying more than one email recipient
$to = "Recipient Name <user@example.com>";  //Specifying one recipient and the name of the recipient
$to = "Recipient1 Name <user@example.com>, Recipient2 <anotheruser@example.com>";  //Specifying more than one recipient with their names

 

Subject

This is a single line of text that gives a summary of what the email is about. It is a required parameter and cannot contain any newline characters.

Message

This is a required parameter that defines the actual message of the email. The message can be either plain-text or HTML format.

i). Plain-text message
For plain-text message, each line should be separated with a LF ( ) and should not exceed 70 characters length.

In case the message has longer lines than 70 characters, use the wordwrap() function.

The wordwrap() function wraps a string into new lines when it reaches a specific length (ie, it adds “ ” characters).

Having our message held in a variable named $msg, we use the wordwrap() function below to break our message into new lines after every 70 characters length.

$msg = wordwrap($msg,70);

If a full stop is found at the beginning of a line in the message, it might be removed. To solve this problem, replace the full stop with a double dot:

<?php
  $txt = str_replace(".", "..", $txt);
 ?>

Example

<?php
  $msg = "Lorem ipsum dolor sit amet, no cum zril aperiri, nulla nostro regione in pri. Ne quas dolor interpretaris duo, eu tollit euripidis democritum nec, postea scripserit an pro. Eum quas utinam in, nec ne iudico epicuri. Magna exerci putant in nam.";
  $msg = wordwrap($msg,70);
  $msg = str_replace(".", "..", $msg);
 ?>

ii). HTML message
When sending a HTML formatted message you need to set the Content-Type to “text/html” using a header. This will tell the recipient mail client that the received message content is in HTML format and it should be rendered as so. If you omit this header the message will be rendered as plain-text with HTML tags.

Example

<?php
  $msg = "
   <h1>Happy Christmas holidays</h1>
   <p>Hello James, I wish you and your entire family happy Christmas holidays.</p>
  ";
 ?>

Single quotes(') works pretty much the same as the double quotes(") in the above examples to enclose the message ($msg) string.

However, you are likely to use quotes within the body of your message. In this case you will need to escape them to avoid errors. Use double quotes to enclose your message in case your message contains single quotes in it and vise versa.

Using variables within the message
You can add variables within your message in a number of ways.

Example:

<?php
$name = "John";
$course = "Computer Science";
$country = "Kenya";
//Required message: John is a Computer Science student from Kenya.
//Method 1
$message = "$name is a $course student from $country";
//Method 2
$message = $name." is a ".$course." student from ".$country;
//Method 3
$message = "{$name} is a {$course} student from {$country}";
//Method 4
$message = $name, " is a ", $course, " student from ", $country;
?>

 

Using heredoc instead of quotes

I said above that when your message string contains a single quote in it you should use double quotes to enclose in and vice versa.

But what if the message string contains both single and double quotes in it?

HEREDOC comes to your rescue.

The heredoc is a string method for multi-line strings and an alternative to using quotes. It is preferable because it allows the usage of both single and double quotes within your string.

<<<” opening operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.

Example:

$message = <<<EOD
Sample paragraph1
EOD;

The closing identifier must begin in the first column of the line. The line with the closing identifier must contain no other characters, except a semicolon (;), ie, make sure that there is no space before EOD; or after it.

headers

Headers are an an optional parameter in mail() function used to pass extra and vital information such as:
  - Sender address
  - Reply-to address
  - Carbon copy (Cc)
  - Blind carbon copy(Bcc)
  - Content-type
  - MIME-Version
  - PHP version
  - etc

When using multiple headers, always separate them with a CRLF ( ).

If outside data are used to compose this header, the data should be sanitized so that no unwanted headers could be injected.

Example of setting headers:

$headers = "MIME-Version: 1.0" ."\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "X-Mailer: PHP /" . phpversion() . "\r\n";
$headers .= "From: <email@example.com>" . "\r\n";
$headers .= "Reply-To: email@example.com" . "\r\n";
$headers .= "Cc: recipient2@example.com" . "\r\n";
$headers .= "Bcc: recipient3@example.com" . "\r\n";

 

Parameters

This is an optional parameter that specifies an additional parameter to the sendmail program. You will rarely need to use so we won't use it in our examples.

Examples

We have multiple working examples which you can copy and use in your projects to do tests.

You need to upload the code to an online hosted server or configure the sendmail appropriately in your local server (XAMPP, WAMPP, EasyPHP etc) for it to work.

Note:
Remember to replace the dummy data in the examples with your valid details for them to work.

All successful sending of emails with print out “Message sent successfully” while the failed ones will print out “Message was not sent”.

In case you don't find the emails in the inbox after sending, kindly check also in the spam/junk folder.

Example 1: Sending Plain-text email

<?php
$to = "johndoe@example.com";
$subject = "My first test subject";
$message = "Hello world!";
$mail = mail($to,$subject,$message);
if($mail){
  echo "Message sent successfully";
}
else{
  echo "Message was not sent";
}
?>

Example 2: Sending HTML email

<?php
$to = "Name <email@domain.com>";
$subject = "My first test subject";
$headers = "MIME-Version: 1.0". "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8". "\r\n";
$headers .= "X-Mailer: PHP /".phpversion(). "\r\n";
$headers .= "From: <email@domain.com>". "\r\n";
$headers  .= "Reply-To: email@domain.com". "\r\n";
$message "
<html>
<head>
<title>My HTML email</title>
</head>
<body>
<p>This email contains HTML Tags!</p>
<table>
<tr><td>First Name</td><td><b>John</b></td></tr>
<tr><td>Last Name</td><td><b>Doe</b></td></tr>
<tr><td>Email</td><td><b>email@example.com</b></td></tr>
</table>
</body>
</html>";

$mail = mail($to,$subject,$msgbody,$headers);
if($mail){
   echo "<span style='color:green'> Message sent successfully</span>";
}
else{
   echo "<span style='color:red'> Oops! An error occurred. Try again later.</span>";
}
?>

 

Example 3: Sending an email with variables in the message body and heredoc message string formating.

<?php
$firstname = "John";
$lastname = "Doe";
$email = "johndoe@example.com";
$phone = "+122 33321343";
$to = "Admin Name <email@domain.com>";
$subject = "Contact form submission";
$headers = "MIME-Version: 1.0". "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8". "\r\n";
$headers .= "X-Mailer: PHP /".phpversion(). "\r\n";
$headers .= "From: <$email>". "\r\n";
$headers .= "Reply-To: $email". "\r\n";
$message = <<<EOD
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Contact form submission</title>
</head>
<body>
<p>Hi Admin,<br>
The following details were submitted by a website visitor:
</p>
<table>
<tr><td>First Name</td><td><b>$firstname</b></td></tr>
<tr><td>Last Name</td><td><b>$lastname</b></td></tr>
<tr><td>Phone</td><td><b>$phone</b></td></tr>
<tr><td>Email</td><td><b>$email</b></td></tr>
</table>
</body>
</html>
EOD;
$mail = mail($to,$subject,$msgbody,$headers);
if($mail){
  echo "<span style='color:green'> Message sent successfully</span>";
}
else{
  echo "<span style='color:red'> Oops! An error occurred. Try again later.</span>";
}
?>

You can customize the HTML messages with embedded or inline CSS to improve their look and feel to look more attractive and to present your brand.

Example 4: Sending email from contact form

<?php
$msg = "";
if(isset($_POST["submit"])){
  $name = $_POST["name"];
  $email = $_POST["email"];
  $phone = $_POST["phone"];
  $subject = $_POST["subject"];
  $message = $_POST["message"];

$msgbody = <<<EOD
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>$subject</title>
</head>
<body>
<div style="background-color: #f9f9f9; padding-top: 30px; padding-bottom: 25px;">
<div style="max-width: 640px; margin: 0 auto; box-shadow: 0px 1px 5px rgba(0,0,0,0.1); overflow: hidden; border-top: 4px solid #139401; background: #fff;padding-bottom:25px;">
<table style="width: 640px;" role="presentation" border="0" width="640" cellspacing="0" cellpadding="0" align="center">
<tbody>
<tr>
<td style="padding: 20px;"><span style="font-size: 14pt;"><strong><span style="color: #333232;">Hi Admin!</span></strong></span>
<p><span style="font-family: &rsquo;proxima_nova_rgregular&rsquo;, Helvetica; font-weight: normal; font-size: 12pt; color: #424242;">The message below was sent through contact form:<br /></span></p>
<p><span style="font-family: &rsquo;proxima_nova_rgregular&rsquo;, Helvetica; font-weight: normal; font-size: 12pt; color: #424242;"><span style="color: #52b505;"><strong>Sender Details:</strong></span><br /><span style="color: #262626;">Name</span>: <strong>$name</strong><br /><span style="color: #333232;">Email</span>: <strong>$email</strong> <br />Phone: <strong>$phone</strong></span></p>
<p><span style="font-family: &rsquo;proxima_nova_rgregular&rsquo;, Helvetica; font-weight: normal; font-size: 12pt; color: #424242;"><span style="color: #52b505;"><strong>Subject:</strong></span> <strong>$subject</strong></span></p>
<p><span style="font-family: &rsquo;proxima_nova_rgregular&rsquo;, Helvetica; font-weight: normal; font-size: 12pt; color: #424242;"><span style="color: #52b505;"><strong>Message:</strong></span><br />$message</span></p>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
EOD;

$to = "Admin Name <admin@example.com>";
$headers = "MIME-Version: 1.0"."\r\n";
$headers .= "Content-type:text/html;charset=UTF-8"."\r\n";
$headers .= "X-Mailer: PHP /".phpversion()."\r\n";
$headers .= "From: <$email>"."\r\n";
$headers .= "Reply-To: $email"."\r\n";
$mail = mail($to,$subject,$msgbody,$headers);
 if($mail){
  $msg = "<span style='color:green'> Message sent successfully</span>";
 }
 else{
  $msg = "<span style='color:red'> Oops! An error occurred. Try again later.</span>";
 }
}
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Contact Us</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style type="text/css">
*{
  padding: 0;
  margin: 0;
}
.contact{
  width: 40%;
  display: block;
  margin: auto;
  margin-top: 20px;
  padding: 10px;
  box-shadow: 1px 1px 2px;
  border-radius: 7px;
  background: #f9fcfc;
}
.contact h1{
  color: #06062a;
  font-size: 28px;
  margin: 0px;
  padding: 0px;
  border-bottom: 1px dashed #ddd;
}
.contact p{
  padding: 5px;
}
form{
  padding-bottom: 35px;
}
input{
  width: 47%;
  position: relative;
  float: left;
  margin-bottom: 10px;
  height: 25px;
}
input:nth-child(1),input:nth-child(3){
  margin-right: 5px;
}
textarea{
  width: 98%;
  margin-bottom: 10px;
}
input,textarea{
  background: #fff;
  border:1px solid #eee;
  border-radius: 5px;
  padding: 5px;
}
input[type="submit"]{
  background: #5ca830;
  height: 35px;
  color: #fff;
  font-size: 16px;
  font-weight: 650;
  border: none;
  border-radius: 8px;
  cursor: pointer;
}
#msg{
  width: 100%;
}
@media screen and (max-width: 960px){
 .contact{
  width: 60%;
 }
}
@media screen and (max-width: 767px){
 .contact{
  width: 90%;
 }
}
@media screen and (max-width: 640px){
 input{
  width: 98%;
 }
 textarea{
  width: 98%;
 }
}
</style>
</head>
<body>
<div class="contact">
<h1>Contact Form</h1>
<p>All the fields are required</p>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="text" name="name" placeholder="Name" required>
<input type="tel" name="phone" placeholder="Phone Number" required>
<input type="email" name="email" placeholder="Email Address" required>
<input type="text" name="subject" placeholder="Message Subject" required>
<textarea name="message" rows="4" placeholder="Write your message here..." required></textarea>
<nput type="submit" name="submit" value="Send Message">
<p id="msg"><?php echo $msg;?></p>
</form>
</div>
</body>
</html>

 

We collect the form inputs (name, email, phone, subject and message) using HTTP post method upon clicking of “Send message” button and send them to the recipient email address.

<?php echo $_SERVER['PHP_SELF']?>” in action attribute of the opening form tag simply echos out the file name of the current page. We use the filename of this page because the PHP script handling our form is on the same page.

In case you want to send the email via an external php script, assign the action attribute with the name of the php file(eg. “ action = 'sendmail.php'”) or file path in case the file is in a different directory/folder(eg. “ action = 'path/to/file/sendmail.php'”).

Below is the form that we just created with the above code. I have set it to send email to your account email address when you click the “Send Message” button.

Note:
Though the PHP mail() function looks pretty much simple to work with, as a general opinion many people do not encourage its usage due to some of these reasons:

  • Wrong format of mail header or content (e.g. differences in line break between Windows/Unix).
  • Errors in the format of header or content can easily cause the mails to be treated as SPAM. In most cases, emails sent via default php mail() function lands in the spam folder.
  • PHP mail() function sends emails using a local sendmail program on Linux, BSD and OS X platforms. However, Windows usually doesn't include a local mail server and thus the function won't work on a windows server. Also when using local servers such as XAMPP or WAMPP it will require some more configurations to work.

According to the official PHP.net manual, mail() function is not suited for sending any substantial amount of emails.

Note

It is worth noting that the mail() function is not suitable for larger volumes of email in a loop. This function opens and closes an SMTP socket for each email, which is not very efficient.

For the sending of large amounts of email, see the » PEAR::Mail, and » PEAR::Mail_Queue packages.

 

Personally, I began by sending emails using the mail() function but later changed to PHPMailer, a free/open-source php mailing library.

The mailing libraries have SMTP integration that allows email sending without a local mail server. Examples of these libraries are PHPMailer and Swiftmailer among others.