Search code examples
phphtmlsmtphtml-emailphpmailer

PHPMailer a href link in HTML mail isn't working correct


I got this code:

$userid = 123456;
    $plaintext  = "
    Klicke auf den folgenden Link um deine Anmeldung bei xxx zu bestätigen:
    http://xxx.de/confirm.php?id=" . $userid;

    $html = '
    Klicke auf den folgenden Link um deine Anmeldung bei xxx zu bestätigen:
    <br><br>
    <a href="http://xxx.de/confirm.php?id=' . $userid . '">Anmeldung abschliessen</a>';


    $mail = new PHPMailer;
    $mail->CharSet = 'utf-8';
    $mail->setLanguage('de', 'language/');
    $mail->isSMTP();
    $mail->Host = "xxx";
    $mail->Port = 587;
    $mail->SMTPAuth = true;
    $mail->Username = 'xxx';
    $mail->Password = 'xxx';
    $mail->SMTPSecure = 'tls';
    $mail->From = '[email protected]';
    $mail->FromName = 'xxx';
    $mail->addAddress($email, $email);
    $mail->addReplyTo('[email protected]', 'xxx');
    $mail->isHTML(true);
    $mail->Subject = $nickname . ' - Bestätige deine Anmeldung';
    $mail->Body    = $html;
    $mail->AltBody = $plaintext;
    $mail->send();

The link works correct in the plain text mail but not in the HTML version, the link becomes something like: xxx.de/?id=fdfafdafadfadfargagga So the ints are becoming endless letters and the confirm.php part disappears. What could be the problem here?


Solution

  • This is indeed your email processors fault. The tidiest way to fix this is to set up a rewrite on your web server. If you're using apache, you could do this in your apache config file or a .htacccess file:

    RewriteRule ^/confirm/([0-9]+) /confirm.php?id=$1 [L]
    

    This will rewrite URLs like http://xxx.de/confirm/1234 (which should be left alone by the email handler) to http://xxx.de/confirm.php?id=1234, which is what your script is expecting. In your template you'd rearrange it to look like the first form:

    $html = 'Klicke auf den folgenden Link um deine Anmeldung bei xxx zu bestätigen:<br><br>
    <a href="http://xxx.de/confirm/' . $userid . '">Anmeldung abschliessen</a>';
    

    and it looks like you have a little encoding problem to deal with too...