本帖最后由 We. 于 2020-11-10 15:34 编辑
破案了!
根据6楼老哥@yyaocs的温馨提示找到问题出在哪里了。
[Python] 纯文本查看 复制代码 message['To'] = Header(to_receiver)
message['Cc'] = Header(cc_receiver)
把收件人和抄送人用Header方法封装一下就不会被挡了!
真是开心。
再补充一下:
如果你想抄送很多人,上面那个解决方案还是不行!以下是解决代码:
[Python] 纯文本查看 复制代码 message['To'] = Header(';'.join(to_receiver), 'utf-8')
message['Cc'] = Header(';'.join(cc_receiver), 'utf-8')
完美解决!
=======================如图
代码跑完了没有异常也没有报错。
发送的邮箱部分成功,163的邮箱成功了,inspur和qq的没有。
主要是想发送带附件压缩包的邮件(普通邮件可以成功),这不报错就蛋疼了。
请各位指正!
[Python] 纯文本查看 复制代码 import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from email.header import Header
email_host = 'smtp.163.com'
email_user = 'xxx'
email_pass = 'xxx'
sender = 'xxx'
to_receiver = ['xxx@qq.com'] # 收件人
cc_receiver = ['xxx@163.com','xxx@inspur.com'] # 抄送
receivers = to_receiver + cc_receiver
content = 'python自动发送的带压缩包的电子邮件。'
title = 'python发送邮件测试'
def sendEmail():
message = MIMEMultipart()
message['From'] = sender
message['To'] = ';'.join(to_receiver)
message['Cc'] = ';'.join(cc_receiver)
message['Subject'] = Header(title)
message.attach(MIMEText(content, 'plain', 'utf-8'))
with open('附件.rar', 'rb') as f:
mine = MIMEBase('rar', 'rar', filename='附件.rar')
mine.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', '附件.rar'))
mine.add_header('Content-ID', '<0>')
mine.add_header('X-Attachment-Id', '0')
mine.set_payload(f.read())
encoders.encode_base64(mine)
message.attach(mine)
try:
smtpObj = smtplib.SMTP_SSL(email_host, 465)
smtpObj.login(email_user, email_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
print('邮件发送成功')
smtpObj.quit()
except smtplib.SMTPException as e :
print(e)
sendEmail()
|