Python对于Email的分成两个部分:
# 需要导入的Module
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
COMMASPACE = ', '
# 生成需要的Object
email message.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()
- 对于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 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() s.connect() s.sendmail(me, [you], msg.as_string()) s.close()
- 发送带有图片附件的邮件:
# 需要导入的Module
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
COMMASPACE = ', '
# 生成需要的Object
email message.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()