2 つの異なる .txt ファイルからテキストを読み取り、それらを連結しています。次に、 を使用して、それをメールの本文に追加しwebbrowser
ます。
1 つのテキスト ファイルは英字 (ascii) で、もう 1 つは日本語 (UTF-8) です。テキストファイルに書き込むと、テキストは正常に表示されます。しかしwebbrowser
、テキストをメール本文に挿入すると、日本語のテキストが疑問符として表示されます。
デフォルトとして異なるメールクライアントを持つ複数のマシンでスクリプトを実行しようとしました。最初はそれが問題かと思いましたが、そうではないようです。Thunderbird と Mail (MacOSX) には疑問符が表示されます。
Hello. Today is 2014-05-09
????????????????2014-05-09????
SOで同様の問題を見てきましたが、問題は解決していません。
- UnicodeEncodeError: 'ascii' コーデックは位置 20 の文字 u'\xa0' をエンコードできません: 序数が範囲内にありません(128)
- Python 関数内の日本語
- 日本語(中国語)の文字を印刷する
- python utf-8 日本語
webbrowser
Pythonで作成したメールの本文に日本語(UTF-8)を表示させる方法はありますか? この機能を使用することもできますemail
が、要件は、スクリプトが既定のメール クライアントを開いてすべての情報を挿入する必要があることです。
私が使用しているコードとテキスト ファイルは以下のとおりです。問題に焦点を当てるために単純化しました。
メールテンプレート.txt
Hello. Today is {{date}}
メールテンプレート-jp.txt
こんにちは。今日は {{date}} です。
Python スクリプト
#
# -*- coding: utf-8 -*-
#
import sys
import re
import os
import glob
import webbrowser
import codecs,sys
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
# vars
date_range = sys.argv[1:][0]
email_template_en = "email-template.txt"
email_template_jp = "email-template-jp.txt"
email_to_send = "email-to-send.txt" # finished email is saved here
# Default values for the composed email that will be opened
mail_list = "test@test.com"
cc_list = "test1@test.com, test2@test.com"
subject = "Email Subject"
# Open email templates and insert the date from the parameters sent in
try:
f_en = open(email_template_en, "r")
f_jp = codecs.open(email_template_jp, "r", "UTF-8")
try:
email_content_en = f_en.read()
email_content_jp = f_jp.read()
email_en = re.sub(r'{{date}}', date_range, email_content_en)
email_jp = re.sub(r'{{date}}', date_range, email_content_jp).encode("UTF-8")
# this throws an error
# UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 26: ordinal not in range(128)
# email_en_jp = (email_en + email_jp).encode("UTF-8")
email_en_jp = (email_en + email_jp)
finally:
f_en.close()
f_jp.close()
pass
except Exception, e:
raise e
# Open the default mail client and fill in all the information
try:
f = open(email_to_send, "w")
try:
f.write(email_en_jp)
# Does not send Japanese text to the mail client. But will write to the .txt file fine. Unsure why.
webbrowser.open("mailto:%s?subject=%s&cc=%s&body=%s" %(mail_list, subject, cc_list, email_en_jp), new=1) # open mail client with prefilled info
finally:
f.close()
pass
except Exception, e:
raise e
編集:追加するのを忘れました私はPython 2.7.1を使用しています