How to send a attachment with PHP Mail
PHPMailer is one of the most popular open source PHP libraries to send emails. so in this tutorial I am going to show you how to send email with attachment in
PHPMailer library1) Download the
PHPMailerlibrary 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
4) Implement the code as below:
include('/path/to/class.phpmailer.php'); $all_data = "<table class='border'><tr><td>Article Name</td><td>View</td></tr>"; $all_data .= "<tr><td>Article 1</td><td>10</td></tr>"; $all_data .= "<tr><td>Article 2</td><td>12</td></tr>" $all_data .= "</table>"; file_put_contents("blog-log/blog-view.html", $all_data); $subject = "Blog View Report ". date('Y-m-d'); //PHPMailer Object $mail = new Mail(); $mail->setFrom("email@example.com"); $mail->setSender("My Name"); $mail->setSubject($subject); $mail->setTo("firstname.lastname@example.org"); $mail->setHtml("PFA"); //path to source file $mail->addAttachment("blog-log/blog-view.html"); $mail->send();
To add attachments to the email we just need to call the function
addAttachmentof the PHPMailer object by passing the file path as argument. For attaching multiple files we need to call it multiple times.
Just using this line of code before
$mail->Send() statement it will attach that file and send it.