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:
    • 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:
    • 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:
    • 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:
    • 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:
    • 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:
    • 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:
    • 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.


Please enter your comment!
Please enter your name here