`
marlonyao
  • 浏览: 248880 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Python发邮件

阅读更多

下面的代码的作用是将电子书作为附件发送到163邮箱。

 

#!/usr/bin/env python
# -*- coding: utf8 -*-

import smtplib,email,os,sys
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email import Encoders
from email.header import Header


def send_file(file):
	base_name = os.path.basename(file) # windows下使用 decode('gbk').encode('utf8')

	msg=MIMEMultipart()

	msg['From'] = from_email
	msg['To'] = to_email
	msg['Subject'] = Header('===book===' + base_name, 'utf8')
	msg['Reply-To'] = from_email

	body=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 files
	input_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: " + file
		send_file(file)
		print "OK sending file: " + file

 

代码很简单,网上很容易找到,比较tricky的地方是如何处理中文字符,容易出现乱码,主要原因在于python下的字符串实际上字节序列,不是字符序列,Python3.0下已经是字符串已经改为字符序列了,我这里使用的还是Python2.6。可能出现乱码的地方有标题, 正文内容,以及附件文件名称。正文内容可以在MIMEText构造函数中传递_charset参数,标题和附件名称通过Header类来设置正确的编码。需要注意的是,传递进去的字符串(实际上是字节序列)和指定的编码必须匹配,否则肯定也是乱码。

 

 

分享到:
评论
1 楼 高攀sky 2016-02-22  
     

相关推荐

Global site tag (gtag.js) - Google Analytics