下面的代码的作用是将电子书作为附件发送到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类来设置正确的编码。需要注意的是,传递进去的字符串(实际上是字节序列)和指定的编码必须匹配,否则肯定也是乱码。
分享到:
相关推荐
Python发邮件代码
详细展示了各种使用python发邮件的程序实例
python发邮件程序,发送方法:./mail.py 收件人 主题 html内容 图片文件 附件文件'
python发邮件
发邮件代码,Python,亲测可用。用pycharm写,直接更改发件人邮箱、密码,和收件人邮箱即可
python发邮件示例
Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件
使用python3发送QQ电子邮件,发送人为自己,接收人可以一个可以多个。
Python- python发邮件
python发送邮件,通过qq邮箱代理,具体怎么设置请百度(获取qq邮箱授权码),可以发送邮件到邮箱,非常简洁的代码
SVN变化发送邮件(Python实现) 实现了svn一但有变化将发送邮件
python email模块发送office附件. 本文编写了python 邮件发附件方法。代码解释。
基于Python的邮件分类系统 开题报告
python爬虫发邮件示例demo,亲自在本地跑过的,都能正常运行,有问题可以私聊我,算是python入门学习吧
简单的python发送邮件的示例,基于python2.7
本文实例为大家分享了python实现邮件自动发送的具体代码,供大家参考,具体内容如下 case 1:纯文本和HTML文件发送 # -*- coding: UTF-8 -*- import smtplib import traceback from email.mime.text import ...
py代码-python发邮件