# python study day15
# 一般不同平台邮件收发过程
# 发件人 -> MUA(Mail User Agent——邮件用户代理) ->
# MTA(Mail Transfer Agent——邮件传输代理) -> 若干个MTA ->
# MDA(Mail Delivery Agent——邮件投递代理) <- MUA <- 收件人
# SMTP 邮件发送协议,python提供 email(负责构造邮件)、smtplib(负责发送邮件)模块
# Message # 一个邮件对象
# +- MIMEBase # 邮件对象基类,类似object
# +- MIMEMultipart # 对各对象组合
# +- MIMENonMultipart
# +- MIMEMessage
# +- MIMEText # 文本邮件对象
# +- MIMEImage # 附件图片邮件
# from email import encodeers
# from email.header import Header
# from emial.mime.text import MIMEText
# from email.utils import parseaddr, formataddr
# import smtplib
#
# def _format_addr(s):
# name, addr = parseaddr(s)
# return formataddr((Header(name, 'utf-8').encode(), addr))
#
# from_addr = input('from:') # 发件地址
# password = input('password:') # 密码
# to_addr = input('to:') # 收件地址
# smtp_server = input('smtp sever:') # 代理邮箱server
#
# msg = MIMEText('hello, send by python study...', 'plain', 'utf-8') # 正文
# msg['From'] = _format_addr('python学习<%s>' % from_addr)
# msg['To'] = _format_addr('myself <%s>' % to_addr) # 如果有多个邮件地址,用,分隔
# msg['Subject'] = Header('来自smtp的问候。。。','utf-8').encode() # 主题
#
# server = smplib.SMTP(smtp_server, 25) # SMTP协议默认端口25
# server.set_debuglevel(1)
# server.login(from_addr, password) #登录SMTP服务器
# server.sendmail(from_addr, [to_addr], msg.as_string()) # [to_addr]list发多人
# server.quit()
# 发送HTML邮件
# msg = MIMEText('<html><body><h1>Hello</h1>' +
# '<p>send by <a href="http://www.python.org">Python</a>...</p>' +
# '</body></html>', 'html', 'utf-8')
# 发送附件邮件
# msg = MIMEMultipart() # 邮件对象
# msg.attach(MIMEText('send with file...', 'plain', 'utf-8'))
# # 添加附件就是加上一个MIMEBase,从本地读取一个图片:
# with open('/Users/michael/Downloads/test.png', 'rb') as f:
# # 设置附件的MIME和文件名,这里是png类型:
# mime = MIMEBase('image', 'png', filename='test.png')
# # 加上必要的头信息:
# mime.add_header('Content-Disposition', 'attachment', filename='test.png')
# mime.add_header('Content-ID', '<0>')
# mime.add_header('X-Attachment-Id', '0')
# # 把附件的内容读进来:
# mime.set_payload(f.read())
# # 用Base64编码:
# encoders.encode_base64(mime)
# # 添加到MIMEMultipart:
# msg.attach(mime)
# 发送正文图片邮件
# 先把图片作为附件添加到邮件,再在html正文中通过src='cid:0'嵌入,多个图 cid:x
# msg.attach(MIMEText('<html><body><h1>Hello</h1>' +
# '<p><img src="cid:0"></p>' +
# '</body></html>', 'html', 'utf-8'))
# 发送同时支持的html和plain格式的邮件
# msg = MIMEMultipart('alternative')
# msg.attach(MIMEText('hello', 'plain', 'utf-8'))
# msg.attach(MIMEText('<html><body><h1>Hello</h1></body></html>', 'html', 'utf-8'))
# 发送加密SMTP邮件
# smtp_server = 'smtp.gmail.com'
# smtp_port = 587 # Gmail的SMTP端口是587
# server = smtplib.SMTP(smtp_server, smtp_port)
# server.starttls() # 之后其他内容一致
# python收取邮件
# 1.用poplib通过pop3把邮件的原始文本下载到本地;
# 2.用email解析原始文本,还原为邮件对象
# import poplib
# # 输入邮件地址, 口令和POP3服务器地址:
# email = input('Email: ')
# password = input('Password: ')
# pop3_server = input('POP3 server: ')
# # 连接到POP3服务器:
# server = poplib.POP3(pop3_server)
# # 可以打开或关闭调试信息:
# server.set_debuglevel(1)
# # 可选:打印POP3服务器的欢迎文字:
# print(server.getwelcome().decode('utf-8'))
# # 身份认证:
# server.user(email)
# server.pass_(password)
# # stat()返回邮件数量和占用空间:
# print('Messages: %s. Size: %s' % server.stat())
# # list()返回所有邮件的编号:
# resp, mails, octets = server.list()
# # 可以查看返回的列表类似[b'1 82923', b'2 2184', ...]
# print(mails)
# # 获取最新一封邮件, 注意索引号从1开始:
# index = len(mails)
# resp, lines, octets = server.retr(index)
# # lines存储了邮件的原始文本的每一行,
# # 可以获得整个邮件的原始文本:
# msg_content = b'\r\n'.join(lines).decode('utf-8')
# # 稍后解析出邮件:
# msg = Parser().parsestr(msg_content)
# # 可以根据邮件索引号直接从服务器删除邮件:
# # server.dele(index)
# # 关闭连接:
# server.quit()
#
# 解析邮件内容
# from email.parser import Parser
# from email.header import decode_header
# from email.utils import parseaddr
# import poplib
# msg = Parser().parsestr(msg_content) # 转为Message对象
# # indent用于缩进显示:
# def print_info(msg, indent=0): # 递归Message对象
# if indent == 0:
# for header in ['From', 'To', 'Subject']:
# value = msg.get(header, '')
# if value:
# if header=='Subject':
# value = decode_str(value)
# else:
# hdr, addr = parseaddr(value)
# name = decode_str(hdr)
# value = u'%s <%s>' % (name, addr)
# print('%s%s: %s' % (' ' * indent, header, value))
# if (msg.is_multipart()):
# parts = msg.get_payload()
# for n, part in enumerate(parts):
# print('%spart %s' % (' ' * indent, n))
# print('%s--------------------' % (' ' * indent))
# print_info(part, indent + 1)
# else:
# content_type = msg.get_content_type()
# if content_type=='text/plain' or content_type=='text/html':
# content = msg.get_payload(decode=True)
# charset = guess_charset(msg)
# if charset:
# content = content.decode(charset)
# print('%sText: %s' % (' ' * indent, content + '...'))
# else:
# print('%sAttachment: %s' % (' ' * indent, content_type))
# def decode_str(s): # decode解码
# value, charset = decode_header(s)[0]
# if charset:
# value = value.decode(charset)
# return value
# def guess_charset(msg): # 检测编码
# charset = msg.get_charset()
# if charset is None:
# content_type = msg.get('Content-Type', '').lower()
# pos = content_type.find('charset=')
# if pos >= 0:
# charset = content_type[pos + 8:].strip()
# return charset
# 运行结果
# +OK Welcome to coremail Mail Pop3 Server (163coms[...])
# Messages: 126. Size: 27228317
#
# From: Test <xxxxxx@qq.com>
# To: Python爱好者 <xxxxxx@163.com>
# Subject: 用POP3收取邮件
# part 0
# --------------------
# part 0
# --------------------
# Text: Python可以使用POP3收取邮件……...
# part 1
# --------------------
# Text: Python可以<a href="...">使用POP3</a>收取邮件……...
# part 1
# --------------------
# Attachment: application/octet-stream
廖雪峰Python学习笔记day15
最新推荐文章于 2024-08-23 16:53:34 发布