这个例子分享了ThinkPHP5封装邮件发送服务的具体代码,供大家参考。具体内容如下
1.Composer安装phpmailer
Composer需要phpmailer/phpmailer2.thinkphp封装了邮件服务类
我将其封装在扩展目录extend/Mail.php文件中,内容如下:
?Php/***邮件服务类*/class mail extensions phpmailer { function _ _ construct(){ date _ default _ time zone _ set(' PRC ');//默认时区设置$ this-charset=config(' mail . charset ');//邮件编码设置$ this-isSMTP();//启用SMTP服务$ this-SMTP debug=config ('mail。SMTP _ debug’);//调试模式级别$ this-调试输出=config ('mail。debug _ output’);//调试输出类型$ this-Host=config(' mail . Host ');//SMTP服务器地址$ this-Port=config(' mail . Port ');//端口号$ this-SMTP auth=config ('mail。SMTP _ auth’);//SMTP登录身份验证$ this-SMTP secure=config ('mail。SMTP _ secure’);//SMTP安全协议$ this-username=config(' mail . username ');//SMTP登录邮箱$ this-password=config(' mail . password ');//SMTP登录密码$ this-set from(config(' mail . from '),config(' mail . from _ name ');//发件人的邮箱和姓名$ this-添加回复到(config ('mail.reply _ to ')、config(' mail . reply _ to _ name ');//回复邮箱和姓名}/* * *发送邮件* @param [type] $toMail收件人地址* @param [type] $toName收件人姓名* @ param[type]$主题邮件主题* @ param[type]$内容邮件内容,支持html * @ param[type]$附件列表。文件路径或路径数组* @return [type]成功返回true,失败返回错误消息*/函数sendmail ($ tomail,$ toname,$ subject,$ content,$ attachment=null){ $ this-addaddaddaddress($ to mail,$ toname);$ this-Subject=$ Subject;$ this-MSghtml($ content);If($attachment) {//添加附件if(is _ string($ attachment)){ is _ file($ attachment)$ this-添加附件($ attachment);} else if(is _ array($ attachment)){ foreach($ attachment as $ file){ is _ file($ file)$ this-AddAttachment($ file);} } } if(!$this-send()){ //send返回$ this-error info;} else { return true}}}注意:如果发送附件,建议使用英文路径。中文路径可能导致附件发送失败,收到的邮件没有附件。
我把上面需要的一些配置参数放在扩展配置目录application/extra/mail.php文件中,内容如下:
?Php/** *邮件服务相关配置*/返回['charset'='utf-8 ',//邮件编码' smtp_debug'=0,//Debug模式。0:关闭,1:客户端消息,2:客户端和服务器消息,3: 2和连接状态,4:debug _ output '=' html ',//Debug输出类型。“echo ”(默认)、“html”或“error _ log”“host ”=“SMTP . 126.com”,//SMTP服务器地址“port ”=465,//端口号。25' SMTP _ auth'=true默认情况下,//启用SMTP身份验证' smtp_secure'='ssl ',//启用安全协议。(默认)、“ssl”或“tls”,留空则不启用“用户名”=“[电子邮件保护]”、//SMTP登录邮箱“密码”=“您的密码”、//SMTP登录密码。126邮件使用客户端授权码,QQ邮件使用独立密码' from'='[emailprotected]',//发件人邮件' from_name'='name ',//发件人姓名' reply_to'=',//回复邮件地址。请留下发件人的邮箱“reply _ to _ name”=' ',//回复邮箱的人的姓名。将发件人姓名留空];注意:通常默认端口为25。如果使用安全协议ssl,端口号通常为465或587。例如,邮箱126。建议使用安全协议,因为阿里巴巴云服务器禁止非安全协议的25个端口。
更多配置参数,可以查看源代码:https://github.com/phpmailer/phpmailer/blob/master/class . phpmailer . PHP。
3.测试
在控制器的方法中,添加测试代码:
公共函数Mail(){ $ Mail=new Mail;$ ok=$ mail-sendmail('[email protected]',' mingc ',' mail来了',' p style=' color3360 # f60font-weight : 700;恭喜,邮件成功!/p ',' c :/用户/管理员/桌面/body . BMP ');var _ dump($ ok);}在这里,我使用126邮箱,安全协议ssl,端口号465,并发送html内容,并且测试成功:
参考链接:phpmail的SMTP邮件示例
以上就是本文的全部内容。希望对大家的学习有帮助,支持我们。