这两天琢磨了php得原生发送邮件,发现自带得mail方法不太好用,于是上网查询了好多方法,亲测以下方法能用
源代码都在 我的github
到github上下载
https://github.com/PHPMailer/PHPMailer
里面有很多文件,但是目前主要就用到两个文件
class.phpmailer.php class.smtp.php
我这个使用得是qq得smtp,如果需要其他得可以自行更改
qq的smtp服务器是:smtp.qq.com 端口号为465 或587
163smtp服务器是:smtp.163.com 端口25
下面是我进行了简单的封装
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2017/6/19
* Time: 9:12
*/
class SenMail
{
private $fromMailName='';
private $formMailPassword='';
private $mail='';
//密码是授权码
function __construct($fromMailName = 'xxxxxx@qq.com', $fromMailPassword = 'xxxxxxx')
{
require_once('class.phpmailer.php');
require_once('class.smtp.php');
$this->fromMailName=$fromMailName;
$this->formMailPassword=$fromMailPassword;
$this->mail = new PHPMailer();
}
/**
* @param string $arrayMail array集合
* @param $senName 发件人
* @param $title 标题
* @param $body 内容
*/
function sendMail($arrayMail,$senName, $title, $body)
{
//invoke mail() function to send mail
// mail($toaddress, $subject, $mailcontent, $fromaddress);
date_default_timezone_set('Asia/Shanghai');//设定时区东八区
$fromMailPassword=$this->formMailPassword;
$fromMailName=$this->fromMailName;
$mail = $this->mail;
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.qq.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$email = explode("@", $fromMailName);
$mail->Username = $email[0]; // SMTP username
$mail->Password = $fromMailPassword; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;
$mail->CharSet = 'utf-8';
// echo $mail->Host; // TCP port to connect to
$mail->setFrom($this->fromMailName, $senName);
// $mail->addAddress('714080794@qq.com', 'Joe User'); // Add a recipient
foreach($arrayMail as $v) {
$mail->addAddress($v); // Name is optional
}
// $mail->addReplyTo('714034323@qq.com', 'Information');
// $mail->addCC('714034323@qq.com');
// $mail->addBCC('714034323@qq.com');
// $mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(false); // Set email format to HTML
$mail->Subject = $title;
$mail->Body = $body;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if (!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo ucwords('Message has been sent');
}
}
}
index.php文件调用
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2017/6/16
* Time: 15:15
*/
require "SenMail.php";
$e = new SenMail();
$toEmail = array('xxxx@163.com','xxxxx@qq.com');
$e->sendMail($toEmail,'xx程','测试2号','我是内容');
给新手的
开启qq邮箱的smtp
密码是授权码,不是qq登录密码
遇到的问题
抛异常:Extesion missing: openssl
这个直接打开php.ini 查找 extension=php_openssl.dll 把注释去掉即可