php发送邮件封装类,使用nette/mail 封装一个发送邮件类 (通用)

使用nette/mail 封装一个发送邮件类 (通用)

使用到的包

composer require nette/mail

封装Mail体

/**

* Created by PhpStorm.

* User: 邓尘锋

* Date: 19-7-5

* Time: 上午11:57

* surest.cn

*/

namespace app\common\server;

use Nette\InvalidArgumentException;

use Nette\Mail\Message;

class Mail extends Message

{

public $config;

// [String] e-mail

protected $from;

// [Array] e-mail list

protected $to;

protected $title;

protected $body;

public function __construct($to)

{

$host = config('email.username');

$this->setFrom("{$host}", "D88科技")

->setHeader("name", $host);

if ( is_array($to) ) {

foreach ($to as $email) {

$this->addTo($email);

}

} else {

$this->addTo($to);

}

}

public function from($from=null)

{

if ( !$from ) {

throw new InvalidArgumentException("邮件发送地址不能为空!");

}

$this->setFrom($from);

return $this;

}

public static function to($to=null)

{

if ( !$to ) {

throw new InvalidArgumentException("邮件接收地址不能为空!");

}

return new Mail($to);

}

public function title($title=null)

{

if ( !$title ) {

throw new InvalidArgumentException("邮件标题不能为空!");

}

$this->setSubject($title);

return $this;

}

public function content($content=null)

{

if ( !$content ) {

throw new InvalidArgumentException("邮件内容不能为空!");

}

$this->setHTMLBody($content);

return $this;

}

}

封装Mailer发送类

/**

* Created by PhpStorm.

* User: chenf

* Date: 19-7-16

* Time: 下午3:35

*/

namespace app\common\server;

use Nette\Mail\Message;

use Nette\Mail\SmtpMailer;

/**

*

* 使用:

* $mail = Mail::to($emails)->title("错误预警")->content($html);

* Mailer::setMailer()->send($mail);

*

* Class Mailer

* @package app\common\server

*/

class Mailer

{

/**

* 实例化一个Mailer类

* @return SmtpMailer

*/

public static function setMailer()

{

# 这里的配置读取的是config配置

$mailer = new SmtpMailer([

'host' => config('email.host'),

'username' => config('email.username'),

'password' => config('email.password'),

'secure' => config('email.secure')

]);

return $mailer;

}

/**

* 发送

* @param Message $mail

*/

public function send(Message $mail)

{

$this->send($mail);

}

}

配置

'host' => 'smtp.exmail.qq.com', // 用的是qq的smtp服务器

'username' => 'username',

'password' => 'password',

'secure' => 'ssl' // ssl 是 445 端口, 如不设置, 默认端口是 22 , 可参见源码

使用

// $emails 是一个数组

// Mail Message 体

$mail = Mail::to($emails)->title("错误预警")->content($html);

// 发送

Mailer::setMailer()->send($mail);

告知

如果直接使用如上方法, 采用的是同步发送的机制, 如果需要采用异步队列进行发送邮件, 我提供如下解决思路

使用redis

数据+key 写入 hash

key 写入 list

创建一个定时任务, 去除list key, 再去除hash数据, 进行发送

了解一下 , 生产者消费者模式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值