安装
代码语言:javascript复制composer require phpmailer/phpmailer
demo
代码语言:javascript复制<?php
require 'vendor/autoload.php';
use PHPMailerPHPMailerPHPMailer;
//test
sendmail('111@qq.com', 'test', 'ccc');
/**
* 邮件发送函数
* @param string $to 接收邮件者邮箱
* @param string $subject 邮件主题
* @param string $body 邮件内容
* @param string $attachment 附件列表
* @return boolean
*/
function sendmail($to, $subject = '', $body = '', $attachment = null){
//邮件配置
$config = [
'SMTP_HOST' => 'smtp.mxhichina.com',
'SMTP_PORT' => '25',
'SMTP_USER' => 'notifications-noreply@xx.com',
'SMTP_PASS' => '123456',
'FROM_EMAIL' => 'notifications-noreply@xx.com',
'FROM_NAME' => 'notifications-noreply',
'REPLY_EMAIL' => '',
'REPLY_NAME' => ''
];
$mail = new PHPMailer;
$mail->CharSet = 'UTF-8';
$mail->IsSMTP();
// 1 = errors and messages
// 2 = messages only
$mail->SMTPDebug = 0; // 关闭SMTP调试功能
$mail->SMTPAuth = true; // 启用 SMTP 验证功能
// $mail->SMTPSecure = 'ssl'; // 使用安全协议
$mail->Host = $config['SMTP_HOST'];
$mail->Port = $config['SMTP_PORT'];
$mail->Username = $config['SMTP_USER'];
$mail->Password = $config['SMTP_PASS'];
$mail->SetFrom($config['FROM_EMAIL'], $config['FROM_NAME']);
$replyEmail = $config['REPLY_EMAIL']?$config['REPLY_EMAIL']:$config['FROM_EMAIL'];
$replyName = $config['REPLY_NAME']?$config['REPLY_NAME']:$config['FROM_NAME'];
$mail->AddReplyTo($replyEmail, $replyName);
$mail->Subject = $subject;
$mail->MsgHTML($body);
$mail->AddAddress($to, '');
// 添加附件
if(is_array($attachment)){
foreach ($attachment as $file){
is_file($file) && $mail->AddAttachment($file);
}
}
return $mail->Send() ? true : $mail->ErrorInfo;
}