【发布时间】:2019-08-25 04:16:40
【问题描述】:
我正在使用 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 消息。我在这里写错代码了吗?
【问题讨论】:
-
你的函数
newMail()不返回'true'或'false',它什么也不返回。 -
这段代码在把它放在一个单独的函数中之前工作了吗?
-
是的,它在单独的函数之外起作用
-
第一个问题是,正如@KIKOSoftware 所说,
newMail()函数什么也不返回。第二个问题是,您在newMail()函数之外包含了 PHPMailer 库。 -
@SuperGENScript 哦,对不起。执行
newMail()函数时,您没有将$set变量作为参数发送。