How to create unsubscribe link using PHPMAILER

1.4k views Asked by At

Struggling to implement an unsubscribe header

  • to single recipient it never creates the auto unsubscribe link (PASS DKIM, SPF & DMARC)
  • to multiple emails, it adds up the link into each email and kills DKIM

Any clue ? Thanks

foreach ($result as $row) {
    try {
        $mail->addCustomHeader(
            "List-Unsubscribe=One-Click",
            "<mailto:[email protected]?subject=Unsubscribe : $row['email']>, <https://cineferte.fr/abo.php?unsub=".$row['email'] . ">"
        );
            $mail->addAddress($row['email'], $row['nom']);
    } catch (Exception $e) {
        echo 'Email invalide: ' . htmlspecialchars($row['email']) . '<br>';
        continue;
    }
    try {
        $mail->send();
        echo 'Email envoyé :' . htmlspecialchars($row['nom']) . '->' . htmlspecialchars($row['email']) . '<br>';
        mysqli_query(
            $db,
            "UPDATE `mailing` SET dat_sent = NOW() WHERE email = '" . mysqli_real_escape_string(
                $db,
                $row['email']
            ) . "'"
        );
    } catch (Exception $e) {
        echo 'Erreur (' . htmlspecialchars($row['email']) . ') ' . $mail->ErrorInfo . '<br>';
        $mail->getSMTPInstance()->reset();
    }
    $mail->clearAddresses();
    $mail->clearAttachments();
}
1

There are 1 answers

4
Synchro On

You're not calling addCustomHeader correctly; you're trying to set multiple headers at once, which it doesn't support, and the format of the header contents is not correct either. Do this instead:

        $mail->addCustomHeader(
            'List-Unsubscribe',
            "<mailto:[email protected]?subject=Unsubscribe%20:%20{$row['email']}>,<https://cineferte.fr/abo.php?unsub=" . $row['email'] . ">"
        );
        $mail->addCustomHeader(
            'List-Unsubscribe-Post',
            'List-Unsubscribe=One-Click'
        );

Apart from that it looks like you're doing things right for sending to a list.