python复制excel内容和格式_通过Python发送电子邮件 - 将excel / csv的内容作为格式化表粘贴到邮件正文上...

I am trying to send mails via Python using smtplib. My main concern is to get the contents of a csv/excel and paste the data as it is(tabular format) onto the mail body of the email being sent out. I have the following snippet ready to search for the file and print the contents on the shell. How would I get the same output onto a mail body?

from os import listdir

import csv

import os

#Search for a csv in the specified folder

directory = "folder_path"

def find_csv_filenames( path_to_dir, suffix="Data.csv" ):

filenames = listdir(path_to_dir)

return [ filename for filename in filenames if filename.endswith( suffix ) ]

filenames = find_csv_filenames(directory)

for name in filenames:

datafile=name

print(name)

path=directory+'//'+datafile

#Read the selected csv

with open(path,'r') as csvfile:

spamreader=csv.reader(csvfile,delimiter=' ',quotechar='|')

for row in spamreader:

print(', '.join(row))

TIA for your help.

解决方案

Create a StringIO instance, say csvText and instead of print use

csvText.write(", ".join(row)+"\n")

The final newline is necessary, because it is not automatically added as by print. Finally (i.e. after the loop) calling csvText.getvalue() will return what you want to mail.

I would also suggest not to glue file specification together by yourself but call os.path.join() instead.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值