PHPMAILER: Attach A File To An Email In PHP

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

  • Import the PHPMailer Lib into your project either using Autoloader or Include. Library can be found @
  • Implement the code as below:


include('phpmailer.php');

$email = new PHPMailer();
$email->From = ‘##Source Mail ID##’;
$email->FromName = ‘##Mailer Name##’;
$email->Subject = ‘##Subject##’;
$email->Body = ‘##Content##’;
$email->AddAddress( ‘##destination Mail ID##’ );
$file = ‘##Path to File to be attached##’;
$email->AddAttachment( $file, ‘##label of file that is attached##’ );
return $email->Send();

if we want to attach a file to an email directly from an upload, you can pass in the uploaded file from the $_FILES global like so
$email->AddAttachment( $_FILES['attachment']['tmp_name'], $_FILES['attachment']['name'] );

Make sure your mail server is configured and is working. In case not then follow this to setup a local open source mail server

Leave a Reply