t-r.de/content/php/subscribe.php

73 lines
2.5 KiB
PHP

<?php
// inspired by https://www.mailgun.com/blog/email/double-opt-in-with-php-mailgun/
// import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
$dname = dirname(__FILE__);
require $dname . '/Exception.php';
require $dname . '/PHPMailer.php';
require $dname . '/SMTP.php';
function MakeConfirmationHash($confEmail, $confCode) {
return md5($confEmail . $confCode);
}
function SendConfirmationEmail($recipientAddress) {
global $general, $smtp, $mail;
$hashedUnique = MakeConfirmationHash($recipientAddress, $general["uniqueKey"]);
$confirmQuery = http_build_query(["c" => $hashedUnique, "e" => $recipientAddress]);
$confirmURL = $general["siteURL"] . $general["confirmScript"] . "?" . $confirmQuery;
// create PHPMailer instance
$mailer = new PHPMailer(true);
try {
//Server settings
// $mailer->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output
$mailer->isSMTP();
$mailer->Host = $smtp["host"];
$mailer->SMTPAuth = $smtp["auth"];
$mailer->Username = $smtp["username"];
$mailer->Password = $smtp["password"];
//$mailer->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption
$mailer->Port = $smtp["port"]; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
//Recipients
$mailer->setFrom($smtp["fromAddress"], $smtp["fromName"]);
$mailer->addAddress($recipientAddress); //Add a recipient
//Content
$mailer->CharSet = "UTF-8";
$mailer->isHTML(true);
$mailer->Subject = $mail["subject"];
$mailer->Body = str_replace("%confirmURL%", $confirmURL, $mail["bodyHTML"]);
$mailer->AltBody = str_replace("%confirmURL%", $confirmURL, $mail["bodyText"]);
$mailer->send();
return TRUE;
} catch (Exception $e) {
error_log("Message error: " . $e);
return FALSE;
}
}
require($dname . "/settings.php");
if (isset($_POST['email'])) {
$email = SanitizeEmail(trim($_POST['email']));
// error_log("Received subscription request for address " . $email . " ..."); //DEBUG
$result = SendConfirmationEmail($email);
if ( $result == TRUE ) {
header('Location: /newsletter/subscribed.html');
error_log("Message to " . $email . " has been sent.");
} else {
header('Location: /newsletter/subscribe-error.html');
error_log("Message to " . $email . " could not be sent.");
}
}
?>