dello 0 Light Poster

Hi,

Hope this makes sense and hope someone can help me.

I have a database table with the following columns: person_id, firstname, surname, email_address.

Periodically I am given a set of files to send to some of the contacts in the database table. The filenames contain the person_id and they are always of the format: person_id.pdf or person_id-2.pdf. Sometimes there is only one of the files available or sometimes it is both of the files. The files are stored in a directory on our server

Example.
directory: letters
files: 1111.pdf, 1111-2.pdf, 2222.pdf, 3333-2.pdf

The user with person_id 1111: should receive an email with two attachements - 1111.pdf and 1111-2.pdf
The user with person_id 2222: should receive an email with one attachement - 2222.pdf
The user with person_id 3333-2: should receive an email with one attachement - 3333-2.pdf

This is just a small example, in real world scenario it could be hundreds of users to send these files to so I need an automated way using PHP to acheive this.

I have got to a point where:
The user with person_id 2222: receives the correct email
The user with person_id 3333: receives the correct email
However the user with person_id 1111: always receives two emails containing the same content.

I think this is because both files exist so whilst executing the loop it is doing it once for each file so my logic is flawed and I can't figure it out.

The way my file is built is:

Use PHPMailer

Make data connection

Submit button - once clicked:

loops through my letters directory to find the files
set filenames as variables to use
use substr on the filename to extract the person_id
run db query to retrieve relevant record where person_id = "filename" (minus the .pdf or -2.pdf)
attach relevant files and send email.

I have attached a copy of my code to hopefully show what I am trying to acheive.

Please ask if you would like further clarification.

I am aware my PHP may have all sorts of errors or non best practice methods but I am learning all time

Kind Regards
Mr Dello

Dani AI

Generated

Based on 's description, the duplicate emails come from sending inside the file loop — when two files match the same person you end up sending twice. The reliable pattern is: 1) scan the directory and group filenames by person_id, 2) fetch that user's info once, 3) build one message and attach every file for that person, then send. That prevents duplicate sends and makes sending efficient for large batches.

Example workflow (compact, copy/adapt to your setup):

$files = glob(__DIR__ . '/letters/*.pdf');
$groups = [];
foreach ($files as $path) {
    $name = basename($path);
    if (preg_match('/^(\d+)(?:-2)?\.pdf$/i', $name, $m)) {
        $id = $m[1];
        $groups[$id][] = $path;
    }
}

/* use PDO prepared statement */
$stmt = $pdo->prepare('SELECT firstname,surname,email_address FROM contacts WHERE person_id = ?');

foreach ($groups as $id => $attachments) {
    $stmt->execute([$id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$user) continue;

    $mail = new PHPMailer(true); /* new instance per recipient */
    /* configure SMTP/auth here */
    $mail->setFrom('noreply@example.com', 'Sender');
    $mail->addAddress($user['email_address'], $user['firstname'].' '.$user['surname']);
    foreach ($attachments as $file) {
        if (is_readable($file)) $mail->addAttachment($file);
    }
    $mail->Subject = 'Your letters';
    $mail->Body = 'Please find attached.';
    $mail->send();
}

Troubleshooting and cautions: instantiate PHPMailer inside the recipient loop (or call clearAttachments/clearAddresses) so state doesn't persist. Use prepared statements and validate person_id extraction (adjust the regex if IDs can contain non-digits). Log successes/failures and throttle sends (sleep or queue) to avoid SMTP limits. For large attachments consider streaming or a download link instead of attaching many big files.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.