[英]Sending email with docx attachment using Python 3.x
我正在使用 python 和 Gmail (在 Gmail 上的已发送文件夹中显示它)发送 email 到我的 Yahoo Z0C83F57C7873A07B4A3 附件的地址。
一切似乎都正常,除了当它到达 Gmail 时,它的附件文件名带有__io.BufferedReader name='myfile.docx'_
原始消息到达目的地雅虎显示:
Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename= <_io.BufferedReader name='myfile.docx'>
如何修复它,使文件名没有<_io.BufferedReader...
等? 我猜它正在修复 header? 另外,为什么content-transfer-encoding:base64
在 header 中重复?
subject = "this is the subject line"
message = MIMEMultipart()
message["Subject"] = subject
message["From"] = sender_email
message["To"] = receiver_email
body = 'This is the body of the email'
message.attach(MIMEText(body))
attach_file = open("myfile.docx", 'rb') # Open the file as binary mode
payload = MIMEApplication(attach_file.read(),
'vnd.openxmlformats-officedocument.wordprocessingml.document')
encoders.encode_base64(payload)
payload.add_header('Content-Disposition',
"attachment; filename= %s" % attach_file)
message.attach(payload)
#for SSL 465 port - wont work yet on gmx but works on gmail
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port,context=context) as server:
try:
# server.ehlo() this is for not needed for gmail but is for gmx TLS
# server.starttls() this is not needed for gmail SSL but is for gmx TLS
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())
self.statusBar().showMessage('Email Sent.')
server.quit()
except smtplib.SMTPAuthenticationError:
self.statusBar().showMessage('Email Not Sent. Authentication Failure.')
server.quit()
except Exception as e: # pylint: disable=broad-except
self.statusBar().showMessage(f"SMTP exception {e}")
server.quit()
好的,我自己修好了,又一次。 太简单了,可惜我错过了。 无论如何,如果您在将 NO NAME 作为附件(或 __io.BufferedReader name='myfile.docx'_)时遇到问题,则在添加时只需将 add.name 添加到附件文件名的末尾header。 并不是说我可以在这里看到很多带有该参考的示例。 最新版本也不需要专门调用编码器,否则您将在原始 header 中获得双重“编码”。
# encoders.encode_base64(payload)
# already encoded, so didn't need this line above
payload.add_header('Content-Disposition',
'attachment',filename='%s' % attach_file.name)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.