Send email to exchange with attachment in russian file name

Question:

I’m using python 2.7.3. and I have following code for send emails with attached file.

# 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)

My problem is that exchange users who receive emails through this code can’t see attachment file name if it has russian letters (for example пример.txt), otherwise if it has english letters everything works fine for them.
I faced with this problem only with customers who use exchange (gmail works fine).
What i’m doing wrong? where should I change encoding?

Asked By: Savva Sergey

||

Answers:

I found the solution finally. I just set encoding for header.

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)
Answered By: Savva Sergey

Came here with the same problem and Savva Sergey’s own solution didn’t work for me.
Encoding with os.path.basename(email_attach1).encode('utf-8') was useless too.
And I’m positive that’s happened because of python’s version. Mine is 3.8 and while I’m doing almost the same, here it is what’s works:

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))
Answered By: blakman

Thanks! The last answer (2021) works! (Python 3.11)

Answered By: Yuri