DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

用python发送各种形式的邮件


分别是发送纯文本邮件、html格式邮件,以及带附件的html格式邮件。纯文本邮件消息体是普通字符串,html格式邮件中消息体是MIMEText型对象,这种对象的特点是不能加附件;带附件的html格式邮件中消息体是MIMEMultipart型对象,正文和附件都用attach()方法添加。

代码如下(红色字体部分是一个html格式文本的示例,可跳过不看):

import smtplib

from email.mime.text import MIMEText

from email.mime.multipart import MIMEMultipart

if name=='main':

msg_body=''' <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

BVT Report

Unit Test Results Summary

TestsFailuresErrorsSuccess rateTime
382338236.0466666667%1.65


Diffcount Report

GODU SERVER

LANGADDMODDELA&MBLKCMTNBNCRATE
Java52774005277455018036393440.41
XML39900399003990.12

GAPI

LANGADDMODDELA&MBLKCMTNBNCRATE
Java52774005277455018036393440.41
XML39900399003990.12

GODU WEB

LANGADDMODDELA&MBLKCMTNBNCRATE
Java52774005277455018036393440.41
XML39900399003990.12

'''

mail_server = smtplib.SMTP('124.127.106.5') # use 'smtp.163.com' to send email with 163

mail_server.set_debuglevel(1)

mail_server.login('lichao1', 'abaqus67')

#发送纯文本邮件

#from_addr = 'LiChaolichao1@boco.com.cn'

#to_addr = 'LiChaolichao1@boco.com.cn'

#subj = 'hello'

#date = datetime.datetime.now().strftime("%d/%m/%Y %H:%M")

#msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % (from_addr, to_addr, subj, date, message_body)

#mail_server.sendmail(from_addr, to_addr, msg)

#发送html格式邮件

#msg = MIMEText (msg_body, 'html')

#msg['From'] = 'LiChaolichao1@boco.com.cn'

#msg['To'] = 'LiChaolichao1@boco.com.cn'

#msg['Subject'] = 'hello'

#mail_server.sendmail('LiChaolichao1@boco.com.cn', 'LiChaolichao1@boco.com.cn', msg.as_string())

#发送带附件的html格式邮件

msg = MIMEMultipart ()

part2 = MIMEText(msg_body, 'html')

msg. attach (part2)

att = MIMEText(open('e:\BVT\GODU-BVT\GCIF\build\2011-01-12\GAPI\build\result\junit\junit-noframes.html', 'rt').read())

att["Content-Type"] = 'application/octet-stream'

att["Content-Disposition"] = 'attachment; filename="JUnitReport.html"'

msg. attach (att)

msg['From'] = 'LiChaolichao1@boco.com.cn'

msg['To'] = 'LiChaolichao1@boco.com.cn'

msg['Subject'] = 'hello'

mail_server.sendmail('LiChaolichao1@boco.com.cn', 'LiChaolichao1@boco.com.cn', msg.as_string())

mail_server.quit()

注意:sendmail()发送邮件时,如果收件人有多个,必须放在一个list中作为参数,如果是字符串,则只发给第一个人,似乎只有python2.6要求是list型参数。



Published

Jan 12, 2011

Last Updated

Jan 12, 2011

Category

Tech

Tags

  • 附件 1
  • HTML 9
  • mime 1
  • Python 136
  • smtp 2
  • 邮件 2

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor