2012-04-24 7 views
12

私は簡単なsmtp送信者と認証を書いています。ここに私のコードですPython 2.7でsmtplibを使用して電子メールに文字セットを設定する方法は?

SMTPserver, sender, destination = 'smtp.googlemail.com', '[email protected]', ['[email protected]'] 
    USERNAME, PASSWORD = "user", "password" 

    # typical values for text_subtype are plain, html, xml 
    text_subtype = 'plain' 


    content=""" 
    Hello, world! 
    """ 

    subject="Message Subject" 

    from smtplib import SMTP_SSL as SMTP  # this invokes the secure SMTP protocol (port 465, uses SSL) 
    # from smtplib import SMTP     # use this for standard SMTP protocol (port 25, no encryption) 
    from email.MIMEText import MIMEText 

    try: 
     msg = MIMEText(content, text_subtype) 
     msg['Subject']=  subject 
     msg['From'] = sender # some SMTP servers will do this automatically, not all 

     conn = SMTP(SMTPserver) 
     conn.set_debuglevel(False) 
     conn.login(USERNAME, PASSWORD) 
     try: 
      conn.sendmail(sender, destination, msg.as_string()) 
     finally: 
      conn.close() 

    except Exception, exc: 
     sys.exit("mail failed; %s" % str(exc)) # give a error message 

私は非アスキーシンボル(ロシア語キリル文字)を送信しようとするまで、完璧に動作します。メッセージに文字セットを定義して適切な方法で表示するにはどうすればよいですか?前もって感謝します!

UPD。 、だから私はtext_subtype = 'テキスト' とspectify、その後、ヘッダに、私はMSG [ 'Content-Typeの'] =「text/htmlのを置く初めて

text_subtype = 'text' 
content="<p>Текст письма</p>" 
msg = MIMEText(content, text_subtype) 
msg['From']=sender # some SMTP servers will do this automatically, not all 
msg['MIME-Version']="1.0" 
msg['Subject']="=?UTF-8?Q?Тема письма?=" 
msg['Content-Type'] = "text/html; charset=utf-8" 
msg['Content-Transfer-Encoding'] = "quoted-printable" 
… 
conn.sendmail(sender, destination, str(msg)) 

;のcharset = UTF:私は自分のコードを変更しました-8 "文字列。それが正しいか?最後に、私はあなたがMSG =ます:MIMEText(content.encode( 'UTF-8')、 'プレーン'、 'UTF-8')

答えて

19
from email.header import Header 
from email.mime.multipart import MIMEMultipart 
from email.mime.text import MIMEText 

def contains_non_ascii_characters(str): 
    return not all(ord(c) < 128 for c in str) 

def add_header(message, header_name, header_value): 
    if contains_non_ascii_characters(header_value): 
     h = Header(header_value, 'utf-8') 
     message[header_name] = h 
    else: 
     message[header_name] = header_value  
    return message 

............ 
msg = MIMEMultipart('alternative') 
msg = add_header(msg, 'Subject', subject) 

if contains_non_ascii_characters(html): 
    html_text = MIMEText(html.encode('utf-8'), 'html','utf-8') 
else: 
    html_text = MIMEText(html, 'html')  

if(contains_non_ascii_characters(plain)): 
    plain_text = MIMEText(plain.encode('utf-8'),'plain','utf-8') 
else: 
    plain_text = MIMEText(plain,'plain') 

msg.attach(plain_text) 
msg.attach(html_text) 

これは関係なく、あなたのテキストが非ASCIIが含まれているかどうかのあなたのテキストとヘッダの両方のためにあなたの適切なエンコードを与える必要があります文字かどうか。また、不必要にbase64エンコーディングを自動的に使用しないことを意味します。

+0

こんにちはロルカン! msg( 'From' '=' [email protected] 'のように)を私のmsgに指定する場合は、' To 'と' From 'はどうですか?私もそれをエンコードする必要がありますか? –

1
のようななめらかに書くべき私のメッセージの問題 を解決してきました

UPDATEあなたはこれを追加してみてください、異なる文字セットを送る達成するためのSMTPヘッダーを使用する必要があり

-

msg['Content-Type'] = "text/html; charset=us-ascii"

(あなたの必要性に応じて文字セットを変更します)

+0

私のために働いたのは、メッセージテキストのエンコーディングはまだ間に合いませんが、subjectは適切な方法で表示されます。 – f1nn

+0

私の投稿を更新しました。あなたは新しいものを見てみることもできます – f1nn

関連する問題