[英]How to combine .decode('utf-8') and .format() in Python?
我正在嘗試使用Python發送一封電子郵件,該電子郵件都將使用UTF-8
編碼,並且將采用格式設置(因此,每個客戶端都會收到他的名字等)。
這是我負責發送電子郵件的功能,經過簡化:
def sendMail(recipient, recipientName):
file = open('~/mail.txt'.format(name), 'r')
data = file.read()
msg = MIMEText(data.decode('utf-8'), 'html', 'utf-8') # <<<<
file.close()
mail = smtplib.SMTP_SSL(ip, port)
mail.login(mailUser, mailPassword)
mail.sendmail(mailHost, recipient, msg.as_string().format(recipientName)) # <<<<
mail.quit()
這就是mail.txt文件的內容 。
基本上,這里相關的是功能的3rd
行和7th
行-其余與郵件發送有關,並且工作正常。 如果我不使用.decode('utf-8')
,則格式設置很好-但是反過來,電子郵件幾乎無法讀取。
我也嘗試了%
參數和f
參數,但都沒有成功-基本上只有.format
除了無法正常工作外,它不會產生任何錯誤。
將.format()
應用於msg.as_string()
似乎非常脆弱。 此時, msg
應該包含正確的MIME編碼的消息,該消息可能根本不再包含您的格式字符串(例如,如果內容需要base64編碼,則看起來根本不會像您的輸入一樣)。 在此過程的較早階段應用格式。
def sendMail(recipient, recipientName):
with open('~/mail{0}.txt'.format(name), 'r', encoding='utf-8') as file:
data = file.read()
msg = MIMEText(data.format(recipientName), 'html', 'utf-8')
mail = smtplib.SMTP_SSL(ip, port)
mail.login(mailUser, mailPassword)
mail.sendmail(mailHost, recipient, msg.as_string())
mail.quit()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.