|
|
下面的代码的作用是将电子书作为附件发送到163邮箱。
#!/usr/bin/env python# -*- coding: utf8 -*-import smtplib,email,os,sysfrom email.MIMEBase import MIMEBasefrom email.MIMEText import MIMETextfrom email.MIMEMultipart import MIMEMultipartfrom email import Encodersfrom email.header import Headerdef send_file(file):base_name = os.path.basename(file) # windows下使用 decode('gbk').encode('utf8')msg=MIMEMultipart()msg['From'] = from_emailmsg['To'] = to_emailmsg['Subject'] = Header('===book===' + base_name, 'utf8')msg['Reply-To'] = from_emailbody=MIMEText('发送文件: ' + base_name, _subtype='html',_charset='utf8')msg.attach(body)part = MIMEBase('application', "octet-stream")part.set_payload( open(file,"rb").read() )Encoders.encode_base64(part)part.add_header('Content-Disposition', 'attachment; filename="%s"' % str(Header(base_name, 'utf8')))msg.attach(part)s = smtplib.SMTP(smtp_server)s.login(user_name, password)s.sendmail(from_email,to_email,msg.as_string())s.close()if __name__ == '__main__':smtp_server='smtp.163.com'from_email=('xxxxxxx@163.com')to_email ='xxxxxxx@163.com'user_name='xxxxxxx@163.com'password='xxxxxxx'# get input filesinput_files = sys.argv[1:]if len(input_files) == 0:print >> sys.stderr, 'Error, no input specified'exit(1)for file in sys.argv[1:]:print "start sending file: " + filesend_file(file)print "OK sending file: " + file
代码很简单,网上很容易找到,比较tricky的地方是如何处理中文字符,容易出现乱码,主要原因在于python下的字符串实际上字节序列,不是字符序列,Python3.0下已经是字符串已经改为字符序列了,我这里使用的还是Python2.6。可能出现乱码的地方有标题, 正文内容,以及附件文件名称。正文内容可以在MIMEText构造函数中传递_charset参数,标题和附件名称通过Header类来设置正确的编码。需要注意的是,传递进去的字符串(实际上是字节序列)和指定的编码必须匹配,否则肯定也是乱码。
|
|