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 https://github.com/PHPMailer/PHPMailer
  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
    include('/path/to/class.phpmailer.php');
  4. Implement the code as below:

        include('/path/to/class.phpmailer.php');
        $content = 'Hello world!';

        $email = new PHPMailer();
        $email->From      = 'you@yourdomain.com';
        $email->FromName  = 'Your Name';
        $email->Subject   = 'Subject';
        $email->Body      = $content;
        $email->AddAddress( 'receiver@gmail.com' );
        
        $file = '/path/to/file/file.zip';
        
        $email->AddAttachment( $file, 'file.zip' );
        
        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
Sign Up

Popular Tags

350x250

Need a web developer?

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