例子,python邮件发送,支持smtp身份验证。
代码:
import sys, smtplib, mimewriter, base64, stringio, os, string, time
from email.mimemultipart import mimemultipart
from email.mimebase import mimebase
from email.mimetext import mimetext
from email.utils import commaspace, formatdate
from email import encoders
def send_mail(send_from, send_to, subject, text, files=[],
server="localhost", user = none, password = none):
assert type(send_to)==list
assert type(files)==list
msg = mimemultipart()
msg['from'] = send_from
msg['to'] = commaspace.join(send_to)
msg['date'] = formatdate(localtime=true)
msg['subject'] = subject
msg.attach( mimetext(text) )
for file in files:
part = mimebase('application', "octet-stream")
part.set_payload( open(file,"rb").read() )
encoders.encode_base64(part)
part.add_header('content-disposition', 'attachment; filename="%s"' % os.path.basename(file))
msg.attach(part)
smtp = smtplib.smtp(server)
if (user != none):
smtp.ehlo()
smtp_userid64 = base64.encodestring(user)
smtp.docmd("auth", "login " + smtp_userid64[:-1])
if password != none:
smtp_pass64 = base64.encodestring(password)
smtp.docmd(smtp_pass64[:-1])
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
# 测试python邮件发送
#test_smtp.py
from smtp import *
send_mail('jbxue1@163.com',
['jbxue2@gmail.com', 'jbxue2@163.com'],
u'标题:来自jb200.com的测试邮件',
u'内容:一寸光阴一寸金',
[r'/home/jbxue/附件1.txt'],
'smtp.163.com', 'user', 'pass')