2013-04-18 16 views
5

私はMIMETextを使ってPython 3.2でメールを作成していますが、非ASCII文字のメッセージを作成するのに問題があります。例えばMIMETextのヘッダーの符号化

from email.mime.text import MIMEText 
body = "Some text" 
subject = "» My Subject"     # first char is non-ascii 
msg = MIMEText(body,'plain','utf-8') 
msg['Subject'] = subject     # <<< Problem probably here 
text = msg.as_string() 

最後の行は

UnicodeEncodeError: 'ascii' codec can't encode character '\xbb' in position 0: ordinal not in range(128) 

私にエラーを与えるにはどうすれば対象はASCIIではないことを教えてくれます:MIMETextをしますか? subject.encode('utf-8')はまったく役に立ちません。とにかく、他の回答に問題のないユニコード文字列を使用している人がいます(Python - How to send utf-8 e-mail?を参照)。 Python 2.7でのエラー(結果が正しいことを意味するとは限りません)。

答えて

9

解決策が見つかりました。 非ASCII文字を含む電子メールヘッダーは、RFC 2047としてエンコードする必要があります。 Pythonでは、ヘッダコンテンツ (http://docs.python.org/2/library/email.header.htmlを参照)の通常の文字列の代わりにemail.header.Headerを使用します。 上記の例を書くための正しい方法は、その後

from email.mime.text import MIMEText 
from email.header import Header 
body = "Some text" 
subject = "» My Subject"     
msg = MIMEText(body,'plain','utf-8') 
msg['Subject'] = Header(subject,'utf-8') 
text = msg.as_string() 

対象文字列が

=?utf-8?q?=C2=BB_My_Subject?= 

事実として電子メールでエンコードされているPythonの2.xの中で前のコードは私のために働いていましたおそらく、誤ってエンコードされたヘッダーを解釈できるメールクライアントに関係しています。

0
  Esta funsion manda un email a un solo correo si alguien quiere la funsión que   mande a varios email tambien la tengo. 
     text = ('Text') 
     mensaje = MIMEText(text,'plain','utf-8') 
     mensaje['From']=(remitente) 
     mensaje['Subject']=('Asunto') 
     mailServer = smtplib.SMTP('xxx.xxx.mx') 
     mailServer.ehlo() 
     mailServer.starttls() 
     mailServer.ehlo() 

     mailServer.sendmail(remitente,destinatario, mensaje.as_string()) 
          mailServer.close() 
+1

お手数ですが、スタックオーバーフローで英語が必要です。この回答を英語に翻訳してください。 – mhlester