Skip to content

Instantly share code, notes, and snippets.

Created November 17, 2015 06:49
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/f734d4a12f18c7ac0886 to your computer and use it in GitHub Desktop.
Save anonymous/f734d4a12f18c7ac0886 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import parseaddr, formataddr
import smtplib
import os
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr(( \
Header(name, 'utf-8').encode(), \
addr.encode('utf-8') if isinstance(addr, unicode) else addr))
def main():
from_addr = 'your@qq.com'
to_addr = 'her@qq.com'
password = 'xxxxxx'
smtp_server = 'smtp.qq.com'
base_dir = os.path.dirname(__file__)
attach_dir = unicode(os.path.join(base_dir, 'attachment_file\\'),'mbcs')
server = smtplib.SMTP(smtp_server, 25)
server.login(from_addr, password)
msg = MIMEMultipart()
msg.set_charset('utf8')
msg.attach(MIMEText(u'邮件正文','plain','utf-8'))
msg['From'] = _format_addr(u'发件人名 <%s>' % from_addr) # 发件人地址
attach_file = u'报表.xlsx'
attach_filedir = os.path.join(attach_dir, attach_file)
attach_file = attach_file.encode('gbk','ignore')
msg['To'] = _format_addr(u'收件人 <%s>' % to_addr) # 收件人地址
msg['Subject'] = Header(u'报表.xlsx', 'utf-8').encode() # 邮件主题=附件文件名
mime = MIMEText(open(attach_filedir, 'rb').read(),'base64','utf-8')
mime.add_header('Content-Disposition', 'attachment', filename = attach_file)
mime.add_header('Content-Type', 'application/octet-stream')
msg.attach(mime)
server.sendmail(from_addr, to_addr, msg.as_string())
if __name__ == '__main__':
main()
@tony21248772
Copy link

python3.5 win7, mime.add_header('Content-Disposition', 'attachment', filename = attach_file)
if attach_file= attach_file.encode('gbk', 'ignore'),
Error AttributeError: 'bytes' object has no attribute 'encode'
why????Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment