Python群发邮件实例代码

时间:2021-05-05 18:42:35 

直接上代码了


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,群发邮件
0
投稿

猜你喜欢

  • 自然语言处理之文本热词提取(含有《源码》和《数据》)

    2021-11-26 11:14:58
  • Python实现实时显示进度条的六种方法

    2022-03-27 02:09:35
  • Python环境下安装使用异步任务队列包Celery的基础教程

    2023-08-23 23:06:48
  • 显卡驱动CUDA 和 pytorch CUDA 之间的区别

    2021-12-29 04:35:31
  • PL/SQL数据类型及操作符

    2009-02-26 11:17:00
  • asp无组件实现画简单图形的类

    2004-06-17 13:30:00
  • [翻译]标记语言和样式手册 Chapter 8 再谈清单

    2008-01-29 13:16:00
  • 使用go求幂的几种方法小结

    2023-09-23 05:07:45
  • 总结Python编程中函数的使用要点

    2021-03-15 01:49:52
  • IE6/7关于 Absolute Position 、relative 的一些意外

    2008-11-27 11:34:00
  • 原创一个AJAX类

    2008-07-24 13:29:00
  • 只有mdf文件的数据库附加失败的修复方法分享(置疑、只读)

    2012-02-12 15:55:17
  • XML DOM介绍和例子

    2007-10-15 20:23:00
  • Flask框架web开发之零基础入门

    2021-01-03 22:23:02
  • 蜕变——记QQ医生3.0

    2009-09-16 14:41:00
  • 导航设计的流行趋势

    2007-12-25 12:06:00
  • Python学习之日志模块详解

    2022-06-24 09:20:22
  • 浅析python的Lambda表达式

    2021-11-16 23:51:19
  • php5.2 Json不能正确处理中文、GB编码的解决方法

    2023-10-26 13:49:28
  • 不支持fsockopen但支持culr环境下下ucenter与modoer通讯问题

    2023-09-11 00:33:45
  • asp之家 网络编程 m.aspxhome.com