python中使用smtplib和email模块发送邮件实例

2019-10-06 17:22:19王振洲

import smtplib

#创建一个带附件的实例
msg = MIMEMultipart()

txt = MIMEText("这是中文的邮件内容哦",'plain','gb2312')   
msg.attach(txt)
#构造附件1
att1 = MIMEText(open('d:drcom.rar', 'rb').read(), 'base64', 'gb2312')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="drcom.rar"'#这里的filename可以任意写,写什么名字,邮件中显示什么名字
msg.attach(att1)

#构造附件2
att2 = MIMEText(open('d:123.txt', 'rb').read(), 'base64', 'gb2312')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="123.txt"'
msg.attach(att2)

#加邮件头
msg['to'] = 'tooooooo@qq.com'
msg['from'] = 'frommmmmmm@gmail.com'
msg['subject'] = 'hello world'

 

 
#发送邮件
try:
    server = smtplib.SMTP()
    server.connect('smtp.gmail.com')
    server.starttls()
    server.login('xxxxx@gmail.com','xxxxxxxxx')#XXX为用户名,XXXXX为密码
    server.sendmail(msg['from'], msg['to'],msg.as_string())
    server.quit()
    print '发送成功'
except Exception, e:
    print str(e)