Email Attachments in PHP

April 28th, 2007

I've often been asked how to not just send emails from PHP, but how to send an attachment within the email as well. To send an attachment, you need to add extra headers, base64 encode the file and so on. In fact, it's not very easy to do.

However, there is a script around that makes this a lot easier by handling all the donkey work - PHPMailer. PHPMailer can handle almost anything you want to throw at it, including embedding images within the email, full blown HTML emails, using external SMTP servers to send the emails and so on. However, today, we're going to just concentrate on using PHPMailer to send an email with an attachment.

PHPMailer is a class based script, which means that you just need to include it into your PHP code, and fire it up:

PHP:
  1. <?php
  2. require("class.phpmailer.php");
  3. $mail = new phpmailer();
  4. $mail->From = 'me@mydomain.com';
  5. $mail->FromName = "My Site's Name";
  6. $mail->Subject = 'Email Subject';
  7. $mail->Body = "Here you can enter the body text for the email.
  8. In fact it can:
  9. >Span
  10. >Multiple Lines just like that!";
  11.  
  12. $mail->AddAddress("joe@brown.com","Joe Brown");
  13. $mail->AddAttachment("./picture.jpg");
  14. $mail->AddAttachment("./picture2.jpg");
  15. $mail->Send();
  16. ?>

As you can see, we've set the From details up, as well as the subject and body text. We can then add the recipient address, the attachment, and then send. That's all there is to it!

You can keep adding attachments as shown above. Just ensure that you provide the right path to the files!


 Add to del.icio.us    Digg this    Technorati

Related Posts:

Entry Filed under: PHP

2 Comments Add your own

  • 1. brito  |  May 7th, 2007 at 11:26 am

    i couldt found class.phpmailer.php file in Email Attachments in PHP posts….

  • 2. Alex  |  July 11th, 2007 at 3:05 pm

    Would I be able to use this method to send mp3's?

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Calendar

April 2007
M T W T F S S
« Aug   Aug »
 1
2345678
9101112131415
16171819202122
23242526272829
30  

Most Recent Posts