1

私は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) を含む場合、添付ファイル名を表示できないことです。この問題に直面したのは、exchange を使用しているお客様だけです (gmail は正常に動作します)。私が間違っているのは何ですか?どこでエンコーディングを変更すればよいですか?

4

2 に答える 2

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)
于 2012-12-03T11:36:00.980 に答える