This article looks at how you can attach a file to an email in PHP using PHPMailer. We have already written a tutorial on send email using PHPMailer. In this tutorial we didn’t go to re-invent the complete code simply add attachment and proceed.
Download the PHPMailer library.
Extract the files to a folder in your application.
Include the class.phpmailer.php file in your code require_once(‘PHPMailer/class.phpmailer.php’);
Implement the code as below:
require_once('PHPMailer/class.phpmailer.php');
$mail = new PHPMailer();
$address = "demo@gmail.com";
$mail->AddReplyTo("demo@gmail.com","demo");
$mail->SetFrom('demo@gmail.com', 'demo');
$mail->AddReplyTo("demo@gmail","replay");
$mail->AddAddress($address, "Demo");
$mail->Subject = "Attachment Test";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$body = "Mail body in HTML";
$mail->MsgHTML($body);
$mail->AddAttachment("demo1.pdf");
$mail->AddAttachment("demo2.pdf");
$mail->AddAttachment("demo3.pdf");
$mail->AddAttachment("demo4.pdf");
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message sent!";
}