我有以下用 Python 3 编写的电子邮件代码...我想根据接收客户端以 HTML 或纯文本形式发送电子邮件。但是,hotmail 和 gmail(我使用后者发送)都接收零换行符/回车符,使纯文本出现在一行上。我的问题是如何在接收方的纯文本电子邮件中获得换行/回车?Linux 上的 Thunderbird 是我的首选客户端,但我在 Microsoft 的 webmail hotmail 中也注意到了同样的问题。
#!/usr/bin/env python3
# encoding: utf-8
"""
python_3_email_with_attachment.py
Created by Robert Dempsey on 12/6/14; edited by Oliver Ernster.
Copyright (c) 2014 Robert Dempsey. Use at your own peril.
This script works with Python 3.x
"""
import os,sys
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
COMMASPACE = ', '
def send_email(user, pwd, recipient, subject, bodyhtml, bodytext):
sender = user
gmail_password = pwd
recipients = recipient if type(recipient) is list else [recipient]
# Create the enclosing (outer) message
outer = MIMEMultipart('alternative')
outer['Subject'] = subject
outer['To'] = COMMASPACE.join(recipients)
outer['From'] = sender
outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'
# List of attachments
attachments = []
# Add the attachments to the message
for file in attachments:
try:
with open(file, 'rb') as fp:
msg = MIMEBase('application', "octet-stream")
msg.set_payload(fp.read())
encoders.encode_base64(msg)
msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))
outer.attach(msg)
except:
print("Unable to open one of the attachments. Error: ", sys.exc_info()[0])
raise
part1 = MIMEText(bodytext, 'plain', 'utf-8')
part2 = MIMEText(bodyhtml, 'html', 'utf-8')
outer.attach(part1)
outer.attach(part2)
composed = outer.as_string()
# Send the email
try:
with smtplib.SMTP('smtp.gmail.com', 587) as s:
s.ehlo()
s.starttls()
s.ehlo()
s.login(sender, gmail_password)
s.sendmail(sender, recipients, composed)
s.close()
print("Email sent!")
except:
print("Unable to send the email. Error: ", sys.exc_info()[0])
raise
这是测试代码:
def test_example():
some_param = 'test'
another_param = '123456'
yet_another_param = '12345'
complete_html = pre_written_safe_and_working_html
email_text = "Please see :" + '\r\n' \
+ "stuff: " + '\r\n' + some_param + '\r\n' \
+ "more stuff: " + '\r\n' + another_param + '\r\n' \
+ "stuff again: " + '\r\n' + yet_another_param, + '\r\n'
recipients = ['targetemail@gmail.com']
send_email('myaddress@gmail.com', \
'password', \
recipients, \
'Title', \
email_text, \
complete_html)
任何建议都会受到欢迎,因为似乎互联网上的每个人都只使用 HTML 电子邮件。这很好,但我希望能够为我们这些不想使用 HTML 的人回退到纯文本。
谢谢,