What security considerations should be taken into account when sending emails with attachments in PHP?

When sending emails with attachments in PHP, it is important to sanitize the file paths and filenames to prevent any potential security vulnerabilities such as directory traversal attacks. Additionally, it is recommended to set appropriate file permissions on the uploaded files to prevent unauthorized access. Finally, consider implementing file type validation to ensure that only allowed file types are attached to the email.

// Sanitize file path and filename
$attachment_path = '/path/to/attachment.pdf';
$attachment_name = 'attachment.pdf';

// Set appropriate file permissions
chmod($attachment_path, 0644);

// File type validation
$allowed_types = array('pdf', 'doc', 'docx');
$extension = pathinfo($attachment_name, PATHINFO_EXTENSION);

if (!in_array($extension, $allowed_types)) {
    die('Invalid file type');
}

// Attach the file to the email
$mail->addAttachment($attachment_path, $attachment_name);