此文是对慕课网中这一课程的笔记。
一 首先是使用 telnet 命令发送邮件,此处用的邮箱为阿里邮箱和新浪邮箱。
C:\Users\Administrator>telnet smtp.aliyun.com 25
220 smtp.aliyun.com MX AliMail Server(127.0.0.1)
helo hi //测试是否连接成功
250 Ok
auth login //开始身份认证
334 dXNlcm5hbWU6 //334说明成功
"邮箱地址的base64编码" UGFzc3dvcmQ6
"邮箱密码的base64编码: Authentication successful //提示 successful 说明登录成功
mail from: <username@aliyun.com> //发件人邮件
250 Mail Ok
rcpt to:<username@sina.cn> //收件人邮箱
250 Rcpt Ok
data //开始写邮件正文
354 End data with <CR><LF>.<CR><LF> // 354说明成功
from: aliyun //邮件中显示发件人
to: sina //邮件中显示的收件人
subject: this is a demo show //邮件中显示的主题,之后按两个回车
this is a email content //输入文章的内容,之后按回国
. //再输入.,回车
250 Data Ok: queued as freedom //提示250,说明邮件已发送成功
二 使用第三方库发送邮件
下载地址:https://github.com/PHPMailer/PHPMailer/
以下为作者写的一个简单的例子:
<?php
$rootPath = dirname(__FILE__);
require '..\PHPMailer-master\PHPMailerAutoload.php'; //引用包
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.aliyun.com'; // smtp 服务器地址
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->CharSet = "UTF-8"; //邮件内容编码
$mail->Username = 'username@aliyun.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
// $mail->SMTPSecure = 'tls'; // 加密方式
// $mail->Port = 587; // TCP port to connect to
$mail->setFrom('username@aliyun.com', 'aliyun');
$mail->addAddress('username@sina.cn', 'sina'); // Add a recipient
$mail->addReplyTo('usesrname@aliyun.com', 'Information'); //收件人回复的邮件地址
$mail->addCC('cc@example.com'); //抄送,需要时设置
$mail->addBCC('bcc@example.com'); //密送,需要时设置
// $mail->addAttachment('/var/tmp/file.tar.gz'); // 发送附件
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true); // 邮件正文使用html格式
$mail->Subject = 'Here is the subject with file';
$mail->Body = 'This is the HTML message body <b>in bold!</b>'; //正文信息(html文档格式)
// $mail->msgHTML(file_get_contents("file.html")); //从 html 文档中读取内容并发送(以 html 文档格式)
// $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; // 未带html的内容
// 如果邮件发送失败,输出错误信息
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}