123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- <?php
- /**
- * Created by PhpStorm.
- * User: Leo.xie
- * Date: 2017/7/28
- * Time: 9:47
- * Description:邮件发送服务
- */
- namespace app\common\service;
- use think\Log;
- use PHPMailer\PHPMailer\PHPMailer;
- class MailService {
- private $account = [
- // ['account'=>'811329263@qq.com','key'=>'jwxrmfukwalobbhi'],
- ['account' => '2990412861@qq.com', 'key' => 'tayeekdedupfdfgc'], //IMAP/SMTP服务
- ];
- /**
- * @param string $sendName 给自己作为发送者设置的姓名
- * @param string $subject 邮件的标题【主题】名称
- * @param string $content 邮件的内容是什么
- * @param string $replyMail 要求邮件回复给谁
- * @param array $toMail 发送邮件给谁的列表 [0=>['mail'=>'xx@qq.com','name'=>'xx']]
- * @param string $fromMail
- * @return bool
- */
- public function send(string $sendName,
- string $subject,
- string $content,
- string $replyMail,
- $toMail = [],
- $fromMail = ''): bool {
- if (!$sendName || !$subject || !$content || !$toMail) {
- HelperService::$_httpErr = 'Mail params is error';
- return false;
- }
- date_default_timezone_set('Asia/Shanghai');
- // 随机邮箱账户
- $randomAccount = $this->account[random_int(0, count($this->account) - 1)];
- $mail = new PHPMailer(); //得到一个PHPMailer实例
- $mail->CharSet = "utf-8"; //设置采用utf-8中文编码(内容不会乱码)
- $mail->isSMTP(); //设置采用SMTP方式发送邮件
- $mail->Host = "smtp.qq.com"; //设置邮件服务器的地址(若为163邮箱,则是smtp.163.com)
- // $mail->Host = "ssl://smtp.qq.com"; //设置邮件服务器的地址(若为163邮箱,则是smtp.163.com)
- $mail->Port = 465; //设置邮件服务器的端口,默认为25
- $mail->From = empty($fromMail) ? $randomAccount['account'] : $fromMail; //设置发件人的邮箱地址
- $mail->FromName = $sendName; //设置发件人的姓名(可随意)
- $mail->SMTPAuth = true; //设置SMTP是否需要密码验证,true表示需要
- $mail->SMTPSecure = 'ssl';
- $mail->Username = $randomAccount['account']; //(后面有解释说明为何设置为发件人)
- $mail->Password = $randomAccount['key']; // 密码
- $mail->Subject = $subject; //主题
- $mail->AltBody = "text/html"; // optional, comment out and test
- $mail->Body = $content; //内容
- $mail->isHTML(true);
- $mail->WordWrap = 50; //设置每行的字符数
- if (empty($replyMail)) {
- $replyMail = $randomAccount['account'];
- }
- $mail->addReplyTo((string)($replyMail), "from"); //设置回复的收件人的地址(from可随意)
- foreach ($toMail as $mailItem) {
- if (!$mailItem['mail'] || !$mailItem['name']) {
- continue;
- }
- $mail->addAddress($mailItem['mail'], $mailItem['name']); //设置收件的地址(to可随意)
- }
- try {
- return $mail->send();
- } catch (\Exception $ex) {
- Log::record('邮件发送失败:' . $ex->getMessage());
- HelperService::$_httpErr = $ex->getMessage();
- return false;
- }
- }
- }
|