PHP Email

Today we will learn sending email with all its variations in this PHP Email tutorial.

  • PHP provides a very easy way to send email using a mail() function.
  • Automated email’s that are received when we create a new account on a site etc, can also be send using mail() function.
  • This mail() function takes 5 parameters:
    • to: this parameter is mandatory. It specifies the recipient’s email address(s).
    • subject: this parameter is mandatory. It specifies the subject of the email.
    • message: this parameter is mandatory. It specifies the actual message body. In PHP the message should not exceed 70 characters.
    • headers: this parameter is optional. It specifies additional headers like From, Content type, Cc, Bcc, etc. These headers should be separated with \r\n.
    • parameters: this parameter is optional. It specifies the additional parameters.
  • The variations that an email can have are listed below:
    • Email with a simple plain text.
    • Email with HTML content.
    • Email with attachments.
  • But to send email using PHP you need a working email server that you have permission to use. For UNIX machines often Sendmail is used and for windows machines a SMTP directive is to be set in the php.ini file to point to the mail server.
  • Email with a simple plain text:
    • Let us try sending a simple text message accepted by user in the email. For that we have to create a HTML form to accept the email-id to whom he wish to send the email, subject of the email and message of the email.
    • Then we will send the message using mail() function of php.
    • To demonstrate it, create a new folder named email in the htdocs folder in xampp folder. Open a new notepad++ document and save it as index.php in this newly created email folder.
    • So let us first see the code for the form for sending email:
    • <html>
      <head>
      <title>Send Email</title>
      <style>
      	#design{
      			border:magenta solid 5px;
      			border-radius:20px;
      			color:purple;
      			font-weight:bold;
      	}
      	h1{
      		color:purple;
      		margin-left:100px;
      		padding:10px;
      	}
      	label{
      		margin-left:20px;
      		display:inline-block;
      		width:60px;
      	}
      	.shift{
      		margin-left:20px;
      	}
      	.style{
      		margin-left:20px;
      		color:purple;
      		font-weight:bold;
      		border:magenta solid 1px;
      	}
      	input{
      		border:magenta solid 1px;
      	}
      	textarea{
      		border:magenta solid 1px;
      	}
      	.error{
      		color:red;
      	}
      	.sent{
      		padding:20px;
      		color:red;
      		font-weight:bold;
      	}
      </style>
      </head>
      <body id="design">
      <h1>Compose Mail</h1>
      <?php
      	if(!empty($errors))
      	{
      		foreach($errors as $err)
      			echo $err;
      	}
      ?>
      <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
      <label for="mail_to">To:</label>
      <input type="text" name="mail_to" value="<?php if(isset($_POST["mail_to"])) echo $_POST["mail_to"];?>"/>*<br>
      <label for="sub">Subject:</label>
      <input type="text" name="sub" value="<?php if(isset($_POST["sub"])) echo $_POST["sub"];?>"/>*<br>
      <label for="msg">Message:</label>*<br>
      <textarea class="shift" name="msg" rows="8" cols="40" ></textarea>
      <input type="submit" value="SEND MAIL" name="send" class="style" />
      </form>
      </body>
      </html>
      
    • Here, we have designed a form to accept the recipient’s email-id, subject and the message to be sent in the email.
    • It contains text fields to accept the recipient’s email, subject of the email and a textarea field to accept the message.
    • The value attribute of the input fields is used to retain the input entered by user.
    • Some styling is done to the fields in the form.
    • The errors in the array $errors[] are displayed in foreach loop as shown below:
    • <?php
      	if(!empty($errors))
      	{
      		foreach($errors as $err)
      			echo $err;
      	}
      ?>
      
    • The errors are stored in it during validation process.
    • To see the form open your browser and write localhost/email in the address bar of the browser.
    • The form looks as shown in the figure below:
    • form
      fig 1

    • The code for validation is written right above the HTML code. The validation code is given below:
    • <?php
      
      function clear()
      {
      	$_POST["mail_to"]="";
      	$_POST["sub"]="";
      	$_POST["msg"]="";
      }
      $satisfy=true;
      if(isset($_POST["send"]))
      {
      	$mail_to=$_POST["mail_to"];
      	$mail_from="[email protected]";
      	$mail_sub=$_POST["sub"];
      	$mail_msg=wordwrap($_POST["msg"],70);
      	
      	$mail_header="From: ".$mail_from."\r\n";
      	$mail_header.="Reply-to:".$mail_from."\r\n";
      	$errors=array();
      	
      	if(empty($mail_to))
      	{
      		$errors[]='<p class="error">* The email-id of recipient is compulsory.</p>';
      		$satisfy=false;
      	}
      	else
      	{
      		if(!preg_match('/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/',$mail_to))
      		{
      			$errors[]='<p class="error">* The recipients email is not in proper format.</p>';
      			$satisfy=false;
      		}
      	}
      	
      	if(empty($mail_sub))
      	{
      		$errors[]='<p class="error">* Subject of the mail is compulsory.</p>';
      		$satisfy=false;
      	}
      	
      	if(empty($mail_msg))
      	{
      		$errors[]='<p class="error">* Message cannot be null.</p>';
      		$satisfy=false;
      	}
      	
      	if($satisfy==true)
      	{
      		$mail_send=mail($mail_to,$mail_sub,$mail_msg,$mail_header);
      		if($mail_send==true)
      		{
      		echo '<p class="sent">** Your message has been sent successfully!</p>';
      		clear();
      		}
      		else
      		{
      		echo '<p class="sent">** Your message has not been sent!</p>';
      		}
      	}
      
      }
      ?>
      
    • The above code is used to validate the form and send its contents in the email.
    • We have declared a variable $satisfy which is initialized to true initially.
    • When anything is not validated, $satisfy will be set to false telling us that our form is not yet validated. But if its value remains true, it means our form is completely validated.
    • Next it is checked that whether the SUBMIT button has been clicked and if it is clicked, the values stored in the $_POST superglobal array variable are retrieved and stored in the local variables.
    • The message is compressed using the wordwrap() function since the mail functions allows message of upto 70 characters.
    • The email header includes from and reply-to fields.
    • The empty $errors array is declared to store the errors if any.
    • All the fields i.e. mail_to, mail_sub and mail_msg are checked to see if they are empty or not. If they are empty, a error message is stored in the $errors array and $satisfy variable is set to false.
    • If the mail_to field is not empty, it is checked to see if the email-id entered in it is in proper format or not using preg_match() function. If it is not in proper format, an error message is stored in $errors array.
    • After checking all the validations, it is checked if the value in $satisfy variable is true. If $satisfy variable contains value true, it means all the fields are validated perfectly.
    • At this time the mail() function is called to send the mail.
    • The mail function returns true on success, hence it’s returned value is stored in variable $mail_send.
    • Value of this $mail_send variable is checked and if it is true, a message Your message has been sent successfully! is displayed otherwise a message Your message has not been sent! is displayed.
    • The clear() function is then called to clear all the fields in the form.
    • The clear() function which is written at the top is shown below:
    • function clear()
      {
      	$_POST["mail_to"]="";
      	$_POST["sub"]="";
      	$_POST["msg"]="";
      }
      
    • Let us check if the validation works. Click the SEND MAIL button without entering the information in the fields. The output is shown below:
    • all_errors_output
      fig 2

    • Now let us fill incomplete information such as incomplete recipient’s email-id and no message in the form. We will get the respective error messages as shown in the following figure:
    • incomplete_form
      fig 3

    • We got 2 error messages that state that recipient’s email-id should be in proper format and message cannot be null.
    • Now let us fill the form completely as shown below:
    • complete_form
      fig 4

    • Now click on the SEND MAIL button. If the mail is sent successfully, the success message will be shown as follows:
    • mail_sent_output
      fig 5

    • This was a simple text message that we learned. Now let us learn how to send an email with HTML contents.
  • Email with HTML contents:
    • When we send a text message using PHP, all the contents will be treated as text.
    • In the text messages, HTML tags are also treated as a simple text.
    • But PHP provides the option to send the HTML messages as actual HTML messages.
    • For this we need to provide the proper content-type of the message.
    • Write the following code in index.php page:
    • <html>
      <head>
      <title>Send Email</title>
      <style>
      	#design{
      			border:magenta solid 5px;
      			border-radius:20px;
      			color:purple;
      			font-weight:bold;
      	}
      	h1{
      		color:purple;
      		margin-left:60px;
      		padding:10px;
      	}
      </style>
      </head>
      <body id="design">
      <h1>Compose Mail</h1>
      <?php
      	//sending Email with HTML content
      	$mail_to="[email protected]";
      	$mail_from="[email protected]";
      	$mail_sub="Wishing happy diwali.";
      	$mail_msg="<h1>Wish you and your family a very happy diwali.</h1>";
      	$mail_msg.="<strong>May this festival of lights and colours fill your life with glowing lights and colours.</strong>";	
      	$mail_header="From: ".$mail_from."\r\n";
      	$mail_header.="Reply-to:".$mail_from."\r\n";
      	$mail_header.="MIME-Version:1.0 \r\n";
      	$mail_header.="Content-type: text/html \r\n";
      	
      	$mail_send=mail($mail_to,$mail_sub,$mail_msg,$mail_header);
      	
      	if($mail_send==true)
      	{
      		echo '<p class="sent">** Your message has been sent successfully!</p>';
      	}
      	else
      	{
      		echo '<p class="sent">** Your message has not been sent!</p>';
      	}
      ?>
      </body>
      </html>
      
    • Here we have set value to the $mail_to variable, which is the recipient’s email-id. Then we have set the sender’s email-id in $mail_from variable, mail subject in $mail_sub variable, HTML message in $mail_msg variable and header in $mail_header variable.
    • The mail header contains the sender’s email-id, reply-to email-id, MIME version and the content-type. The text/html content type allows the html content to be treated as html content only.
    • Similarly attachments can also be attached to the mail.
  • Email with attachments:
    • We send mails with mixed contents such as text, html and attachments.
    • To allow transmission of this mixed content, the multipart/mixed content-type is to be specified in the header.
    • Next thing is the content of attachments is to be encoded and then is to be splitted into chunks for transmission.
    • Let us write the following code in index.php file to demonstrate mail with attachment:
    • <html>
      <head>
      <title>Send Email</title>
      <style>
      	#design{
      			border:magenta solid 5px;
      			border-radius:20px;
      			color:purple;
      			font-weight:bold;
      	}
      	h1{
      		color:purple;
      		margin-left:60px;
      		padding:10px;
      	}
      </style>
      </head>
      <body id="design">
      <h1>Compose Mail</h1>
      
      <?php
      	//sending email with attachment
      	$mail_to="[email protected]";
      	$mail_from="[email protected]";
      	$mail_sub="details of function used to send email.";
      	$mail_msg="Respected Sir,";
      	$mail_msg.="I have sent a text file that contains the details of the function used to send email using PHP.";
      	$mail_msg.="Thanks.";
      	
      	//read the text that is to be attached
      	
      	$fp=fopen("mail.txt","r");
      	if(!$fp)
      	{
      		echo "<br>Failed to attach.";
      	}
      		//read the file
      		$attachment=fread($fp,filesize("mail.txt"));
      //encode the read data for safe transit
      		$encode_attachment=base64_encode($attachment);
      		//split it into chunks
      		$attachment_in_chunks=chunk_split($encode_attachment);
      		
      		$unique=md5(time());
      		
      	//adding information to mail header
      	$mail_header="From: ".$mail_from."\r\n";
      	$mail_header.="Reply-to:".$mail_from."\r\n";
      	$mail_header.="MIME-Version:1.0 \r\n";
      	$mail_header.="Content-type:multipart/mixed \r\n";
      	$mail_header.="boundary=$unique \r\n";
      	$mail_header.=--$unique."\r\n";
      
      	//header for text message
      	$mail_header.="Content-type: text/plain \r\n";
      	$mail_header.=$mail_msg."\r\n";
      	$mail_header.=--$unique."\r\n";
      	
      	//header for attachment
      	$mail_header.="Content-type: multipart/mixed\r\n";
      	$mail_header.="filename: mail.txt\r\n";
      	$mail_header.=$attachment_in_chunks."\r\n";
      	$mail_header.=--$unique--."\r\n";
      		
      	//send email
      	
      	$mail_send=mail($mail_to,$mail_sub,"",$mail_header);
      	if($mail_send==true)
      	{
      		
      		echo '<p class="sent">** Your message has been sent successfully!</p>';
      	}
      	else
      	{
      		echo '<p class="sent">** Your message has not been sent!</p>';
      	}
      ?>
      </body>
      </html>
      
    • First of all copy the file you want to attach to the email and paste it in the email folder which is in the htdocs folder in xampp folder.
    • Now the steps to attach the file are:
      • First read the file using file handling and store the content in a variable.
      • Now encode the content in the variable using base64_encode() function.
      • After encoding it, break it into chunks for easy transmission.
    • Now let us see what all we have done in our program.
    • We have assigned the recipient’s email-id, sender’s email-id, email subject and message to variables $mail_to, $mail_from, $mail_sub and $mail_msg respectively.
    • Then after that we want to make our attachment ready for attachment.
    • So we read the mail.txt file contents using fread() function. The function filesize() calculates the file size in bytes.
    • The file name mail.txt is used directly without full path, because it is present right in our email folder where we have our index.php file. If it would have been somewhere else, we would have to use its full path.
    • The file contents are read in variable $attachment.
    • Then the contents in variable $attachment are encoded using base64_encode() function and stored into variable $encode_attachment. This gives safety during transmission.
    • This data stored in $encode_attachement is now broken down into smaller chunks using chunk_split() function. It adds \r\n into the file content at regular intervals, normally after every 76 characters.
    • The text and attachment can be specified within boundaries.
    • A boundary begins with 2 hyphens followed by a unique number. For the last section of the message, it even ends with 2 hyphens.
    • To generate a unique number we have used an md5() function with time() function as its parameter. It will create a 32 bit hexadecimal unique number everytime.
    • This number is stored in variable $unique and it attached in header of every section.
    • Next header for complete mail is specified with information like from, reply-to, content-type, MIME-type and boundary. Each data is attached with \r\n at the end.
    • The content-type multipart/mixed specifies that mixed content will be included in the email.
    • Next a header for message is specified with information like text/plain content type, message and unique boundary.
    • Next a header for attachment is specified with multipart/mixed content-type, filename, the actual attachment content and the boundary. In this case, as attachment is the last section the boundary starts as well as ends with 2 hyphens.
    • Then the mail() function is used to send the email as shown below:
    • $mail_send=mail($mail_to,$mail_sub,"",$mail_header);
    • Here, the message parameter in mail() function is kept blank because the text message and the attachment is attached to the header itself.
    • The mail() function returns true if the mail is sent successfully, otherwise it returns false.
    • So if it returns true, a message Your message has been sent successfully! is displayed otherwise a message Your message has not been sent! is displayed.
    • If you want you can add HTML content also, but for that don’t forget to include content-type as text/html.
    • When you reload your browser by saving the above code you will get the following output:
    • html_attachment_mail_sent_output
      fig 6

    • You will get the same output for Email with HTML content also.

This was all about sending email. We learned all types of email in a very simple way in this PHP Email tutorial.

Previous articlePHP Exceptions
Next articlePHP Filters

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -