Attachment in php mail getting previous also getting attached

A common issue!

When you're sending an email with attachments in PHP using the mail() function or a library like PHPMailer, you might encounter a problem where the previous attachment is also being sent along with the new one. This is because the mail() function doesn't clear the attachment buffer between calls.

Here are a few solutions to resolve this issue:

1. Use a library like PHPMailer

PHPMailer is a popular and well-maintained library that provides a more robust way of sending emails with attachments. It has built-in support for clearing the attachment buffer, so you won't encounter this issue.

2. Use the clearAttachments() method

If you're using the mail() function, you can try calling the clearAttachments() method before sending the new attachment. This method is not a standard PHP function, but it's available in some PHPMailer forks or custom implementations.

3. Use a temporary file for the attachment

Instead of sending the attachment directly, you can write it to a temporary file and then send the file as an attachment. This way, you can ensure that the previous attachment is not sent along with the new one.

Here's an example:

$attachment = 'path/to/new/attachment';
$tmp_file = tempnam(sys_get_temp_dir(), 'attachment');
file_put_contents($tmp_file, file_get_contents($attachment));
$mail->addAttachment($tmp_file, 'attachment_name');
unlink($tmp_file);

4. Use a loop to send multiple attachments

If you need to send multiple attachments, you can use a loop to iterate over the attachments and send each one separately. This way, you can ensure that each attachment is sent individually and not mixed with previous attachments.

Here's an example:

$attachments = array('attachment1', 'attachment2', 'attachment3');
foreach ($attachments as $attachment) {
    $mail->addAttachment($attachment);
    $mail->send();
}

By implementing one of these solutions, you should be able to resolve the issue of previous attachments being sent along with the new one.