What are some best practices for sending email attachments using PHPMailer or Swiftmailer?

When sending email attachments using PHPMailer or Swiftmailer, it is important to ensure that the attachments are properly encoded and added to the email message. This can be done by specifying the file path, MIME type, and file name for each attachment. Additionally, it is recommended to check if the file exists before attaching it to the email.

// Example code using PHPMailer to send an email with attachments
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer(true);

try {
    // Server settings
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your@example.com';
    $mail->Password = 'your_password';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    // Attachments
    $mail->addAttachment('/path/to/file.pdf', 'document.pdf');

    // Recipients
    $mail->setFrom('from@example.com', 'Sender Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');

    // Content
    $mail->isHTML(true);
    $mail->Subject = 'Subject';
    $mail->Body = 'Email body content';

    $mail->send();
    echo 'Email sent successfully';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}