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.
The steps below shows you how to set up and use the PHPMailer library:
include('/path/to/class.phpmailer.php'); $content = 'Hello world!'; $email = new PHPMailer(); $email->From = 'firstname.lastname@example.org'; $email->FromName = 'Your Name'; $email->Subject = 'Subject'; $email->Body = $content; $email->AddAddress( 'email@example.com' ); $file = '/path/to/file/file.zip'; $email->AddAttachment( $file, 'file.zip' ); return $email->Send();
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.