banner Hi, this is Shiva Kumar. You can call me Shiva. I'm a developer like you. Earlier I used to write articles for Computers Today. Now I started this web site to help each other ( or ) atleast contribute some thing from my end. I'm always a student, if you need any articles or help which is not there in this web site, please send me a mail. I will try to update them in this web site if possible.
May
10th

How to send attachments with email using PHP

Author: admin | Files under php



Introduction

Sending mails with php is simple and easy. Now, in this tutorial we will move a step forward to see how easy it is to send attachments thru these mails. To send email attachments you need to make use of MIME (Multipurpose Internet Mail Extensions) - a mechanism that allows email to go beyond a basic, limited character set.

In this tutorial, I will try to explain sending mail attachments in php using two methods as follows:

•    Sending email attachments using the php mail() function
•    Sending email attachments using the PEAR::Mail class


Sending email with attachments using the php mail() function

As I said earlier, MIME type is the most important for sending mail attachments, so for the purpose of this tutorial I am using multipart/mixed MIME email - this means we can send a text email and attach a zip file to it.

Sending mail attachments in php is simple but looks complex outside, so, we divide the things into following steps:

•    Set the Email and Attachment Details
•    Read in the Attachment
•    Add the MIME content
•    Send the email

Set the Email and Attachment Details

The email details are obvious. We need mail-to, from and subject details.  For the attachments, we need the path to the file and the headers for the file type (zip in this case).

  1.  
  2. <?php
  3.  
  4. $to = "$name <$email>";
  5. $from = "John-Smith <john.smith@domain.com>";
  6. $subject = "Here is your attachment";
  7.  
  8. $fileatt = "/public_html/extra/important.zip";
  9. $fileatttype = "application/zip";
  10. $fileattname = "most_important.zip";
  11.  
  12. $headers = "From: $from";
  13.  
  14. ?>
  15.  

Here, we have to observe one thing, see the $fileatt, we specified the filename “important. Zip” that is going to attach. Then, the $fileattname variable determines the name of the attachment we specified most_important.zip.

So, the attached file and attachment name can be different and doesn’t have to match the name of the original file (I did not want to confuse, as of now just think it like that)

Read in the Attachment

Now, we will read the attachment file contents into a variable as follows:

  1.  
  2. <?php
  3.  
  4. $file = fopen( $fileatt, ‘rb’ );
  5. $data = chunk_split(base64_encode(fread( $file, filesize( $fileatt ) ));
  6. fclose( $file );
  7.  
  8. ?>
  9.  

You have noticed the second line, it reads the contents of the file and encodes it and converted a format that is compatible with standard email: 7-bit ASCII.

Add the MIME content

In this section we will add the MIME content and creates the headers and message content along with attachment as follows:

  1.  
  2. <?php
  3.  
  4. $semi_rand = md5( time() );
  5.  
  6. $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
  7.  
  8. $headers .= "\nMIME-Version: 1.0\n" .
  9. "Content-Type: multipart/mixed;\n" .
  10. " boundary=\"{$mime_boundary}\"";
  11.  
  12. $message = "This is a multi-part message in MIME format.\n\n" .
  13. "–{$mime_boundary}\n" .
  14. "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
  15. "Content-Transfer-Encoding: 7bit\n\n" .
  16. $message . "\n\n";
  17.  
  18. $message .= "–{$mime_boundary}\n" .
  19. "Content-Type: {$fileatttype};\n" .
  20. " name=\"{$fileattname}\"\n" .
  21. "Content-Disposition: attachment;\n" .
  22. " filename=\"{$fileattname}\"\n" .
  23. "Content-Transfer-Encoding: base64\n\n" .
  24. $data . "\n\n" .
  25. "–{$mime_boundary}–\n";
  26.  
  27. ?>
  28.  

Send the email

Till now, we created message content (by reading the attachment file and adding the message boundaries) and filled the mail and its attachment details. Now, the final part, in which we will send mail using the php mail function as follows:

  1.  
  2. <?php
  3.  
  4. if( mail( $to, $subject, $message, $headers ) ) {
  5.  
  6. echo "<p>The email was sent.</p>";
  7.  
  8. }
  9. else {
  10.  
  11. echo "<p>There was an error sending the mail.</p>";
  12.  
  13. }
  14. ?>
  15.  

If you want to send HTML text in the mail, instead of specifying “Content-Type: text/plain; charset=”iso-8859-1” specify content type as HTML, as follows “Content-Type: text/html; charset=”iso-8859-1″” and add the HTML content to the message and it will look as follows:

  1.  
  2. $message = "<h2>Hello World!</h2>
  3. <p>This is something with <b>HTML</b> formatting.</p>.\n\n" .
  4. "–{$mime_boundary}\n" .
  5. "Content-Type: text/html; charset=\"iso-8859-1\"\n" .
  6. "Content-Transfer-Encoding: 7bit\n\n" .
  7. $message . "\n\n";
  8.  



Sending email attachments using the PEAR::Mail class

PEAR stands for PHP Extension and Application Repository; this is a collection of PHP reusable classes. PEAR::Mail is a class in the PEAR package and does much the same as using mail (), with the exception that it is slightly powerful and flexible.

I want to explain not only how to use PEAR::Mail to send attachments but, also some very important (and most often, these important things are always missed by people) considerations behind this program. So, first see the program to send mail attachments using the PEAR::Mail as follows:

  1.  
  2. <?php
  3.  
  4. include_once(‘Mail.php’);
  5. include_once(‘mime.php’);
  6.  
  7. // email address of the recipient
  8. $to = "coolersport@yahoo.com";
  9.  
  10. // email address of the sender
  11. $from = "khiemprincess@yahoo.com";
  12.  
  13. // subject of the email
  14. $subject = "Hello world from coolersport";
  15.  
  16. $text = “This is the message content of the mail”;
  17.  
  18. $message = new Mail_mime();
  19.  
  20. $message->setTXTBody($text);
  21.  
  22. $message->addAttachment(‘sample.pdf’,’ application/pdf’);
  23.  
  24. $body = $message->get();
  25.  
  26. $extraheaders = array("From"=>$from, "Subject"=>$subject);
  27.  
  28. $headers = $message->headers($extraheaders);
  29.  
  30. $mail = Mail::factory("mail");
  31. $mail->send($to, $headers, $body);
  32.  
  33. echo "Your Email with attachment was sent.";
  34.  
  35. ?>
  36.  

I will try to explain the above example by dividing into steps as follows:
•    Including the files, does it is required?
•    Using the mime to add mail content and attachments
•    Creating the headers of the mail
•    Sending the mail

Including the files, does it is required?

The first two lines of code are just including the two files, Mail.php and mime.php. These two files contain the classes PEAR::Mail and PEAR::Mail_Mime which contain all the important functions that will do our work. Make sure that you are using the correct path where these two file are located on your server.

  1.  
  2. include_once(‘Mail.php’);
  3. include_once(‘mime.php’);
  4.  

This kind of including the files is required before using any PEAR::Mail functions.

Using the mime to add mail content and attachments

PEAR::Mail was just there to lay the groundwork for our use of attachments. You see, there is a very close cousin of PEAR::Mail called PEAR::Mail_Mime, and this has a number of features to make sending attachments with PEAR::Mail emails very easy.

We can create an instance of the mime class as follows:

  1.  
  2. $message = new Mail_mime();
  3.  

Now, if you want to add plain text to the mail, use the setTXTBody function as follows:

  1.  
  2. $message->setTXTBody($text);
  3.  

And also, if you want to add HTML content to the message, we can call another function called as setHTMLBody as follows:

  1.  
  2. $message->setHTMLBody($html);
  3.  

Now another, interesting thing is sending attachments to the mail. This can be done by calling the addAttachment function as follows:

  1.  
  2. $message->addAttachment(‘sample.pdf’,’ application/pdf’);
  3.  

Suppose, if you want to send text file as an attachment then, use as follows:

  1.  
  2. $message->addAttachment(‘sample.txt’,’ text/plain’);
  3.  

Creating the headers of the mail

Here, things start bit complicated the needed headers of the mail, are from and subject which we passed to and created an array as follows:

  1.  
  2. $extraheaders = array("From"=>$from, "Subject"=>$subject);
  3.  

Now, when sending complex emails, you need to have a special set of headers in there that tells the mail reader what to expect. This can be done using the headers function which is provided by the mime class. So, once you have your content in place, you just call headers() to get the header information as follows:

  1.  
  2. $headers = $message->headers($extraheaders);
  3.  

See, we send $extraheaders as an argument to the headers function, because, we still need to use the old headers (from, subject, etc), So, you can pass into headers() function an array of existing headers, and it will add these to the array it returns.

Sending the mail

Now, we have every thing in place, mail content, attachments and headers. So, just send a mail as follows:

  1.  
  2. $mail = Mail::factory("mail");
  3. $mail->send($to, $headers, $body);
  4.  

NOTE: The first line creates a default instance of PEAR::Mail - the parameter “mail” is passed in so that PEAR::Mail will use PHP’s mail() function to send the email. If you pass in “sendmail”, it will send direct via the sendmail program (Unix only).

Similar Posts - 90% of Users have seen these posts also

One response. Wanna say something?

  1. KrisBelucci
    Jun 2, 2009 at 19:04:50
    #1

    Hi, good post. I have been wondering about this issue,so thanks for posting.

Post a Comment