這兩天琢磨了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郵箱->設置->賬號
密碼是授權碼,不是qq登錄密碼
遇到的問題
拋異常:Extesion missing: openssl
這個直接打開php.ini 查找 extension=php_openssl.dll 把注釋去掉即可