Python发送Email

来源:互联网 发布:搬家软件哪个好 编辑:程序博客网 时间:2024/05/19 17:47
Python对于Email的分成两个部分:
  1. 对于POP、SMTP的支持。
  2. 对于Email数据的支持。

第一部分: 用POP、SMTP来读取信件:

import getpass, poplibM = 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 functionimport smtplib# Import the email modules we'll needfrom 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 messagemsg = MIMEText(fp.read())fp.close()# me == the sender's email address# you == the recipient's email addressmsg['Subject'] = 'The contents of %s' % textfilemsg['From'] = memsg['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
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()


原创粉丝点击