关于python和php发送邮件
关于python和php发送邮件
背景
突然想做一个能在手机上提示事件发生的东西,考虑了几种方式:
- 写一个APP与服务器进行socket通信,每隔一定时间取信息,事件发生时提醒;
- 利用短信,诸如SMS,飞信等;
- 利用QQ,微信等通信工具提醒;
- 服务器发送邮件到指定邮箱,然后手机上利用邮箱管理软件提醒;
斟酌一下,1太麻烦,2太费钱,3需要获取QQ,微信API,呃...找了下资料,还是太麻烦,4勉强还行,那就4吧。
python实现
网上找了个现成的,测试还可以用,就直接搬上来:
# coding=utf-8
import smtplib
from email.mime.text import MIMEText
mailto_list = ['XXXX@163.com']
mail_host = "smtp.163.com"
mail_user = "XXXX@163.com"
mail_pass = "XXXX"
mail_postfix = "163.com"
def send_mail(to_list, sub, content):
me = "hello" + "<" + mail_user + "@" + mail_postfix + ">"
msg = MIMEText(content, _subtype='plain', _charset='utf-8')
msg['Subject'] = sub
msg['From'] = "XXXXX@163.com"
msg['To'] = ";".join(to_list)
try:
server = smtplib.SMTP()
server.connect(mail_host)
server.login(mail_user, mail_pass)
server.sendmail(me, to_list, msg.as_string())
server.close()
return True
except Exception, e:
print str(e)
return False
if __name__ == '__main__':
if send_mail(mailto_list, "提示邮件", "测试一下!"):
print "success"
else:
print "failed"
php实现
网上php版本有很多,但这个版本相对而言较为简洁,测试也可用。
<?php
$bfconfig = Array (
'sitename' => 'YTNotice',
);
$mail = Array (
'state' => 1,
'server' => 'smtp.163.com',
'port' => 25,
'auth' => 1,
'username' => 'xxxx@163.com',
'password' => 'xxx',
'charset' => 'utf-8',
'mailfrom' => xxxx@163.com'
);
function sendmail($mail_to, $mail_subject, $mail_message) {
global $mail, $bfconfig;
date_default_timezone_set('PRC');
$mail_subject = '=?'.$mail['charset'].'?B?'.base64_encode($mail_subject).'?=';
$mail_message = chunk_split(base64_encode(preg_replace("/(^|(\r\n))(\.)/", "\1.\3", $mail_message)));
$headers = "";
$headers .= "MIME-Version:1.0\r\n";
$headers .= "Content-type:text/html\r\n";
$headers .= "Content-Transfer-Encoding: base64\r\n";
$headers .= "From: ".$bfconfig['sitename']."<".$mail['mailfrom'].">\r\n";
$headers .= "Date: ".date("r")."\r\n";
list($msec, $sec) = explode(" ", microtime());
$headers .= "Message-ID: <".date("YmdHis", $sec).".".($msec * 1000000).".".$mail['mailfrom'].">\r\n";
if(!$fp = fsockopen($mail['server'], $mail['port'], $errno, $errstr, 30)) {
exit("CONNECT - Unable to connect to the SMTP server");
}
stream_set_blocking($fp, true);
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != '220') {
exit("CONNECT - ".$lastmessage);
}
fputs($fp, ($mail['auth'] ? 'EHLO' : 'HELO')." befen\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 220 && substr($lastmessage, 0, 3) != 250) {
exit("HELO/EHLO - ".$lastmessage);
}
while(1) {
if(substr($lastmessage, 3, 1) != '-' || empty($lastmessage)) {
break;
}
$lastmessage = fgets($fp, 512);
}
if($mail['auth']) {
fputs($fp, "AUTH LOGIN\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 334) {
exit($lastmessage);
}
fputs($fp, base64_encode($mail['username'])."\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 334) {
exit("AUTH LOGIN - ".$lastmessage);
}
fputs($fp, base64_encode($mail['password'])."\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 235) {
exit("AUTH LOGIN - ".$lastmessage);
}
$email_from = $mail['mailfrom'];
}
fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 250) {
fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 250) {
exit("MAIL FROM - ".$lastmessage);
}
}
foreach(explode(',', $mail_to) as $touser) {
$touser = trim($touser);
if($touser) {
fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $touser).">\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 250) {
fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $touser).">\r\n");
$lastmessage = fgets($fp, 512);
exit("RCPT TO - ".$lastmessage);
}
}
}
fputs($fp, "DATA\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 354) {
exit("DATA - ".$lastmessage);
}
fputs($fp, $headers);
fputs($fp, "To: ".$mail_to."\r\n");
fputs($fp, "Subject: $mail_subject\r\n");
fputs($fp, "\r\n\r\n");
fputs($fp, "$mail_message\r\n.\r\n");
$lastmessage = fgets($fp, 512);
if(substr($lastmessage, 0, 3) != 250) {
exit("END - ".$lastmessage);
}
fputs($fp, "QUIT\r\n");
}
测试代码:
<?php
require "sendmail.php";
sendmail("tomail@163.com","消息","测试一下");
注意事项
- 拼写是smtp不是stmp,刚开始还找半天smtplib的库,其实是自带的。
- 文件保存的时候文件名不要写成email,这和库Email重了。