How to attach pdf in mail with phpmailer

To attach a PDF file to an email using PHPMailer, you can follow these steps:

  1. First, make sure you have the PHPMailer class included in your PHP script. You can do this by including the PHPMailer file:

    require_once 'PHPMailer/PHPMailer.php';
    require_once 'PHPMailer/SMTP.php';
    require_once 'PHPMailer/Exception.php';
  2. Create a new instance of the PHPMailer class:

    $mail = new PHPMailer\PHPMailer\PHPMailer();
  3. Set the email sender and recipient information:

    $mail->setFrom('[email protected]', 'Your Name');
    $mail->addAddress('[email protected]', 'Recipient Name');
  4. Set the email subject and body:

    $mail->Subject = 'Test Email with PDF Attachment';
    $mail->Body = 'This is a test email with a PDF attachment.';
  5. 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.

  6. 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.