PHPMailer的使用 —— 发送邮件

编辑于 2021-05-17 15:43:21 阅读 937

安装

composer require phpmailer/phpmailer

demo

<?php
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;

//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;
}

广而告之,我的新作品《语音助手》上架Google Play了,欢迎下载体验