python 发邮件需要用到smtplib, email两个模块,其中smtplib用来发送邮件,email来定义正文和附件,发送的形式
smtplib很简单
smtp = smtplib.SMTP() #生成SMTP实例
smtp.connect("smtp.XXX.com") #发送邮箱的sendmail server
smtp.login("username", "password") #发送邮箱的用户名和密码登录
smtp.sendmail("mail_from", "mail_to", msg.as_string()) #从发信箱发邮件到收信箱
smtp.quit() #退出
email模块
msg=MIMEMultipart('alternative') 多种类的MIME混合支持html/plain
MIMEText(self, _text, _subtype='plain', _charset='us-ascii') 正文内容
MIMEText(content,_subtype='html', _charset='utf-8') content是一个字符串
MIMEImage(self, _imagedata, _subtype=None, _encoder=encoders.encode_base64, **_params) 图片内容
MIMEImage(file('screenshot.png','rb').read()) _imagedata也是一个字符串
MIMEBase(self, _maintype, _subtype, **_params) 基本类型
mime = MIMEBase('text', filename='test_file')
mime.add_header('Content-Disposition', 'attachment', filename='test_file') 内容描述
mime.add_header("Content-ID", '<0>') cid:0
mime.set_payload(f.read()) 读取文件内容
encoders.encode_base64(mime) 如果是图片需要编码
sendmail.py
import smtplib
from email import encoders
from email.mime.text import MIMEText #正文内容
from email.mime.multipart import MIMEMultipart #多种文件类型
from email.mime.base import MIMEBase #基本类型
from email.mime.image import MIMEImage #图片类型
from_mail='XXX@163.com'
to_mail='YYY@sina.cn'
msg=MIMEMultipart('alternative') #混合html/plain
msg['From']=from_mail
msg['To']=to_mail
msg['Subject']='test report'
fp = open('filename.html')
content = fp.read()
fp.close()
con=MIMEText(content,'html', 'utf-8') #正文是filename.html中的内容
msg.attach(con) #把正文加入到多类型文件中
#add picture into content
img=MIMEImage(file('screenshot.png','rb').read()) #图片类型实际上就是多了base64编码
img.add_header('Content-ID','1') #增回属性cid:1
msg.attach(img) #把图片加入到多类型文件中
msg.attach(MIMEText(content+"<img src='cid:1'>", 'html', 'utf-8')) #把图片嵌入到正文中,并放在content之后,否则会覆盖
#attachment
with open('filename') as f:
mime = MIMEBase('text', 'test_file')
mime.add_header('Content-Disposition', 'attachment', filename='test_file')
# mime.add_header("Content-ID", '<0>')
# mime.add_header("X-Attachment-Id", '0')
mime.set_payload(f.read())
# encoders.encode_base64(mime)
msg.attach(mime) #增加附件的通用方法,不包括图片
server=smtplib.SMTP('smtp.163.com')
server.docmd('ehlo','XXX@163.com')
server.login('username.163.com','password')
server.sendmail(from_mail,to_mail,msg.as_string())
server.quit()
加密SMTP
smtp_server = '192.168.10.3'
smtp_port = 587
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
参考
http://www.liaoxuefeng.com/