发送表格作为电子邮件正文(不附件)在Python [英] Send table as an email body (not attachment ) in Python

查看:445
本文介绍了发送表格作为电子邮件正文(不附件)在Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的输入文件是一个CSV文件,通过运行一些由python Tabulate模块组成的python脚本,我创建了一个如下所示的表: -

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:-

tabulate_output

|    Attenuation |   Avg Ping RTT in ms |   TCP UP |
|---------------:|---------------------:|---------:|
|             60 |                2.31  | 106.143  |
|             70 |                2.315 | 103.624  |

我想将此表格发送到电子邮件正文中,不是作为 附件使用python。

I would like to send the this table in the email body and not as an attachment using python.

我已经创建了一个sendMail函数,并期望在mail_body中发送表。
sendMail([to_addr],from_addr,mail_subject,mail_body,[file_name])

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])

推荐答案

此代码以典型的纯文本加上html多部分/替代格式发送消息。如果你的记者在一个html感觉的邮件阅读器中读取这个,他将看到HTML表。如果他读纯文本阅读器,他会看到纯文本版本。

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.

在这两种情况下,他将看到消息正文中包含的数据,而不是附件。

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 = 'xxx@gmail.com'
password = 'yyyzzz!!2'
server = 'smtp.gmail.com:587'
you = 'qqq@gmail.com'

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()

这篇关于发送表格作为电子邮件正文(不附件)在Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆