python发送表格邮件,发送表格作为电子邮件正文(不附件)在Python

该博客介绍了一种方法,通过Python脚本将CSV文件中的数据转换为表格,并将其内联插入到电子邮件正文中,而不是作为附件发送。使用了`tabulate`模块和`email`库创建了一个HTML邮件,确保收件人在任何阅读器中都能清晰地查看数据表格。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

| 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 an attachment using 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])

解决方案

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 = """

Hello, Friend.

Here is your data:

{table}

Regards,

Me

"""

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值