发送电子邮件与俄语文件名中的附件交换

时间:2012-11-30 13:26:34

标签: python encoding exchange-server attachment smtplib

我正在使用python 2.7.3。我有以下代码用于发送带附件的电子邮件。

# coding: cp1251
import os
import smtplib

from email import Encoders
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
from email.Utils import formatdate

def sendEmail(to_address, mail_settings, attachment_file_path, subject = 'my_subject'):

HOST = mail_settings['host']
port = mail_settings['port']
username = mail_settings['login']
password = mail_settings['pass']

msg = MIMEMultipart()
msg["From"] = mail_settings['from_address']
msg["To"] = ','.join(to_address)
msg["Subject"] = subject.decode('cp1251')
msg['Date'] = formatdate(localtime=True)
msg['Content-Type'] = "text/html; charset=cp1251"

# attach a file
part = MIMEBase('application', "octet-stream")
part.set_payload( open(attachment_file_path,"rb").read() )
Encoders.encode_base64(part)    
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attachment_file_path))
msg.attach(part)

server = smtplib.SMTP(host=HOST, port=port)           

try:
    failed = server.sendmail(mail_settings['from_address'], to_address, msg.as_string())        
    print('sent')
    server.close()
except Exception, e:
    errorMsg = "Unable to send email. Error: %s" % str(e)
    print(errorMsg)

我的问题是,通过此代码接收电子邮件的交换用户如果有俄语字母(例如пример.txt)则看不到附件文件名,否则如果它有英文字母,一切正常。 我只面对使用交换的客户(gmail工作正常)才遇到这个问题。 我做错了什么?我应该在哪里更改编码?

2 个答案:

答案 0 :(得分:3)

我终于找到了解决方案。我只为头文件设置了编码。

mail_coding = 'utf-8'
att_header = Header(os.path.basename(attachment_file_path), mail_coding);
part.add_header('Content-Disposition', 'attachment; filename="%s"' % att_header)

答案 1 :(得分:0)

带着同样的问题来到这里,Savva Sergey 自己的解决方案对我不起作用。 用 os.path.basename(email_attach1).encode('utf-8') 编码也无用。 我很肯定这是因为 python 的版本。我的是 3.8,虽然我做的几乎一样,但这是有效的:

import os
from email.mime.application import MIMEApplication
email_attach1 = './path/to/文件.pdf'
part = MIMEApplication(
        open(email_attach1,"rb").read(),
        Name=os.path.basename(email_attach1),_subtype="pdf"
  )
part.add_header('Content-Disposition',
         'attachment',filename=os.path.basename(email_attach1))