我需要在用户做特定事情时发送电子邮件,例如填写表单,提交请求等。这些都发生在不同的页面上。
我知道PHPMailer的默认用法如下:
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->setFrom('from@example.com', 'Your Name');
$mail->addAddress('myfriend@example.net', 'My Friend');
$mail->Subject = 'First PHPMailer Message';
$mail->Body = 'Hi! This is my first e-mail sent through PHPMailer.';
if(!$mail->send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
是否可以使用mail()类,而不必每次都重新指定邮件功能的用户名,密码和消息?
基本上你可以有这样的功能:
sendMail($from, $to, $subject, $body);
然后传递给PHPMailer实例的变量?
与this question类似。
答案 0 :(得分:2)
require 'vendor/autoload.php';
class MyMail extends PHPMailer
{
private $_host = 'your stmp server name';
private $_user = 'your smtp username';
private $_password = 'your password';
public function __construct($exceptions=true)
{
$this->Host = $this->_host;
$this->Username = $this->_user;
$this->Password = $this->_password;
$this->Port = 465;
$this->SMTPAuth = true;
$this->SMTPSecure = 'ssl';
$this->isSMTP();
parent::__construct($exceptions);
}
public function sendMail($from, $to, $subject, $body)
{
$this->setFrom($from);
$this->addAddress($to);
$this->Subject = $subject;
$this->Body = $body;
return $this->send();
}
}
$m = new MyMail();
$result = $m->sendMail('test@test.hu', 'youremail@yourdomain.com', 'Test from script', 'test message from script');