通过python发送邮件编码出错

使用QQ邮箱往另一个QQ邮箱发送带有附件的邮件时显示如下

代码如下

# 发送设置
host_server = 'smtp.qq.com'         #主机地址
sender = '11111@qq.com'        #发件人邮箱
code = 'abcdefg'           #授权码
user = '22222@qq.com'           #收件人邮箱
# 邮件信息
mail_title = '平均就业薪资'           #标题
mail_content = '1月份平均就业薪资,具体请查看附件'  #内容
# 构建附件
attachment = MIMEApplication(open('文件/AvgSalary.xlsx','rb').read())
attachment.add_header('Content-Disposition','attachment',filename='data.xlsx')
# SMTP
smtp = smtplib.SMTP(host_server)
smtp.login(sender,code)             #登录
msg = MIMEMultipart()               #带附件的实例
msg['Subject'] = mail_title
msg['From'] = sender
msg['To'] = user
msg.attach(MIMEText(mail_content))
msg.attach(attachment)
smtp.sendmail(sender,user,msg.as_string())

恳求各位大佬帮忙解决!谢谢!抱拳了老铁们~ 

 

报错是因为附件的格式问题,只要在第10行调整一下就好了

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# 发送设置
host_server = 'smtp.qq.com'  # 主机地址
sender = '11111@qq.com'  # 发件人邮箱
code = 'abcdefg'  # 授权码
user = '22222@qq.com'  # 收件人邮箱
# 邮件信息
mail_title = '平均就业薪资'  # 标题
mail_content = '1月份平均就业薪资,具体请查看附件'  # 内容
# 构建附件
attachment = MIMEText(open('文件/AvgSalary.xlsx', 'rb').read(), 'base64', 'utf-8')    # 这里加上'base64', 'utf-8'参数就好
attachment.add_header('Content-Disposition', 'attachment', filename='data.xlsx')
# SMTP
smtp = smtplib.SMTP(host_server)
smtp.login(sender, code)  # 登录
msg = MIMEMultipart()  # 带附件的实例
msg['Subject'] = mail_title
 msg['From'] = sender
msg['To'] = user
msg.attach(MIMEText(mail_content))
msg.attach(attachment)
smtp.sendmail(sender, user, msg.as_string())