Attach a file to an email in PHP using PHPMailer

This article looks at how you can attach a file to an email in PHP using PHPMailer. Using this library saves you a whole load of hassle writing the code yourself, which you would need to wrap around the PHP mail() function.

PHPMailer library

The steps below shows you how to set up and use the PHPMailer library:

  1. Download the PHPMailer library at
  2. Extract the files to a folder in your application, e.g. a library folder
  3. Include the class.phpmailer.php file in your code
  4. Implement the code as below:

        $content = 'Hello world!';

        $email = new PHPMailer();
        $email->From      = '';
        $email->FromName  = 'Your Name';
        $email->Subject   = 'Subject';
        $email->Body      = $content;
        $email->AddAddress( '' );
        $file = '/path/to/file/';
        $email->AddAttachment( $file, '' );
        return $email->Send();

Attaching a file uploaded from a form

The above code assumes the attachment is already stored on your server, or that you've stored a file that has been uploaded from a form before sending the email. What if we want to attach a file to an email directly from an upload?

To achieve this, you can pass in the uploaded file from the $_FILES global like so:

$email->AddAttachment( $_FILES['attachment']['tmp_name'], $_FILES['attachment']['name'] );

Note this assumes your upload file name tag is 'attachment'. You would also want to add some security checks to the uploaded file to ensure uploaded files are safe to be sent to the recipient.

Sign Up

NEXT: Build an HTML5 responsive contact form

In this tutorial we'll be using the latest HTML5 form attributes with modern CSS responsive techniques to create a flexible, cross-platform contact form.

comments powered by Disqus

Popular Tags

Need a web developer?

If you'd like to work with code synthesis on your next project get in touch via the contact page.