- 浏览: 1777758 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (723)
- IE 国际化 (1)
- java (310)
- python (52)
- Spring (101)
- eclipse (43)
- birt (10)
- exe4j (1)
- ActiveMQ (3)
- HornetQ (7)
- Ext (16)
- Linux (50)
- james (1)
- mail (3)
- 经验 (288)
- tomcat (5)
- Netty (3)
- ant (6)
- rsync (2)
- MD5 (3)
- 正则表达式 (3)
- 非技术 (59)
- mysql (28)
- sftp (1)
- Commons (2)
- oracle (3)
- vsftp (1)
- jdoc (1)
- socket (3)
- SEDA (2)
- UUID (1)
- quartz (7)
- javascript (50)
- sql (5)
- array (3)
- POI (3)
- redis (2)
- junit (4)
- 二维码 (1)
- jdk (8)
- h2 (6)
- maven (37)
- JVM (5)
- html (4)
- css (1)
- excel (4)
- myeclipse (2)
- scala (0)
- jQuery (5)
- log (10)
- slf4j (2)
- log4j (9)
- REST (15)
- guava (18)
- Joda-Time (7)
- ini4j (1)
- 配置文件 (2)
- lucene (1)
- database (3)
- curator (2)
- zookeeper (3)
- 并发 (2)
- jetty (6)
- ehcache (5)
- windows (1)
- protobuf (1)
- select2 (2)
- easyui (10)
- Freemarker (1)
- Filter (1)
- twisted (1)
- DateTime (11)
- mockrunner (1)
- DataSource (4)
- ajax (1)
- shell (18)
- powermockito (5)
- json (5)
- lombok (1)
- jointjs (1)
- cookie (1)
- mybatis (11)
- 加密解密 (2)
- 安全 (2)
- web (1)
- notepad++ (3)
- mac (48)
- sublime (14)
- git (7)
- docker (10)
- jar (1)
- gson (5)
- ubuntu (3)
- 模式 (1)
- neo4j (2)
- elasticsearch (1)
- OmniGranffle (1)
- ASCII (1)
- jdbc (3)
- kafka (1)
- MQ (1)
- chrome (3)
- 华为 (1)
- 路由器 (1)
- api (2)
- 架构 (1)
- 设计模式 (1)
- pip (4)
- springboot (48)
- 数据库 (4)
- thread (1)
- java.thread (1)
- sqlite (1)
- postman (1)
- springboot-actuator (2)
- jwt (1)
- token (1)
- brew (9)
- vim (1)
- virtualbox (1)
- Swagger (1)
- spring-retry (3)
- 调度 (1)
- item2 (5)
- graph (12)
- jgrapht (12)
- tuple (1)
- hadoop (5)
- curl (1)
- 算法 (3)
- Jekyll (1)
- github (1)
- ssh-keygen (1)
- zip (2)
- http (2)
- RestTemplate (8)
- 文件处理 (2)
- XStream (1)
- XML (3)
- JAXB (1)
- 笛卡尔积 (2)
- hive (1)
- 搜狗输入法 (1)
- 常用java类 (2)
- nginx (1)
- log4j2 (1)
- drawio (2)
- 安卓 (1)
- 小米 (1)
- okhttp (1)
- requests (1)
- 格式化 (2)
- MySQL Workbench (1)
- 分布式 (1)
- zip4j (1)
- hbase (5)
- hikari (1)
- javers (1)
- pydatetime (4)
- pyassert (1)
- pylog (2)
- tree (2)
- download (1)
- zeppelin (1)
- utils (2)
- wget (1)
- 鼠标 (1)
- 位运算 (2)
- open api (1)
- 域名 (1)
最新评论
-
youngcoder:
haohaohao~
Spring cache 注解功能不起作用的解决方案 -
kanpiaoxue:
lixz 写道有具体实例demo吗好多年前写的了。你还是去官网 ...
spring batch(一):基础部分 -
lixz:
有具体实例demo吗
spring batch(一):基础部分 -
BuDongOrz:
...
Spring MVC controller 读取配置文件 -
hvang1988:
理解错了,原来还是计数,不是时间
spring batch(二):核心部分(1):配置Spring batch
参考: http://docs.python.org/library/email-examples.html#email-examples
Here are a few examples of how to use the email package to read, write, and send simple email messages, as well as more complex MIME messages.
First, let’s see how to create and send a simple text message:
# Import smtplib for the actual sending function import smtplib # Import the email modules we'll need from email.mime.text import MIMEText # Open a plain text file for reading. For this example, assume that # the text file contains only ASCII characters. fp = open(textfile, 'rb') # Create a text/plain message msg = MIMEText(fp.read()) fp.close() # me == the sender's email address # you == the recipient's email address msg['Subject'] = 'The contents of %s' % textfile msg['From'] = me msg['To'] = you # Send the message via our own SMTP server, but don't include the # envelope header. s = smtplib.SMTP('localhost') s.sendmail(me, [you], msg.as_string()) s.quit()
And parsing RFC822 headers can easily be done by the parse(filename) or parsestr(message_as_string) methods of the Parser() class:
# Import the email modules we'll need from email.parser import Parser # If the e-mail headers are in a file, uncomment this line: #headers = Parser().parse(open(messagefile, 'r')) # Or for parsing headers in a string, use: headers = Parser().parsestr('From: <user@example.com>\n' 'To: <someone_else@example.com>\n' 'Subject: Test message\n' '\n' 'Body would go here\n') # Now the header items can be accessed as a dictionary: print 'To: %s' % headers['to'] print 'From: %s' % headers['from'] print 'Subject: %s' % headers['subject']
Here’s an example of how to send a MIME message containing a bunch of family pictures that may be residing in a directory:
# Import smtplib for the actual sending function import smtplib # Here are the email package modules we'll need from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart COMMASPACE = ', ' # Create the container (outer) email message. msg = MIMEMultipart() msg['Subject'] = 'Our family reunion' # me == the sender's email address # family = the list of all recipients' email addresses msg['From'] = me msg['To'] = COMMASPACE.join(family) msg.preamble = 'Our family reunion' # Assume we know that the image files are all in PNG format for file in pngfiles: # Open the files in binary mode. Let the MIMEImage class automatically # guess the specific image type. fp = open(file, 'rb') img = MIMEImage(fp.read()) fp.close() msg.attach(img) # Send the email via our own SMTP server. s = smtplib.SMTP('localhost') s.sendmail(me, family, msg.as_string()) s.quit()
Here’s an example of how to send the entire contents of a directory as an email message: [1]
#!/usr/bin/env python """Send the contents of a directory as a MIME 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() sys.exit(1) directory = opts.directory if not directory: directory = '.' # Create the enclosing (outer) message outer = MIMEMultipart() 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' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = open(path) # Note: we should handle calculating the charset msg = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(path, 'rb') msg = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(path, 'rb') msg = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(path, 'rb') 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: fp = open(opts.output, 'w') fp.write(composed) fp.close() else: s = smtplib.SMTP('localhost') s.sendmail(opts.sender, opts.recipients, composed) s.quit() if __name__ == '__main__': main()
Here’s an example of how to unpack a MIME message like the one above, into a directory of files:
#!/usr/bin/env python """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, 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()
Here’s an example of how to create an HTML message with an alternative plain text version: [2]
#!/usr/bin/env python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # me == my email address # you == recipient's email address me = "my@email.com" you = "your@email.com" # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = "Link" msg['From'] = me msg['To'] = you # Create the body of the message (a plain-text and an HTML version). text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org" html = """\ <html> <head></head> <body> <p>Hi!<br> How are you?<br> Here is the <a href="http://www.python.org">link</a> you wanted. </p> </body> </html> """ # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) # Send the message via local SMTP server. s = smtplib.SMTP('localhost') # sendmail function takes 3 arguments: sender's address, recipient's address # and message to send - here it is sent as one string. s.sendmail(me, you, msg.as_string()) s.quit()
发表评论
-
wget下载文件夹
2021-01-14 13:23 754使用wget下载文件夹的功能和python快速启动HT ... -
python处理时间
2021-01-08 12:55 221from datetime import dat ... -
python的sys.exit()的0-255问题
2020-08-14 16:42 636最近写了一个python脚本用到了sys.exit( ... -
如何使用Python SimpleHTTPServer提供UTF-8编码的文件?
2020-08-13 21:15 548如何使用Python SimpleHTTPServer提供 ... -
python计算方法耗时
2020-07-21 10:18 515from datetime import dat ... -
python2的datetime格式化
2020-06-03 16:08 313官网地址: https://docs.python.o ... -
python的简易教程
2020-05-20 09:56 269《Learn Python Programming》: ... -
python的log文件回滚
2020-05-18 15:03 334python生成按照文件大小进行回滚的日志 ... -
python的assert断言
2020-05-15 11:09 330举例: assert len(lists) & ... -
python的datetime
2020-05-15 10:56 259参考文章: https://www.programi ... -
python打印日志到标准输出
2020-04-30 12:17 576import logging ... -
python需求文件requirements.txt的创建及使用
2020-03-25 21:34 960迁移python环境是很麻烦的事情,需要精准的安装一 ... -
python运行os.system(cmd)的退出问题
2020-02-26 10:02 2231发现之前有人写了一个python的脚本使用os.sy ... -
使用python自带的http模块(urllib2)发送POST请求
2019-12-30 15:20 787python的requests的package非常好用 ... -
python获得机器名和IP地址
2019-12-27 16:34 325import socket # ... -
python处理xml
2019-11-27 16:57 304使用python的内置功能 xml.etree.Elemen ... -
python requests的例子
2019-10-08 15:03 323# get import requests url ... -
pip一次安装多个package
2019-07-01 15:45 941在一个pip的命令行里面可以同时指定安装多个package。 ... -
pip加速
2019-06-27 20:17 503原文:https://blog.csdn.net/z ... -
python SimpleHTTPServer和SimpleXMLRPCServer
2018-11-19 22:15 1108python有2个非常有用的内置服务器: Simp ...
相关推荐
Completely updated for version 3.x, Programming Python also delves into the language as a software development tool, with many code examples scaled specifically for that purpose. Topics include: ...
Completely updated for version 3.x, Programming Python also delves into the language as a software development tool, with many code examples scaled specifically for that purpose. Topics include: ...
对于压缩包中的"Examples_email"文件,它可能包含了更具体的例子,如使用不同的邮件格式(HTML、纯文本)、添加多个附件、处理抄送和密送等。你可以解压并查看这些文件以获取更深入的理解。通过阅读和实践这些示例,...
preventing credit card fraud, filtering out spam from our email inboxes, detecting and diagnosing medical diseases, the list goes on and on. If you want to become a machine learning practitioner, a ...
Python参考手册,官方正式版参考手册,chm版。以下摘取部分内容:Navigation index modules | next | Python » 3.6.5 Documentation » Python Documentation contents What’s New in Python What’s New In ...
5. `examples/`:示例代码,演示如何使用protobuf定义消息类型、生成代码以及序列化和反序列化数据。 6. `LICENSE`:许可文件,说明protobuf的授权条款,通常是Apache 2.0或类似的开源许可。 7. `README`:包含...
除了基本的步骤定义,`Behave`还支持更复杂的结构,如`Scenario Outline`(模板场景)、`Background`(背景)以及`Examples`(示例数据)。此外,还可以自定义断言库,使用数据驱动测试,甚至集成到持续集成/持续...
Programming Python, 2nd Edition 目录如下,需要下载的朋友不要错过哦~ Programming Python, 2nd Edition By Mark Lutz Publisher : O'Reilly Pub Date : March 2001 ISBN : 0-596-00085-5 Pages : 1256 ...
- `examples/`: 示例代码展示如何使用PugSQL - `tests/`: 单元测试确保库的正确功能 - `setup.py`: 用于安装PugSQL的Python脚本 通过安装并探索这个压缩包,你可以深入了解PugSQL的用法,包括如何定义查询,如何...
Now, Python expert Doug Hellmann introduces every major area of the Python 3.x library through concise source code and output examples. Hellmann’s examples fully demonstrate each feature and are ...
- `examples`:使用Python-KnockKnock的示例脚本 - `README.md`:库的使用说明 - `LICENSE`:授权信息 9. **总结** Python-KnockKnock简化了在机器学习项目中实现训练结束通知的过程,让开发者能够更专注于模型...
Master the Powerful Python 3 Standard Library through Real Code Examples The Python 3 Standard Library contains hundreds of modules for interacting with the operating system, interpreter, and Internet...
This book gives you the skills you need to use Python for penetration testing, with the help of detailed code examples. This book has been updated for Python 3.6.3 and Kali Linux 2018.1. Key Features...
Interesting and easy-to-follow examples, to name some, news topic classification, spam email detection, online ad click-through prediction, stock prices forecast, will keep you glued till you reach ...
5. **示例**:`examples/`目录中可能有使用库的示例代码,帮助用户快速上手。 6. **LICENSE**:包含版权和许可信息,定义了库的使用、修改和分发的规则。 7. **README**:提供库的基本信息、安装指南和使用方法。 ...
Chapter 3, Spam Email Detection with Naive Bayes, covers classification, naive Bayes, and its in-depth implementation, classification performance evaluation, model selection and tuning, and cross-...