Heim > Artikel > Backend-Entwicklung > PHPMailer实现邮件发送
很多时候,我们都需要发送邮件给我们的会员,比如注册激活、活动推送等等。
在PHP中实现邮件发送的方法有很多,比如比较新的Swift Mailer 、还有PHPMailer等。在这主要介绍一下PHPMailer这一个邮件发送类。
下载
PHPMailer的GitHub地址:https://github.com/PHPMailer/PHPMailer
实现
代码如下
<code><span></span>php <span>//引入类文件</span> require_once <span>'PHPMailerAutoload.php'</span>; <span>//实例化类</span><span>$mail</span><span>=</span><span>new</span> PHPMailer(); <span>//是否开始debug模式</span><span>$mail</span><span>-></span>SMTPDebug <span>=</span><span>1</span>; <span>//这里的数字表示提示错误的的类型</span><span>//使用STMP服务</span><span>$mail</span><span>-></span>isSMTP(); <span>//声明发送者邮箱SMTP服务器地址</span><span>$mail</span><span>-></span>Host <span>=</span><span>'smtp.163.com'</span>; <span>//这个是163邮箱SMTP服务器地址</span><span>//开启SMTP认证</span><span>$mail</span><span>-></span>SMTPAuth <span>=</span><span>true</span>; <span>//发送邮箱帐号</span><span>$mail</span><span>-></span>Username <span>=</span><span>'admin'</span>; <span>//发送邮箱密码</span><span>$mail</span><span>-></span>Password <span>=</span><span>'admin'</span>; <span>//注意这个密码可能不是平时登入时所用的密码,一般邮箱服务商为提供一个授权码,使用时填写这个授权码</span><span>//加密协议</span><span>$mail</span><span>-></span>STMPSecure <span>=</span><span>'SSL'</span>; <span>//端口号</span><span>$mail</span><span>-></span>Port <span>=</span><span>25</span>; <span>//发送者邮箱和昵称</span><span>$mail</span><span>-></span>setFrom(<span>'from@163.com'</span>,<span>'Admin'</span>); <span>//接受者邮箱和昵称</span><span>$mail</span><span>-></span>addAddress(<span>'to@163.com'</span>,<span>'Customer'</span>); <span>//是否开启HTML格式</span><span>$mail</span><span>-></span>isHTML(<span>true</span>); <span>//设置邮件的字符编码,不然中文乱码</span><span>$mail</span><span>-></span>CharSet<span>=</span><span>'UTF-8'</span>; <span>//邮件主题</span><span>$mail</span><span>-></span>Subject <span>=</span><span>'subject'</span>; <span>//邮件内容</span><span>$mail</span><span>-></span>Body <span>=</span><span>'body'</span>; <span>//邮件替代内容</span><span>$mail</span><span>-></span>AltBody <span>=</span><span>'altbody'</span>; <span>//当邮件不支持html时备用显示,可以省略 </span><span>//邮件附件</span><span>$mail</span><span>-></span>addAttachment(<span>'load.zip'</span>); <span>if</span>(<span>!</span><span>$mail</span><span>-></span>send()){ echo <span>'Message could not be sent'</span>; echo <span>'Mail Error:'</span><span>.</span><span>$mail</span><span>-></span>ErrorInfo; }<span>else</span>{ echo <span>'Message has been sent'</span>; } </code>
博主亲测有效,大家可以看着代码一步一步进行学习
这里我指出几个问题
PHPMailerAutoload.php
这个文件即可。以上就介绍了 PHPMailer实现邮件发送,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。