实例一:利用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()