How to send attachment in mail in phpmailer

To send an attachment in a mail using PHPMailer, you can use the addAttachment() method. Here's an example:

<?php
require_once 'PHPMailer/PHPMailer.php';
require_once 'PHPMailer/SMTP.php';
require_once 'PHPMailer/Exception.php';

$mail = new PHPMailer\PHPMailer\PHPMailer();

$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

$mail->setFrom('[email protected]', 'Your Name');
$mail->addAddress('[email protected]', 'Recipient Name');

$mail->isHTML(true);

$mail->Subject = 'Test Email with Attachment';
$mail->Body = 'This is a test email with attachment';

$attachment = 'path/to/your/attachment.pdf'; // replace with your attachment path
$mail->addAttachment($attachment, 'application/pdf', 'attachment.pdf', 'Test Attachment');

if (!$mail->send()) {
    echo 'Error sending email: '. $mail->ErrorInfo;
} else {
    echo 'Email sent successfully!';
}
?>

In the above example, the addAttachment() method is used to add an attachment to the email. The method takes four parameters:

  1. attachment: The path to the attachment file.
  2. mimetype: The MIME type of the attachment (optional, defaults to the MIME type of the file).
  3. attachmentName: The name of the attachment (optional, defaults to the original file name).
  4. encoding: The encoding of the attachment (optional, defaults to base64).

You can also use the addStringAttachment() method to send a string as an attachment:

$mail->addStringAttachment($string, 'attachment.txt', 'text/plain', 'Test Attachment');

Make sure to replace the placeholders ('smtp.example.com', '[email protected]', 'your_password', '[email protected]', '[email protected]', and 'path/to/your/attachment.pdf') with your actual email settings and attachment path.