How to attach pdf in mail with phpmailer
To attach a PDF file to an email using PHPMailer, you can follow these steps:
-
First, make sure you have the
PHPMailer
class included in your PHP script. You can do this by including thePHPMailer
file:require_once 'PHPMailer/PHPMailer.php'; require_once 'PHPMailer/SMTP.php'; require_once 'PHPMailer/Exception.php';
-
Create a new instance of the
PHPMailer
class:$mail = new PHPMailer\PHPMailer\PHPMailer();
-
Set the email sender and recipient information:
$mail->setFrom('[email protected]', 'Your Name'); $mail->addAddress('[email protected]', 'Recipient Name');
-
Set the email subject and body:
$mail->Subject = 'Test Email with PDF Attachment'; $mail->Body = 'This is a test email with a PDF attachment.';
-
Attach the PDF file to the email:
$mail->addAttachment('path/to/your/pdf/file.pdf', 'application/pdf');
In the above code, replace
'path/to/your/pdf/file.pdf'
with the actual path to the PDF file you want to attach. -
Finally, send the email using the
send()
method:$mail->send();
Here's the complete code:
<?php require_once 'PHPMailer/PHPMailer.php'; require_once 'PHPMailer/SMTP.php'; require_once 'PHPMailer/Exception.php';
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->setFrom('[email protected]', 'Your Name'); $mail->addAddress('[email protected]', 'Recipient Name');
$mail->Subject = 'Test Email with PDF Attachment'; $mail->Body = 'This is a test email with a PDF attachment.';
$mail->addAttachment('path/to/your/pdf/file.pdf', 'application/pdf');
if (!$mail->send()) { echo 'Error sending email: '. $mail->ErrorInfo; } else { echo 'Email sent successfully!'; } ?>
Make sure to replace the placeholders (`[email protected]`, `[email protected]`, and `path/to/your/pdf/file.pdf`) with the actual values.