【发布时间】:2017-07-15 13:45:04
【问题描述】:
我正在尝试创建一个 php 类来使用各种模板发送邮件。例如,我想发送带有用户名和密码的欢迎邮件。我正在尝试创建一个名为 sendwelcomemail() 的电子邮件函数,它正在从 getmailautho() 类访问默认的 php 邮件配置。
代码如下:
<?php
// Include the PHPMailer class
include('PHPMailer/class.phpmailer.php');
require_once 'PHPMailer/PHPMailerAutoload.php';
class email {
public function getmailauth(){
// Setup PHPMailer
$mail = new PHPMailer();
$mail->IsSMTP();
// This is the SMTP mail server
$mail->Host = 'smtp.gmail.com';
// Remove these next 3 lines if you dont need SMTP authentication
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = 'test@gmail.com';
$mail->Password = 'testing';
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
// Set who the email is coming from
$mail->SetFrom('testing@gmail.com', 'test');
}
function sendwelcomemail($username,$password,$to){
$this->getmailauth();
global $mail;
// Retrieve the email template required
$message = file_get_contents('templates/welcome.html');
// Replace the % with the actual information
$message = str_replace('%username%', $username, $message);
$message = str_replace('%password%', $password, $message);
// Set who the email is sending to
$mail->AddAddress($to);
// Set the subject
$mail->Subject = 'Your account information';
//Set the message
$mail->MsgHTML($message);
$mail->AltBody = strip_tags($message);
// Send the email
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
}
}
?>
<h3> testing </h3>
<?php
$email = new email;
$email->sendwelcomemail("test","test","test@test.com");
?>
当我运行这个脚本时,我收到以下错误:
致命错误:第 49 行 C:\xampp\htdocs\db\mail_function.php 中的 null 时调用成员函数 AddAddress()
你们能帮我解决这个错误吗?也欢迎任何建议:)
【问题讨论】:
-
创建构造函数并在其中添加初始化邮件,然后使用 $this->mail 在其他函数中访问它,它将起作用。
标签: php class email templates smtp