Sometimes, we want to send attachments with PHP Mail().
In this article, we’ll look at how to send attachments with PHP Mail().
How to send attachments with PHP Mail()?
To send attachments with PHP Mail(), we can call the AddAttachment
method in PHPMailer.
We install it by running
composer require phpmailer/phpmailer
Then, we write
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$email = new PHPMailer();
$email->SetFrom('you@example.com', 'Your Name');
$email->Subject = 'Message Subject';
$email->Body = $bodytext;
$email->AddAddress('destinationaddress@example.com');
$file_to_attach = 'PATH_OF_YOUR_FILE_HERE';
$email->AddAttachment($file_to_attach , 'NameOfFile.pdf');
return $email->Send();
to create a new PHPMailer
object.
Then we call methods to add the from, subject, body and address.
Next, we call AddAttachment
to add the file by the file path and the file name of the attachment.
And then we call Send
to send the email.
Conclusion
To send attachments with PHP Mail(), we can call the AddAttachment
method in PHPMailer.