2013-01-03 25 views
15

私は、メッセージをテキストファイルに書き込むスクリプトを作成し、それを電子メールとして送信しました。 電子メールが最終的にすべて1行に表示されることを除いて、すべてがうまくいっています。Pythonのsmtplibを使って電子メールの改行を取得する方法は?

私は\nで改行を追加し、テキストファイルでは動作しますが、電子メールでは動作しません。 考えられる理由は何か分かりますか?


はここに私のコードです:私たちのすべてのため残念ながら

import smtplib, sys 
import traceback 
def send_error(sender, recipient, headers, body): 

    SMTP_SERVER = 'smtp.gmail.com' 
    SMTP_PORT = 587 
    session = smtplib.SMTP('smtp.gmail.com', 587) 
    session.ehlo() 
    session.starttls() 
    session.ehlo 
    session.login(sender, 'my password') 
    send_it = session.sendmail(sender, recipient, headers + "\r\n\r\n" + body) 
    session.quit() 
    return send_it 


SMTP_SERVER = 'smtp.gmail.com' 
SMTP_PORT = 587 
sender = '[email protected]' 
recipient = '[email protected]' 
subject = 'report' 
body = "Dear Student, \n Please send your report\n Thank you for your attention" 
open('student.txt', 'w').write(body) 

headers = ["From: " + sender, 
       "Subject: " + subject, 
       "To: " + recipient, 
       "MIME-Version: 1.0", 
       "Content-Type: text/html"] 
headers = "\r\n".join(headers) 
send_error(sender, recipient, headers, body) 

答えて

12

あなたのメッセージ本文がHTMLコンテンツ("Content-Type: text/html")を持つように宣言があります。改行のHTMLコードは<br>です。コンテンツタイプをtext/plainに変更するか、HTML文書をレンダリングするときに後者が無視されるため、平方の代わりに改行にHTMLマークアップを使用するか、\nを使用する必要があります。


さらに、email packageもご覧ください。あなたの電子メールメッセージの定義を簡略化できるクラスがいくつかあります(with examples)。あなたが(未テスト)を試みることができる。例えば

import smtplib 
from email.mime.text import MIMEText 

# define content 
recipients = ["[email protected]"] 
sender = "[email protected]" 
subject = "report reminder" 
body = """ 
Dear Student, 
Please send your report 
Thank you for your attention 
""" 

# make up message 
msg = MIMEText(body) 
msg['Subject'] = subject 
msg['From'] = sender 
msg['To'] = ", ".join(recipients) 

# sending 
session = smtplib.SMTP('smtp.gmail.com', 587) 
session.starttls() 
session.login(sender, 'my password') 
send_it = session.sendmail(sender, recipients, msg.as_string()) 
session.quit() 
21

、ないプログラムまたはアプリケーションのすべてのタイプは、Pythonが行うのと同じ標準を使用しています。あなたの質問を見て

私はあなたのヘッダがあることに注意してください:あなたの新しいライン用のHTML形式のタグを使用する必要があることを意味"Content-Type: text/html"

は、これらは改行と呼ばれています。 <br>

あなたのテキストは次のようになります。

"Dear Student, <br> Please send your report<br> Thank you for your attention" 

あなたではなく、文字型の新しいラインを使用する場合は、あなたが読むためにヘッダーを変更する必要があります。"Content-Type: text/plain"

あなたはまだ新規作成を変更する必要があります単一の\nからダブルの\r\nまでのライン文字で、電子メールで使用されます。

あなたのテキストは次のようになります。

"Dear Student, \r\n Please send your report\r\n Thank you for your attention" 
+0

ありがとうございました。 '\ r \ n'は私のためには機能しませんが、'
'はそれを行います。 –

0

Content-Type: text/plainにContent-Typeヘッダを設定する(末尾の\r\nとは)私は複数行のプレーンテキストの電子メールを送信することができました。

0

Outlookは、改行は、エクストラと思われるプレーンテキストから削除します。 https://support.microsoft.com/en-us/kb/287816

以下のアップデートを試して、行を弾丸のように見せることができます。それは私のために働いた。

body = "Dear Student, \n- Please send your report\n- Thank you for your attention" 
+0

なぜ賛成投票ですか? – edW

関連する問題