在 Python 中将表格作为电子邮件正文(不是附件)发送
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38275467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send table as an email body (not attachment ) in Python
提问by Durvesh
My input file is a CSV file and by running some python script which consists of the python Tabulate module, I have created a table that looks like this below:-
我的输入文件是一个 CSV 文件,通过运行一些由 python Tabulate 模块组成的 python 脚本,我创建了一个如下所示的表:-
| Attenuation | Avg Ping RTT in ms | TCP UP |
|---------------:|---------------------:|---------:|
| 60 | 2.31 | 106.143 |
| 70 | 2.315 | 103.624 |
I would like to send the this table in the email body and not as anattachmentusing python.
我想在电子邮件正文中发送此表,而不是使用 python作为附件发送。
I have created a sendMail function and will be expecting to send the table in the mail_body.
sendMail([to_addr], from_addr, mail_subject, mail_body, [file_name])
我已经创建了一个 sendMail 函数,并且希望在 mail_body 中发送表。
sendMail([to_addr], from_addr, mail_subject, mail_body, [file_name])
回答by Rob?
This code sends the message in the typical plain text plus html multipart/alternative format. If your correspondent reads this in an html-aware mail reader, he's see the HTML table. If he reads it plain-text reader, he'll see the plain text version.
此代码以典型的纯文本加 html multipart/alternative 格式发送消息。如果您的通讯员在支持 html 的邮件阅读器中阅读此内容,他将看到 HTML 表格。如果他阅读纯文本阅读器,他将看到纯文本版本。
In either case, he will see the data included in the body of the message, and not as an attachment.
在任何一种情况下,他都会看到消息正文中包含的数据,而不是附件。
import csv
from tabulate import tabulate
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
me = '[email protected]'
password = 'yyyzzz!!2'
server = 'smtp.gmail.com:587'
you = '[email protected]'
text = """
Hello, Friend.
Here is your data:
{table}
Regards,
Me"""
html = """
<html><body><p>Hello, Friend.</p>
<p>Here is your data:</p>
{table}
<p>Regards,</p>
<p>Me</p>
</body></html>
"""
with open('input.csv') as input_file:
reader = csv.reader(input_file)
data = list(reader)
text = text.format(table=tabulate(data, headers="firstrow", tablefmt="grid"))
html = html.format(table=tabulate(data, headers="firstrow", tablefmt="html"))
message = MIMEMultipart(
"alternative", None, [MIMEText(text), MIMEText(html,'html')])
message['Subject'] = "Your data"
message['From'] = me
message['To'] = you
server = smtplib.SMTP(server)
server.ehlo()
server.starttls()
server.login(me, password)
server.sendmail(me, you, message.as_string())
server.quit()