Send an Email with PDF Attachment – PHP

To send pdf with your email in PHP, here is what you need to do:

I am using php mail function to do that

$fileatt = "./yourpdf.pdf"; // Path to the file
$fileatt_type = "application/pdf"; // File Type
$fileatt_name = "pdfname.pdf"; // Filename that will be used for the file as the attachment

$email_from = "from_emailaddress"; // Who the email is from
$email_subject = "Your subject here"; // The Subject of the email

$email_message="Your Message\r\n\n";

$email_to = "to_emailaddress"; // Who the email is to

$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));

$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$email_message .= "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$email_message .= "\n\n";

$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data .= "\n\n" .

$sent = @mail($email_to, $email_subject, $email_message, $headers);

You can change $fileatt_type to send other attachments.

Tags: , ,
Subscribe to Comments RSS Feed in this post

3 Responses

  1. You can change $fileatt_type to send other attachments.

  2. If include more then one line in email_message,the pdf is not getting attached ,i tried using and \n ,but its mot working.
    if i use \n the email formatting doesnt happen instead \n is appearing in my message.
    my email_message format is something like this.

    Hello user,
    pls find the attachment.

    for more info

    phone no.

  3. sorry this is not working for me

    attachment file source is fully displayed in message with encrypted source…………..

    please give me solution……


Leave a Reply

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