使用python emai以nonascii文件名发送附件

2024-10-01 09:32:58 发布

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

我怎样才能发送一封附加了文件名包含unicode字符的电子邮件?在

到目前为止,文件将到达,但文件名为“noname”。在

这一部分对于ASCII文件名非常有效:

import smtplib
from email.mime.text import MIMEText
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.Utils import formatdate
from email import Encoders
from email.Utils import encode_rfc2231

msg = MIMEMultipart()
msg['Subject'] = "New magazine delivery!"
msg['From'] = sender_email
msg['To'] = ', '.join(kindle_emails)
msg['Date'] = formatdate(localtime=True)
message = "see attachment"
msg.attach(MIMEText(message))
part = MIMEApplication(open(f, 'rb').read(), _subtype='application/x-mobipocket-ebook')

part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(filename)
msg.attach(part)

添加一个包含编码、语言和编码字符串的元组,而不仅仅是文件名。在

^{pr2}$

第二次尝试:

按如下方式全局设置字符集:

from email import Charset
Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')

第三次尝试

使用utils.encode_rfc2231

from email.Utils import encode_rfc2231
utf8filename = encode_rfc2231(os.path.basename(f).encode('utf-8'), charset='utf-8')
part.add_header('Content-Disposition', 'attachment', filename=('utf-8', 'fr', utf8filename))

第四次尝试

使用urllib.quote()对文件名进行url编码。这与第三种方法对文件名的影响相同。在

utf8filename = urllib.quote(os.path.basename(f).encode('utf-8'))
part.add_header('Content-Disposition', 'attachment', filename=('utf-8', 'fr', utf8filename))

有什么想法吗?在

我是否遗漏了RFC2231文件名字符编码的一些重要内容?在

我使用Gmail的SMTP服务器和Python2.7。在


Tags: fromimportadd编码attachment文件名emailmsg
1条回答
网友
1楼 · 发布于 2024-10-01 09:32:58

与其这样告诉服务器它是UTF-8:

filename=('utf-8', 'fr', os.path.basename(f).encode('utf-8')))

…当我不告诉我就发送UTF-8时,它就起作用了:

^{pr2}$

文件名将正确显示。在

这似乎与documentation的说法相矛盾:

If the value contains non-ASCII characters, it must be specified as a three tuple in the format (CHARSET, LANGUAGE, VALUE), where CHARSET is a string naming the charset to be used to encode the value, LANGUAGE can usually be set to None or the empty string (see RFC 2231 for other possibilities), and VALUE is the string value containing non-ASCII code points.

这不起作用,但是python 3 documentation添加了:。在

If a three tuple is not passed and the value contains non-ASCII characters, it is automatically encoded in RFC 2231 format using a CHARSET of utf-8 and a LANGUAGE of None.

只有这样才行得通,即使对于Python2.7也是如此,尽管文档中没有提到它。在

相关问题 更多 >