前言:前两天分享了一下邮件的发送,但是存在的问题也很明显,首先是发送需要经过163或QQ邮箱服务器,而且不是真正的匿名,还是能够收到回复信息,其次如果系统运行在内网,限制163等,则邮件会发送失败!
于是,今天分享一个真正意义上的匿名发送(只能在Linux下运行,后面还要配置文件.....)
惯例,先上代码:
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib
class MailNoReply(object):
def __FormatAddress(self, text):
name, addr = parseaddr(text)
return formataddr((Header(name, 'utf8').encode(), addr))
def SendOneMail(self, sender, receiver, subject, content):
'''
利用本地sendmail服务发一封信
:param sender: [string] 发信人地址 xx@yy.zz 格式,可杜撰
:param receiver: [string] 收信人地址 xx@yy.zz 格式,需真实存在
:param subject: [string] 邮件主题
:param content: [string] 邮件内容
:return: True/False 成功/失败
'''
try:
message = MIMEText(content, 'plain', 'utf8')
message['From'] = self.__FormatAddress('凌晨起床敲代码(随便写) <%s>' % sender)
message['To'] = self.__FormatAddress('收件人名称(随便写) <%s>' % receiver)
message['Subject'] = Header(subject, 'utf8').encode()
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, [receiver], message.as_string())
return True
except smtplib.SMTPException as e:
return False
if __name__ == "__main__":
from datetime import datetime
import random
random_password = ''.join(str(i) for i in random.sample(range(0, 9), 6))
email = "xxxxxxxx@qq.com"
foo = MailNoReply()
foo.SendOneMail('xxx@xxx.xx', email, '密码重置',
'亲爱的客户,您于%s发起密码重置,新密码为%s,如非本人操作请速联系管理员!' % (datetime.now().strftime('%Y-%m-%d %H:%M:%S'), random_password))
效果图:
前提是需要配置sendmail:
ubuntu
sudo apt-get install sendmail sendmail-cf
sudo apt-get install mailutils
修改/etc/mail/sendmail.mc中DAEMON_OPTIONS(Family=inet, Name=MTA-v4, Port=smtp, Addr=127.0.0.1')dnl的127.0.0.1为0.0.0.0
sudo m4 sendmail.mc > sendmail.cf
把/etc/hosts中“127.0.0.1 localhost.localdomain localhost 主机名称”保留其他注掉
用echo “邮件正文” | mail -s 邮件主题 test@126.com -a From xxx@xx.xx测试一把
centos
sudo yum install -y sendmail sendmail-cf
sudo yum install mailx
修改/etc/mail/sendmail.mc中DAEMON_OPTIONS(Port=smtp,Addr=127.0.0.1, Name=MTA')dnl的127.0.0.1为0.0.0.0
sudo m4 /etc/mail/sendmail.mc > /etc/mail/sendmail.cf
sudo service sendmail start [ centos7 --> systemctl start sendmail.service ]
用echo “邮件正文” | mailx -s 邮件主题 test@126.com -r admin@xx.xx测试一把
用python脚本本机测试一把