MailService.php 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Leo.xie
  5. * Date: 2017/7/28
  6. * Time: 9:47
  7. * Description:邮件发送服务
  8. */
  9. namespace app\common\service;
  10. use think\Log;
  11. class MailService{
  12. private $account = [
  13. ['account'=>'811329263@qq.com','key'=>'jwxrmfukwalobbhi'],
  14. ];
  15. /**
  16. * @param string $sendName 给自己作为发送者设置的姓名
  17. * @param string $themeName 邮件的标题【主题】名称
  18. * @param string $content 邮件的内容是什么
  19. * @param array $replyMail 要求邮件回复给谁
  20. * @param array $toMail 发送邮件给谁的列表[0=>['mail'=>'xx@qq.com','name'=>'xx']]
  21. * @return bool
  22. * @throws \Exception
  23. */
  24. public function send($sendName,$themeName,$content,$replyMail,$toMail=[]){
  25. if(!$sendName || !$themeName || !$content || !$toMail){
  26. HelperService::$_httpErr = "Mail params is error";
  27. return false;
  28. }
  29. vendor('phpmailer.class#phpmailer'); //下载phpmailer并include两个文件
  30. vendor('smtp.class#phpmailer');
  31. date_default_timezone_set('Asia/Shanghai');
  32. $random = rand(0,count($this->account)-1);
  33. $mail = new \PHPMailer(); //得到一个PHPMailer实例
  34. $mail->CharSet = "utf-8"; //设置采用utf-8中文编码(内容不会乱码)
  35. $mail->IsSMTP(); //设置采用SMTP方式发送邮件
  36. $mail->Host = "ssl://smtp.qq.com"; //设置邮件服务器的地址(若为163邮箱,则是smtp.163.com)
  37. $mail->Port = 465; //设置邮件服务器的端口,默认为25
  38. $mail->From = $this->account[$random]['account']; //设置发件人的邮箱地址
  39. $mail->FromName = "{$sendName}"; //设置发件人的姓名(可随意)
  40. $mail->SMTPAuth = true; //设置SMTP是否需要密码验证,true表示需要
  41. $mail->Username= $this->account[$random]['account']; //(后面有解释说明为何设置为发件人)
  42. $mail->Password = $this->account[$random]['key'];
  43. $mail->Subject = "{$themeName}"; //主题
  44. $mail->AltBody = "text/html"; // optional, comment out and test
  45. $mail->Body = "{$content}"; //内容
  46. $mail->IsHTML(true);
  47. $mail->WordWrap = 50; //设置每行的字符数
  48. if(empty($replyMail)){
  49. $replyMail = '811329263@qq.com';
  50. }
  51. $mail->AddReplyTo("{$replyMail}","from"); //设置回复的收件人的地址(from可随意)
  52. foreach($toMail as $mail_item){
  53. if(!$mail_item['mail'] || !$mail_item['name']){
  54. continue;
  55. }
  56. $mail->AddAddress($mail_item['mail'],$mail_item['name']); //设置收件的地址(to可随意)
  57. }
  58. try {
  59. return $mail->Send();
  60. }catch(\Exception $ex){
  61. Log::record('邮件发送失败:'.$ex->getMessage());
  62. HelperService::$_httpErr = $ex->getMessage();
  63. return false;
  64. }
  65. }
  66. }