How to Attach Remote File to Email using PHPMailer
In this tutorial, we will learn about how to attach remote file to email using PHPMailer library.
PHPMailer provides a convenient method addAttachment() to attach files to email. However, this method does not work with remote files stored on remote server.
Therefore, we will use other method that will solve issue of file attachment to email from remote server using PHP.
In this guide, we will need to send email using PHPMailer library with remote file attachment. If you are not aware of how to send email in PHP using PHPMailer then you can check out our tutorial about it.
After that we will need to check if file exists on remote server using PHP.
It is important because first we need to make sure that file exists on remote server then we can attach that file in our email.
Use the below code snippet to check if remote file exists using PHP.
// Remote file URL
$remote_file_url = 'https://www.example.com/pdf/filename.pdf';
// Open file using fopen() function
$file_exist = @fopen($remote_file_url, 'r');
// Check if file exists on remote server
if($file_exist){
echo 'Remote file exists.';
}else{
echo 'Remote file is not found!';
}
Now, we know how to check if remote file exists on server using PHP. We can easily attached the remote file to our email using the below code.
Code to Attach Remote File:
// if remote file exists, attach it in your php mailer email
if($file_exist){
$mail->addStringAttachment(file_get_contents($remote_file_url), 'file.pdf');
}
You will need to attach remote file before $mail->Send(); in your PHP mailer email.
This will send the remote file as an attachment in your email.
Conclusion
By now we hope that you have learnt how to attach remote file to email using PHPMailer library by using the above simple method.
If you found this tutorial helpful, share it with your friends and developers group.
I spent several hours to create this tutorial, if you want to say thanks so like my page on Facebook, Twitter and share it.
Facebook Official Page: All PHP Tricks
Twitter Official Page: All PHP Tricks