Python群发邮件实例代码

yipeiwu_com5年前Python基础

直接上代码了

复制代码 代码如下:

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)

细心的读者会发现代码中有这样一句:msg['to']=','.join(strTo),但是msg[['to']并没有在后面被使用,这么写明显是不合理的,但是这就是stmplib的bug。你只有这样写才能群发邮件。查明原因如下:

The problem is that SMTP.sendmail and email.MIMEText need two different things.

email.MIMEText sets up the “To:” header for the body of the e-mail. It is ONLY used for displaying a result to the human being at the other end, and like all e-mail headers, must be a single string. (Note that it does not actually have to have anything to do with the people who actually receive the message.)

SMTP.sendmail, on the other hand, sets up the “envelope” of the message for the SMTP protocol. It needs a Python list of strings, each of which has a single address.

So, what you need to do is COMBINE the two replies you received. Set msg‘To' to a single string, but pass the raw list to sendmail.

好了今天就到这里。

相关文章

python搜索包的路径的实现方法

查看python搜索包的路径的实现方法: python搜索包的路径存储在sys.path下 查看方法: import sys sys.path 临时添加python搜索包路径的方法: 方...

Python网络编程之TCP与UDP协议套接字用法示例

本文实例讲述了Python网络编程之TCP与UDP协议套接字用法。分享给大家供大家参考,具体如下: TCP协议 服务器端: #!/usr/bin/env python from so...

Python实现的字典排序操作示例【按键名key与键值value排序】

本文实例讲述了Python实现的字典排序操作。分享给大家供大家参考,具体如下: 对字典进行排序?这其实是一个伪命题,搞清楚python字典的定义---字典本身默认以key的字符顺序输出显...

解决Python中list里的中文输出到html模板里的问题

最仅在做一个数据分析的功能时候遇到将list中的中文字符按照数组的形式输出到html模板里的js中进行处理,但是直接输出模板会按照unicode编码输出,这个问题真的让人头大。 本方法实...

在Ubuntu系统下安装使用Python的GUI工具wxPython

(一)wxpython的安装     Ubuntu下的安装,还是比较简单的。 #使用:apt-cache search wxpython 测试一下,可以...