直接上代码了
代码如下:
import smtplibmsg = mimemultipart()
#构造附件1att1 = 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.
好了今天就到这里。