种子灵感
http://www.runoob.com/python/python-email.html
https://blog.csdn.net/xiaosongbk/article/details/60142996
项目中实际使用
发送附件, excel 文件
注意使用 Python 3的环境不会考虑太多 编码转化等问题
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email import encoders
from email.mime.base import MIMEBase
from email.utils import parseaddr, formataddr
from Tools.oyyo_datetime import OYYODatetime
SMTP_SERVER = 'xxx.com.cn' # 发送邮件服务器
FROM_MAIL = 'xxx.com.cn' # 发送邮件用户名
MAIL_PASS = 'xxx' # 密码
TO_MAIL = ['2219386421@qq.com'] # yang
BODY = " 请查收!"
SUBJECT = '请查收!'
class SendEmail(object):
def __init__(self):
pass
def formatAddr(self, s):
"""格式化邮件地址"""
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
def send_email(self, path):
smtp_server = SMTP_SERVER
from_mail = FROM_MAIL
mail_pass = MAIL_PASS
to_mail = TO_MAIL
body = BODY
# 构造一个MIMEMultipart对象代表邮件本身
msg = MIMEMultipart()
# Header对中文进行转码
msg['From'] = Header("服务端", 'utf-8')
msg['To'] = Header("运营", 'utf-8')
now = OYYODatetime.get_now_string()
sub = SUBJECT + " " + now
print(sub)
subject = sub
msg['Subject'] = Header(subject, 'utf-8')
# plain代表纯文本
msg.attach(MIMEText(body, 'plain', 'utf-8'))
# att1 = MIMEText(open('aaa.xlsx', 'rb').read(), 'base64', 'utf-8')
att1 = MIMEText(open(path, 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att1["Content-Disposition"] = 'attachment; filename="userAddress.xlsx"' # 这个名字是和发送出去保持一致的
msg.attach(att1)
try:
s = smtplib.SMTP()
s.connect(smtp_server, "25")
s.login(from_mail, mail_pass)
s.sendmail(from_mail, to_mail, msg.as_string()) # as_string()把MIMEText对象变成str
s.quit()
print("成功了")
except smtplib.SMTPException as e:
print(("Error: %s") % e)
print("失败了")
if __name__ == '__main__':
s = SendEmail()
# sendMail('请查收!', 'a.txt')
s.send_email("aaa.xlsx")