点击查看代码
<?php
class MailSender {
// 发件人邮箱地址
private $fromEmail;
// 发件人名称
private $fromName;
// 收件人邮箱地址
private $toEmail;
// 邮件主题
private $subject;
// 邮件内容
private $body;
// 构造函数,接收发件人邮箱和名称进行初始化
public function __construct($fromEmail, $fromName) {
$this->fromEmail = $fromEmail;
$this->fromName = $fromName;
}
// 设置收件人邮箱地址的方法
public function setToEmail($toEmail) {
$this->toEmail = $toEmail;
}
// 设置邮件主题的方法
public function setSubject($subject) {
$this->subject = $subject;
}
// 设置邮件内容的方法
public function setBody($body) {
$this->body = $body;
}
// 发送邮件的方法
public function sendMail() {
// 设置邮件头,包含发件人信息、MIME 版本和内容类型
$headers = "From: {$this->fromName} <{$this->fromEmail}>\r\n";
$headers.= "MIME-Version: 1.0\r\n";
$headers.= "Content-Type: text/html; charset=UTF-8\r\n";
// 使用 PHP 的 mail 函数发送邮件,返回发送结果
return mail($this->toEmail, $this->subject, $this->body, $headers);
}
}
?>
使用
点击查看代码
// 使用示例
$mailer = new MailSender('[email protected]', 'Your Name');
$mailer->setToEmail('[email protected]');
$mailer->setSubject('Test Email');
$mailer->setBody('<h1>Hello!</h1>This is a test email.');
if ($mailer->sendMail()) {
echo "Email sent successfully.";
} else {
echo "Failed to send email.";
}