Sending html mails with attachment using PHP mail

For sending a simple mail, PHP provides the mail function

The mail function has the optional parameter $additional_header which can be used to set the From, Cc, Bcc fields. It can also be used to set the content-type to html for sending html mails

Sending html mails with PHP

Sending html mails with attachment

However in many situations you may wish to send a file as an attachment with some html message. Say your website has an form with resume upload for Job application. When someone fills the form you may want to send the applicant a thank you email with his uploaded resume as attachment.

For sending mails with attachment we can use the same mail function of PHP with little modification in the headers and the message body.

Below is the function for sending mails with attachment using PHP mail function

The above functions accepts an associative array as params. You can call this function as below

If you take a look at the send_mail() function you will notice that in the header we have declared the content type as multipart/mixed

The above header indicates that the message body will contain multiple parts and each will be separated by the $separator which is a unique key. For our case we have generated it using md5( time() ).

Then in the first part we send the html message

Notice the use of ‘–‘ before $separator and $eol as CRLF. Here $eol is nothing but PHP_EOL which is analogous to \r\n.

After appending the html message we now the append the attachment

The double slashes ‘–‘ appended to separator at the end marks the end of the message.

Join the discussion

  1. Srinivas says:

    sir, my requirement is attachment image display in html content of the body please give me suggestion.

  2. devesh pandya says:

    Its help me so much .Thanks for tutorial.

  3. Arun says:

    i need send email with table layout and also attachment? Did you know that?can you suggest me?

Leave a Reply

Your email address will not be published. Required fields are marked *