Python email
跳转到导航
跳转到搜索
消息头
导入:
import email.header
编码:
email.header.Header(str, encoding).encode()
解码:
email.header.decode_header(str)
返回一个列表,其元素为一个 (bytes, encoding) 的二元元组。
解码邮件头
import re
import email.header
def decode_multiline_header(s):
return ''.join(b.decode(e or 'ascii') for b, e in email.header.decode_header(re.sub(r'\n\s+', ' ', s)))
发送邮件
发送纯文本邮件:
import smtplib
from getpass import getpass
s = smtplib.SMTP('smtp.163.com')
status = s.login('xxx', getpass())[0]
if status == 235:
msg = 'From: xxx@163.com\r\n'\
'To: yyy@gmail.com\r\n'\
'Subject: zzz\r\n'\
'\r\n'
msg += 'content'
s.sendmail('xxx@163.com', 'yyy@gmail.com', msg)
q.quit()
发送附件,SSL连接:
import smtplib
from getpass import getpass
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
msg = MIMEMultipart()
msg['Subject'] = 'subject'
msg['From'] = 'user <user@gmail.com>' # ASCII only!
msg['To'] = 'other@gmail.com'
submsg = MIMEBase('application', 'x-xz')
submsg.set_payload(open(path, 'rb').read())
encoders.encode_base64(submsg)
submsg.add_header('Content-Disposition', 'attachment', filename=path)
msg.attach(submsg)
s = smtplib.SMTP_SSL('smtp.gmail.com')
s.login('user', getpass())
s.sendmail('user@gmail.com', 'other@gmail.com', msg.as_string())
s.quit()
注意: MIMEMultipart 等是 email.message.Message 的子类,其对象类似于键可重复的有序字典。使用 get_all 方法获取某个键的所有值, replace_header 可以更新第一个找到的头信息。
更复杂的示例
发送可选的 HTML 邮件。包括登陆到 SMTP 服务器的部分。适用于 Python 2 & 3:
# vim:fileencoding=utf-8
import re
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
smtp_host = 'SMTP server here'
mail_user = 'sender'
mail_pass = 'password'
mail_from = '名字 <%s>' % mail_user
addr_re = re.compile(r'(.*?)\s+(<[^>]+>)($|,\s*)')
def sendmail(msg):
s = smtplib.SMTP(smtp_host)
s.login(mail_user, mail_pass)
# send_message is for Python 3.2+
# s.send_message(msg)
s.sendmail(msg['From'], msg['To'], msg.as_string())
s.quit()
def assemble_mail(subject, to, html=None, text=None):
if html is None and text is None:
raise TypeError('no message given')
if html:
html = MIMEText(html, 'html', 'utf-8')
if text:
text = MIMEText(text, 'plain', 'utf-8')
if html and text:
msg = MIMEMultipart('alternative', _subparts = [text, html])
else:
msg = html or text
msg['Subject'] = encode_header(subject)
msg['From'] = encode_header_address(mail_from)
msg['To'] = encode_header_address(to)
return msg
def encode_header_address(s):
return addr_re.sub(_addr_submatch, s)
def encode_header(s):
return Header(s, 'utf-8').encode() if not eight_bit_clean(s) else s
def _addr_submatch(m):
return encode_header(m.group(1)) + ' ' + m.group(2) + m.group(3)
def eight_bit_clean(s):
return all(ord(c) < 128 for c in s)