php下使用phpmailer发送邮件

由于默认虚拟空间不支持mail()函数,客户需要留言发送邮件,找到phpmailer发送不成功,调试成功后记录一下。

最新的下载地址在github,https://github.com/Synchro/PHPMailer

使用很简单,但我遇到三个问题。

1、Gmail开通了两步验证的同学,需要生成一个app专业密码,使用它,开启SSL,端口号是465

2、QQ邮箱需要申请密保后才能开启SMTP等服务,所以在qq邮箱后台没有开启服务的当然是发不出邮件的

下面是以GMAIL测试的发送代码

 1 <?php
 2 require 'PHPMailerAutoload.php';
 3 
 4 $mail = new PHPMailer;
 5 
 6 $mail->SMTPDebug = 3;                               // Enable verbose debug output
 7 
 8 $mail->isSMTP();                                      // Set mailer to use SMTP
 9 $mail->Host = 'smtp.gmail.com;';  // Specify main and backup SMTP servers
10 $mail->SMTPAuth = true;                               // Enable SMTP authentication
11 $mail->Username = 'luwenjie110@gmail.com';                 // SMTP username
12 $mail->Password = '********';                           // SMTP password
13 $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
14 $mail->Port = 465;                                    // TCP port to connect to
15 
16 $mail->setFrom('luwenjie110@gmail.com', 'Mailer');
17 $mail->addAddress('269811553@qq.com', 'Joe User');     // Add a recipient
18 //$mail->addAddress('ellen@example.com');               // Name is optional
19 //$mail->addReplyTo('info@example.com', 'Information');
20 //$mail->addCC('cc@example.com');
21 //$mail->addBCC('bcc@example.com');
22 
23 //$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
24 //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
25 $mail->isHTML(true);                                  // Set email format to HTML
26 
27 $mail->Subject = 'Here is the subject';
28 $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
29 $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
30 
31 if(!$mail->send()) {
32     echo 'Message could not be sent.';
33     echo 'Mailer Error: ' . $mail->ErrorInfo;
34 } else {
35     echo 'Message has been sent';
36 }

 3、本地调试ok,上传到虚拟空间后出错:Parse error: syntax error, unexpected T_FUNCTION class.phpmailer.php on line 3040

    google 后知道问题出在php版本上:https://github.com/PHPMailer/PHPMailer/issues/535

    将西数空间php调成5.5没报错但还是无法发送邮件,继续调成5.3则正常了。但多次测试后还是大多数时间发送超时,折腾了很久以为是跟页面js有冲突,没加载完等原因。

    其实最后还是想到了是gmail不稳定的原因,在国内就是这样,最后改用qq邮箱,效果非常好。

    完结!

posted @ 2016-01-21 14:36  luwenjie  阅读(447)  评论(0编辑  收藏  举报