Python电子邮件附件没有解码

2024-09-27 00:20:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个文本字符串而不是外部文件发送电子邮件附件,但附件没有在接收端解码。我使用内置的stringencode函数在base64中对附件进行了编码。我见过许多附加外部文件的示例,但没有看到将字符串作为附件发送的示例。在

为什么附件没有在接收端解码?我是不是对附件编码不当?在

attachment = MIMEText("This is a test".encode('base64', 'strict'))
attachment.add_header('Content-Disposition', 'attachment', 'test.txt')           
msg.attach(attachment)

Tags: 文件函数字符串test文本示例编码附件
2条回答

如果确实需要使用base64,则应显式设置编码:

attachment = MIMEText("This is a test".encode('base64', 'strict'))
attachment.add_header('Content-Disposition', 'attachment', filename='test.txt')           
attachment.replace_header('content-transfer-encoding', 'base64')
msg.attach(attachment)

如果您不需要base64,只需让库为您决定:

^{pr2}$

或者,使用email.encoders.encode_base64

attachment = MIMEText("This is a test")
email.encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment', filename='test.txt')           
msg.attach(attachment)

您可以参考http://docs.python.org/2/library/email.mime.html?highlight=mimetext#email.mime.text.MIMEText并使用

email.mime.text.MIMEText(_text[, _subtype[, _charset]])

使用_subtype默认的plain和字符集显式地声明您的编码。在

相关问题 更多 >

    热门问题