如何在使用 Python 的 smtplib 发送的电子邮件中获得换行符? [英] How to get line breaks in e-mail sent using Python's smtplib?
问题描述
我编写了一个脚本,可将消息写入文本文件并将其作为电子邮件发送.一切都很顺利,除了电子邮件最终似乎都在一行中.
I have written a script that writes a message to a text file and also sends it as an email. Everything goes well, except the email finally appears to be all in one line.
我通过
添加换行符,它适用于文本文件,但不适用于电子邮件.您知道可能的原因是什么吗?
I add line breaks by
and it works for the text file but not for the email.
Do you know what could be the possible reason?
这是我的代码:
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 + "
" + body)
session.quit()
return send_it
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
sender = 'sender_id@gmail.com'
recipient = 'recipient_id@yahoo.com'
subject = 'report'
body = "Dear Student,
Please send your report
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 = "
".join(headers)
send_error(sender, recipient, headers, body)
推荐答案
您已声明您的消息正文包含 HTML 内容 ("Content-Type: text/html"
).换行符的 HTML 代码是
.您应该将内容类型更改为 text/plain
或使用 HTML 标记作为换行符而不是纯
,因为后者在呈现 HTML 文档时会被忽略.
You have your message body declared to have HTML content ("Content-Type: text/html"
). The HTML code for line break is <br>
. You should either change your content type to text/plain
or use the HTML markup for line breaks instead of plain
as the latter gets ignored when rendering a HTML document.
作为旁注,还可以查看电子邮件包.有一些类可以为您简化电子邮件消息的定义(带有示例).
As a side note, also have a look at the email package. There are some classes that can simplify the definition of E-Mail messages for you (with examples).
例如您可以尝试(未经测试):
For example you could try (untested):
import smtplib
from email.mime.text import MIMEText
# define content
recipients = ["recipient_id@yahoo.com"]
sender = "sender_id@gmail.com"
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()
这篇关于如何在使用 Python 的 smtplib 发送的电子邮件中获得换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!