文章目录
1. phpmailer/phpmailer
Composer 仓库搜索 email
找到的扩展
这么优雅的代码
2. 名词解释
setFrom
设置邮件 发件人
addAddress
添加邮件 接件人
addCC 和 addBCC
CC代表抄送,英文全称是 Carbon Copy
BCC代表暗抄送,英文全称是 Blind Carbon Copy。
暗抄送和抄送的唯一区别就是,
暗抄送能够让各个收件人只查看到邮件,而不能看到其他收件人的地址。
addReplyTo
回件(回复邮件)的接收人, 如果未设置 replay, 那么回件的接件人为发件人
应用场景: 公司发送邮件, 通知所有人发送个人资料给人事 (邮件由公司统一发送的, 而邮件回件接收人确实人事)
addAttachment
添加附件
Subject
设置邮件主题
3. Example
//创建项目目录
mkdir example-phpmailer
cd example-phpmailer
// 安装 phpmailer
composer require phpmailer/phpmailer
// 创建 测试文件
touch index.php
index.php
内容如下, 以 QQ 邮箱为例, 密码需要修改为个人配置
<?php
//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
//Load Composer's autoloader
require 'vendor/autoload.php';
//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'smtp.qq.com'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'Your Email Adress'; // SMTP username
$mail->Password = 'Your Email Password'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // Enable implicit TLS encryption
$mail->Port = 465; // TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
//Recipients
$mail->setFrom('527147280@qq.com', '527147280');
// $mail->addAddress('178912797@qq.com', '178912797'); //Add a recipient
$mail->addAddress('1967599562@qq.com'); //Name is optional
// $mail->addReplyTo('178912797@qq.com', 'Information');
// $mail->addCC('cc@example.com');
$mail->addBCC('178912797@qq.com');
//Attachments
// $mail->addAttachment('/var/tmp/file.tar.gz'); //Add attachments
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); //Optional name
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
参考文章