Python群发邮件实例代码

860次阅读  |  发布于5年以前

直接上代码了

复制代码 代码如下:

import smtplib
msg = MIMEMultipart()

构造附件1

att1 = MIMEText(open('/home/a2bgeek/develop/python/hello.py', 'rb').read(), 'base64', 'gb2312')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="hello.txt"'#这里的filename可以任意写,写什么名字,邮件中显示什么名字
msg.attach(att1)

构造附件2

att2 = MIMEText(open('/home/a2bgeek/develop/python/mail.py', 'rb').read(), 'base64', 'gb2312')

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

att2["Content-Disposition"] = 'attachment; filename="123.txt"'

msg.attach(att2)

加邮件头

strTo = ['XXX1@139.com', 'XXX2@163.com', 'XXX3@126.com']
msg['to']=','.join(strTo)
msg['from'] = 'YYY@163.com'
msg['subject'] = '邮件主题'

发送邮件

try:
server = smtplib.SMTP()
server.connect('smtp.163.com')
server.login('YYY@163.com','yourpasswd')
server.sendmail(msg['from'], strTo ,msg.as_string())
server.quit()
print '发送成功'
except Exception, e:
print str(e)

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8