转:Python发送Email(1)
上一篇 /
下一篇 2012-06-20 14:41:57
/ 个人分类:自动化测试相关
Python对于
Email的分成两个部分:
- 对于POP、SMTP的支持。
- 对于Email数据的支持。
第一部分:
用POP、SMTP来读取信件:
import getpass, poplib
M = poplib.POP3('localhost')
M.user(getpass.getuser())
M.pass_(getpass.getpass())
numMessages = len(M.list()[1])
for i in range(numMessages):
for j in M.retr(i+1)[1]:
第二部分,对于数据的支持:
- 发送普通文本类型邮件:
# Import smtplib for the actual sending function
import smtplib
# Import theemailmodules we'll need
fromemail.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'semailaddress
# you == the recipient'semailaddress
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()
s.connect()
s.sendmail(me, [you], msg.as_string())
s.close()
- 发送带有图片附件的邮件:
import smtplib
# 需要导入的Module
from
email.mime.image import MIMEImage
from
email.mime.multipart import MIMEMultipart
COMMASPACE = ', '
# 生成需要的Object
emailmessage. msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
# me ==源地址
# family = 需要发送的地址
msg['From'] = me
msg['To'] = COMMASPACE.join(family)
msg.preamble = 'Our family reunion'
#pngfiles是一些图形的文件名列表
for file in pngfiles:
# 打开文件
# 自动探测图形类型
fp = open(file, 'rb')
img = MIMEImage(fp.read())
fp.close()
msg.attach(img)
# 通过SMTP发送
s = smtplib.SMTP()
s.connect()
s.sendmail(me, family, msg.as_string())
s.close()
比较简单,明天继续
收藏
举报
TAG: