I have received requests from my readers to write an article on send email with attachment, so in this tutorialÂ I am going to show you how to send email with attachment in PHP. We have already write a tutorial on send email withÂ SMTP and PHP Mailer. In this tutorial we didn’t go to re-invent the complete code simply add attachment and proceed.
Also Read: Send Email with SMTP and PHP Mailer
I have used SMTP email using phpmailer (A full-featured email creation and transfer class for PHP) library.
require_once('PHPMailer_v5.1/class.phpmailer.php'); //library added in download source.
$msg = 'Hello World';
$subj = 'test mail message';
$to = 'email@example.com';
$from = 'firstname.lastname@example.org';
$name = 'My Name';
echo smtpmailer($to,$from, $name ,$subj, $msg);
function smtpmailer($to, $from, $from_name = 'Example.com', $subject, $body, $is_gmail = true)
$mail = new PHPMailer();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->Username = 'email@example.com';
$mail->Password = '*******';
$mail->Sender=$from; // indicates ReturnPath header
$mail->AddReplyTo($from, $from_name); // indicates ReplyTo headers
//$mail->AddCC('firstname.lastname@example.org', 'CC: to phpgang.com');
$mail->Subject = $subject;
$mail->Body = $body;
$error = 'Mail error: '.$mail->ErrorInfo;
$error = 'Message sent!';
This is the simple code to send email to any one without attachment no you have to just add a single line and send this email with attachment.
$mail->AddAttachment($path); // $path: is your file path which you want to attach like $path = "reload.png";
Just using this line of code beforeÂ $mail->Send() statement it will attach that file and send it. if you want to attach multiple files then add separate attachment method for each file.
If you want more option in attachment like name, MIME and file type use it like this.
$mail->AddAttachment($path,$name,$encoding,$type); // advance parameters for attachment.
To upload a file you can use our file upload tutorial and send that file in attachment.
I hope it helps please do share a with your friends circles and give us your feedback so we can improve our upcoming tutorials.