python实现邮件发送完整代码(带附件发送方式)

实例一:利用SMTP与EMAIL实现邮件发送,带附件(完整代码)

__author__ = ‘Administrator‘
#coding=gb2312

from email.Header import Header
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
import smtplib, datetime


def SendMailAttach():

msg = MIMEMultipart()
att = MIMEText(open(‘测试.xlsx‘, ‘rb‘).read(), ‘base64‘, ‘gb2312‘)
att["Content-Type"] = ‘application/octet-stream‘
att["Content-Disposition"] = ‘attachment; filename="测试.xlsx"‘
msg.attach(att)

msg[‘to‘] = ‘[email protected]
msg[‘from‘] = ‘[email protected]
msg[‘CC‘]=‘[email protected]
msg[‘subject‘] = Header(‘冒烟测试结果 (‘ + str(datetime.date.today()) + ‘)‘,‘gb2312‘)

body = "Python test mail"
msg.attach(MIMEText(body, ‘plain‘))

server = smtplib.SMTP(‘58.62.220.52‘,25)
server.login("用户名","密码")
msg_text=msg.as_string()
server.sendmail(msg[‘from‘], msg[‘to‘],msg_text)
server.close

 

 

实例二:利用SMTP实现简单的邮件发送。(不带附件发送)

__author__ = ‘Administrator‘
#coding=utf-8
import smtplib
msg=["From:[email protected]",‘To:[email protected]‘,"Subject:Test Demo"]
msgBody="Hello world"
smtp=smtplib.SMTP()
smtp.connect("58.62.220.52",25)
smtp.login("用户名","密码")
smtp.sendmail("[email protected]","[email protected]","\r\n\r\n".join(("\r\n".join(msg),msgBody)))
print "邮件发送成功!"
smtp.quit()

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。