我正在使用PHPMailer发送电子邮件。但我必须编写在每个页面上发送电子邮件的冗长代码。因此,我想尝试将所有内容放入一个函数中,并在我想使其变得干燥,简单和容易时随时调用它。但是在尝试发送电子邮件时它不起作用。我尝试了以下方法:
functions.php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';
$settings = $pdo->prepare("SELECT * FROM settings");
$settings-> execute();
$set = $settings->fetch();
function newMail($name, $email, $sub, $msg, $set) {
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Host = $set['set_smtp_host'];
$mail->Port = $set['set_smtp_port'];
$mail->SMTPSecure = $set['set_smtp_security'];
$mail->IsHTML(true);
$mail->SMTPAuth = true;
$mail->Username = $set['set_smtp_uname'];
$mail->Password = $set['set_smtp_pass'];
$mail->setFrom($set['set_noreply_email'], $set['set_site_name']);
$mail->addAddress($email, $name);
$mail->Subject = $sub;
$mail->Body = $msg;
$mail->Send();
}
现在,我尝试通过这种方式在另一页(其中包含functions.php)上调用该函数:
$fname = (!empty($_POST['fname']))?$_POST['fname']:null;
$email = (!empty($_POST['email']))?$_POST['email']:null;
$sub = ''.$title.' - Account Verification Link';
$msg = 'SOME BODY MESSAGE';
if(newMail($fname, $email, $sub, $msg)){
echo alert_success("Registration successful! Please check your email and click on the activation link to activate your account. If you did not receive any email within 5 minutes then <a href='resend.php'>click here</a> to resend it.");
}else{
echo alert_success("Registration successful! But unfortunately, we could not send you a verification email. Please <a href='resend.php'>click here</a> to resend it.");
}
这里总是返回else消息。我在这里编码错误吗?
答案 0 :(得分:3)
修改功能 newMail :
return $mail->Send();
如果已发送邮件,则send方法返回true,因此您的函数应该返回该值,否则返回:
if(newMail(...)){ }
对于为什么要应用else情况,永远都是错误的。
function newMail($name, $email, $sub, $msg, $set) {
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Host = $set['set_smtp_host'];
$mail->Port = $set['set_smtp_port'];
$mail->SMTPSecure = $set['set_smtp_security'];
$mail->IsHTML(true);
$mail->SMTPAuth = true;
$mail->Username = $set['set_smtp_uname'];
$mail->Password = $set['set_smtp_pass'];
$mail->setFrom($set['set_noreply_email'], $set['set_site_name']);
$mail->addAddress($email, $name);
$mail->Subject = $sub;
$mail->Body = $msg;
return $mail->Send(); // add return here
}