通过 python 处理 email - Email via Python
Email via Python
1 MIME - Multipurpose Internet Mail Extensions
SMTP - Simple Message Transport Protocol 邮件的发送,
例子 - send email
import smtplib
from email.mime.text import MIMEText
from email.utils import formatdate, make_msgid
mess = 'hello there'
mesgobj = MIMEText(mess)
mesgobj['To'] = 'testrecevier@example.com'
mesgobj['From'] = 'testsender@example.com'
mesgobj['Subject'] = 'Greeting'
mesgobj['Date'] = formatdate(localtime=1) # Date header, formatdate() 生成 email 专门日期格式
mesgobj['Message-ID'] = make_msgid() # make_msgid() 方法生成唯一的 Message-ID,
print(mesgobj.as_string())
print(mesgobj.as_bytes()) s = smtplib.SMTP('SMTP-SERVER-ADDR')
s.send_message(mesgobj)
s.quit() 邮件的解析,
例子 - parsing email,
from email.parser import Parser
headers = Parser().parsestr(mesgobj.as_string()) # mesgobj 为上例中对象.
for h,v in headers.items():
print("Header[%s] - " % h,v)
print('Emial content - ', mesgobj.get_payload()) # 打印邮件正文. 带有附件的邮件发送处理 - Packing MIME,
邮件的附件有 音频, 图像, 压缩文件等等, 通过 python doc 的上的例子看一下儿
对邮件的附件的处理方式,
例子 - send email with attachments,
* an example of how to send the entire contents of a directory as an email message import os
import sys
import smtplib
# For guessing MIME type based on file name extension
import mimetypes
from optparse import OptionParser
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText COMMASPACE = ', ' def main():
parser = OptionParser(usage='''\
Send the contents of a directory as a MIME message. Usage: %prog [options] Unless the -o option is given, the email is sent by forwarding to your local
SMTP server, which then does the normal delivery process. Your local machine
must be running an SMTP server.
''')
parser.add_option('-d', '--directory',
type='string', action='store',
help='''Mail the contents of the specified directory,
otherwise use the current directory. Only the regular
files in the directory are sent, and we don't recurse to
subdirectories.''')
parser.add_option('-o', '--output',
type='string', action='store', metavar='FILE',
help='''Print the composed message to FILE instead of
sending the message to the SMTP server.''')
parser.add_option('-s', '--sender',
type='string', action='store', metavar='SENDER',
help='The value of the From: header (required)')
parser.add_option('-r', '--recipient',
type='string', action='append', metavar='RECIPIENT',
default=[], dest='recipients',
help='A To: header value (at least one required)')
opts, args = parser.parse_args()
if not opts.sender or not opts.recipients:
parser.print_help() # SMTP server 只处理地址有效的 sender 跟 recipients
sys.exit(1)
directory = opts.directory
if not directory:
directory = '.' # 之前的代码的功能是通过 OptionParser 没款完成对命令行参数的解析
# Create the enclosing (outer) message
outer = MIMEMultipart() # 构建一个带附件的 email 对象
outer['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
outer['To'] = COMMASPACE.join(opts.recipients)
outer['From'] = opts.sender
outer.preamble = 'You will not see this in a MIME-aware mail reader.\n' for filename in os.listdir(directory): # 按附件类型做相应的处理
path = os.path.join(directory, filename)
if not os.path.isfile(path):
continue
# Guess the content type based on the file's extension. Encoding
# will be ignored, although we should check for simple things like
# gzip'd or compressed files.
ctype, encoding = mimetypes.guess_type(path) # 附件类型的判断
if ctype is None or encoding is not None:
# No guess could be made, or the file is encoded (compressed), so
# use a generic bag-of-bits type.
ctype = 'application/octet-stream' # zip, pdf 等附件的类型
maintype, subtype = ctype.split('/', 1)
if maintype == 'text': # 处理的 文本text 类型的附件
fp = open(path)
# Note: we should handle calculating the charset
msg = MIMEText(fp.read(), _subtype=subtype)
fp.close()
elif maintype == 'image': # 处理的 图像image 类型的附件
fp = open(path, 'rb')
msg = MIMEImage(fp.read(), _subtype=subtype)
fp.close()
elif maintype == 'audio': # 处理的 音频audio 类型的附件
fp = open(path, 'rb')
msg = MIMEAudio(fp.read(), _subtype=subtype)
fp.close()
else:
fp = open(path, 'rb') # 处理的其他类型的附件:如 zip, pdf 等
msg = MIMEBase(maintype, subtype)
msg.set_payload(fp.read())
fp.close()
# Encode the payload using Base64
encoders.encode_base64(msg)
# Set the filename parameter
msg.add_header('Content-Disposition', 'attachment', filename=filename)
outer.attach(msg)
# Now send or store the message
composed = outer.as_string()
if opts.output: # 保存到文件 store
fp = open(opts.output, 'w')
fp.write(composed)
fp.close()
else:
s = smtplib.SMTP('localhost') # SMTP server 发送处理
s.sendmail(opts.sender, opts.recipients, composed)
s.quit() if __name__ == '__main__':
main() MIME 的解包 - Unpacking MIME 接收方对收到的 MIMEMultipart 的处理,
'''Unpack a MIME message into a directory of files.''' import os
import sys
import email
import errno
import mimetypes
from optparse import OptionParser
def main():
parser = OptionParser(usage='''\
Unpack a MIME message into a directory of files. Usage: %prog [options] msgfile
''')
parser.add_option('-d', '--directory',
type='string', action='store',
help='''Unpack the MIME message into the named
directory, which will be created if it doesn't already
exist.''')
opts, args = parser.parse_args()
if not opts.directory:
parser.print_help()
sys.exit(1) try:
msgfile = args[0]
except IndexError:
parser.print_help()
sys.exit(1) try:
os.mkdir(opts.directory)
except OSError as e:
# Ignore directory exists error
if e.errno != errno.EEXIST:
raise fp = open(msgfile)
msg = email.message_from_file(fp)
fp.close() counter = 1
for part in msg.walk():
# multipart/* are just containers
if part.get_content_maintype() == 'multipart':
continue
# Applications should really sanitize the given filename so that an
# email message can't be used to overwrite important files
filename = part.get_filename()
if not filename:
ext = mimetypes.guess_extension(part.get_content_type())
if not ext:
# Use a generic bag-of-bits extension
ext = '.bin'
filename = 'part-%03d%s' % (counter, ext)
counter += 1
fp = open(os.path.join(opts.directory, filename), 'wb')
fp.write(part.get_payload(decode=True))
fp.close() if __name__ == '__main__':
main() Reference,
https://docs.python.org/3/library/email.html
通过 python 处理 email - Email via Python的更多相关文章
- python auto send email
/*************************************************************************** * python auto send emai ...
- Python深入:Distutils发布Python模块--转载
https://blog.csdn.net/gqtcgq/article/details/49255995 Distutils可以用来在Python环境中构建和安装额外的模块.新的模块可以是纯Pyth ...
- Python 标准库一览(Python进阶学习)
转自:http://blog.csdn.net/jurbo/article/details/52334345 写这个的起因是,还是因为在做Python challenge的时候,有的时候想解决问题,连 ...
- python经典书记必读:Python编程快速上手 让繁琐工作自动化
所属网站分类: 资源下载 > python电子书 作者:熊猫烧香 链接:http://www.pythonheidong.com/blog/article/69/ 来源:python黑洞网,专注 ...
- python trojan development 1st —— use python to send mail and caputre the screen then combine them
import smtplib from email.mime.text import MIMEText msg_from='1@qq.com' #发送方邮箱 passwd='bd' #填入发送方邮箱的 ...
- Python学习【day02】- Python基础练习题
#!/usr/bin/env python # -*- coding:utf8 -*- # 执行Python 脚本的两种方式 # 答:①在windows的cmd窗口下 > D:/Python/p ...
- Python深入:Distutils发布Python模块
Distutils可以用来在Python环境中构建和安装额外的模块.新的模块可以是纯Python的,也可以是用C/C++写的扩展模块,或者可以是Python包,包中包含了由C和Python编写的模块. ...
- 【python之路1】python安装与环境变量配置
直接搜索 Python,进入官网,找到下载,根据个人电脑操作系统下载相应的软件.小编的是windows os .下载python-2.7.9.msi 安装包 双击安装程序,进入安装步骤.在安装过程中 ...
- 使用python+xpath 获取https://pypi.python.org/pypi/lxml/2.3/的下载链接
使用python+xpath 获取https://pypi.python.org/pypi/lxml/2.3/的下载链接: 使用requests获取html后,分析html中的标签发现所需要的链接在& ...
- 【Python网络编程】利用Python进行TCP、UDP套接字编程
之前实现了Java版本的TCP和UDP套接字编程的例子,于是决定结合Python的学习做一个Python版本的套接字编程实验. 流程如下: 1.一台客户机从其标准输入(键盘)读入一行字符,并通过其套接 ...
随机推荐
- Codeforces - A. Watermelon
A. Watermelon time limit per test 1 second memory limit per test 64 megabytes input standard input o ...
- Asp.Net Core下的开源任务调度平台ScheduleMaster—快速上手
概述 ScheduleMaster是一个开源的分布式任务调度系统,它基于Asp.Net Core平台构建,支持跨平台多节点部署运行. 它的项目主页在这里: https://github.com/hey ...
- 图解kubernetes服务打散算法的实现源码
在分布式调度中为了保证服务的高可用和容灾需求,通常都会讲服务在多个区域.机架.节点上平均分布,从而避免单点故障引起的服务不可用,在k8s中自然也实现了该算法即SelectorSpread, 本文就来学 ...
- phpstorm配置git并解决Terminal 中文乱码(Unicode 编码)的方法
前言:在使用PHPstorm的时候,需要用到terminal,主要还是用这个操作git,但是在使用这个的时候会发现,代码里所有中文都是乱码状态,不利于使用,下面就来看看怎么解决这个问题 一.先在php ...
- Selenium的简单使用
selenium的使用对于新手来说十分友好,因为他避开了如今网络中的异步加载抓取的困扰,使得我们大部分的时间可以用于提取信息和存储中,下面就简单的列一些使用的代码,希望给同样初学的你有一定的参考价值. ...
- [bzoj4444] [loj#2007] [洛谷P4155] [Scoi2015] 国旗计划
Description \(A\) 国正在开展一项伟大的计划--国旗计划.这项计划的内容是边防战士手举国旗环绕边境线奔袭一圈.这项计划需要多名边防战士以接力的形式共同完成,为此,国土安全局已经挑选了 ...
- 客户端 jQuery 跨端口 调用 node 服务端
一句话 很顶用 response.setHeader('Access-Control-Allow-Origin', 'http://127.0.0.1:8020'); 说 响应的头文件里设置 一个 h ...
- GitHub学习之路1
对于代码的管理以及维护上,GitHub不失为一个较为明智的选择.而对于GitHub的灵活应用也是相当重要的,以下记录为以防自己忘记. 1. 创建SSH Key ssh-keygen -t rsa –C ...
- robotframework,移动端(小程序)自动化,滚动屏幕的方法
场景描述: 小程序端定位元素有无法定位弹出层内容的问题(自动化工具只能识别到背景主层,无法识别到弹出层) 解决思路: 1.弹出层元素与背景主层元素位置一致,当点击出弹出层时,在定位背景主层即可定位到弹 ...
- 文艺平衡树(区间splay)
文艺平衡树(luogu) Description 题目描述 您需要写一种数据结构(可参考题目标题),来维护一个有序数列. 其中需要提供以下操作:翻转一个区间,例如原有序序列是 5\ 4\ 3\ 2\ ...