How to Send Email Attachments via PHP
While sending an email, it is often necessary to send attachments with it, too. In this tutorial, we are going to illustrate how to send attachments with PHP mail easily.
Just follow the steps below.
Using the PHPMailer Script
The PHPMailer script is the most straightforward option of sending attachments with PHP.
To use it, you need to follow the steps below:
As a first step, you need to download the PHPMailer script from this source: http://github.com/PHPMailer/PHPMailer
Extract and Copy
The next step is extracting the archive and copying the script’s folder to an appropriate place within the project.
Include the Main Script File
The third step is including the main script file in the following way:
Finally, you can see that sending emails with attachments becomes insanely simple. To be more precise, let’s consider an example:
use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; $email = new PHPMailer(); $email->SetFrom('[email protected]', 'Your Name'); //Name is optional $email->Subject = 'Message Subject'; $email->Body = $bodytext; $email->AddAddress('[email protected]'); $file_to_attach = 'PATH_OF_YOUR_FILE_HERE'; $email->AddAttachment($file_to_attach, 'NameOfFile.pdf'); return $email->Send();
So, we can state that the PHPMailer script is an easy and efficient way to send attachments with PHP.
There is an alternative means such as PHP mail() function, but we don’t recommend to use it. The reason is that it can have a lot of bugs and will make you stack of code in the process of writing it.
PHPMailer is considered a classic email sending library for PHP. It supports various means to send email messages. Among them are qmail, mail(), Sendmail, and so on. Moreover, it includes a range of additional advanced features such as support of TLS and SSL protocols, SMTP authentication, HTML content along with plain text, and more.