处理传出emai的UTF8的正确方法

2024-04-26 05:56:16 发布

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

有谁能解释一下用UTF-8表格发送这封邮件的正确方式吗?目标接收为人类无法读取的代码。在

Edit1:添加了更多有关代码的详细信息,该代码显示上载的_file变量来自何处。 编辑2:添加了代码的最后一部分

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def upload(upload_file):
ftp = ftplib.FTP('ftp.domain.com')
ftp.login("user","pass")
f = open(upload_file,'rb')
ftp_server_response = ftp.storbinary('STOR %s' %upload_file, f)
ftp_server_response_msg = ftp_server_response.split("/", 5)[4]
f.close()
ftp.quit()
os.remove(upload_file)
uploaded_filename = os.path.basename(upload_file)
html = """\
<iframe src="https://example.com/embed/{file_id}/{uploaded_file}" scrolling="no" frameborder="0" width="700" height="430" allowfullscreen="true" webkitallowfullscreen="true" mozallowfullscreen="true"></iframe>
""".format(file_id=ftp_server_response_msg, uploaded_file=uploaded_filename)
From = 'email@domain.com'
Recipient  = 'email@domain.com'

# Credentials
username = 'user01@domain.com'
password = 'password'
server = smtplib.SMTP('smtp.domain.com:587')

email_msg = MIMEMultipart('alternative')
email_msg['Subject'] = os.path.basename(upload_file).rsplit(".", 1)[0]
email_msg['From'] = From
email_msg['To'] = Recipient
email_msg_part1 = MIMEText(html, 'html')
email_msg.attach(email_msg_part1)

server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(From, Recipient, email_msg.as_string())
server.quit()

if __name__ == "__main__":
pool = Pool(9)
tasks = []
for root, dirs, filenames in os.walk("/ext_hdd/download"):
    dirs[:] = [d for d in dirs if d not in exclude]
    for extension in file_extensions:
        for filename in fnmatch.filter(filenames, extension):
            match = os.path.join(root, filename)
            file_size = os.path.getsize(match)
            if file_size > 209715200:

                    tasks.append(pool.apply_async(upload, args=(match,)))
            else:
                    pass

for task in tasks:
    print task
    task.get()
pool.close()
pool.join()

Tags: 代码incomforserverosemailresponse
1条回答
网友
1楼 · 发布于 2024-04-26 05:56:16

快速回答可能是因为您没有在MIMEText上指定编码,而且subject头也没有定义为UTF-8。假设所有字符串都是UTF-8编码的,则应使用:

email_msg_part1 = MIMEText(html, 'html', "utf-8")
email_msg['Subject'] = Header(os.path.basename(upload_file).rsplit(".", 1)[0], "utf-8")

但是,如果这不起作用,那么您应该集中精力于upload_file的源代码。在

我假设upload_file来自一个文件列表。在Linux上,文件名不会像在Windows上那样以中性方式编码,也不会在OS X上强制执行。这意味着您可以创建一个文件名为UTF-8编码的文件,对于正在读取文件名为ISO-8859-15的程序来说,该文件名看起来已损坏。在

/ext_hdd/download中的文件可能没有UTF-8文件名。然后,您将传递这个非UTF-8编码字符串,以便在应该使用UTF-8编码字符串的地方使用。在

要解决这个问题,您应该尽可能使用Unicode字符串,并让mime库按自己的意愿进行编码。要获得Unicode字符串,您需要对编码字符串(如文件名)进行解码。一种简单的方法是将Unicode字符串作为目录名传递给os.walk()

^{pr2}$

这将在可能的情况下使用Python的语言环境来解码文件名。如果无法解码,它将返回已编码的文件名。然后需要对字符串强制编码。假设编码实际上是Windows-1252。将此添加到os.walk()代码中:

if isinstance(filname, str):
    filename = filename.decode("windows-1252")

然后,当您调用时,将消息部分设置为顶部给定的部分。在

相关问题 更多 >