我之前没有使用MVC发送过电子邮件,而且有点卡住了。
在我的app文件夹中,我有一个库文件夹,其中包含Controller.php,Core.php,Database.php和我创建的Email.php
在Email.php中我有一个班级:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require '../vendor/autoload.php';
class Email {
public function sendMail()
{
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'mail.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'mail@example.com'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('mail@example.com');
$mail->addAddress('someone@example.com'); // Add a recipient // Name is optional
$mail->addReplyTo('mail@example.com');
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
}
}
我正在尝试在访问电子邮件视图时触发发送电子邮件。但是,我不知道在控制器中放什么。下面的代码给了我一个错误。
public function email()
{
$this->sendMail();
$this->view('pages/email');
}
致命错误:未捕获错误:调用未定义的方法Pages :: sendMail()
答案 0 :(得分:3)
您必须创建一个类Email:
的实例$email = new Email();
$email->sendMail();