通过Python发送电子邮件 - 将excel / csv的内容作为格式化表粘贴到邮件正文上 [英] Emails via Python - Paste contents of excel/csv as a formatted table onto the mail body
问题描述
从os import listdir
import csv
import os
#在指定的文件夹中搜索csv
directory =folder_path
def find_csv_filenames(path_to_dir,suffix =Data.csv):
filenames = listdir(path_to_dir)
return [filename(文件名中的文件名,如果filename.endswith(suffix)]
文件名= find_csv_filenames(目录)
名称文件名:
datafile = name
print(name)
path = directory +'//'+ datafile
#读取所选的csv
打开(路径,'r')为csvfile:
spamreader = csv.reader(csvfile,delimiter ='',quotechar ='|')
为垃圾邮件阅读器中的行:
打印(','.join(row))
TIA为您的帮助。
创建一个 StringIO 实例,说csvText而不是打印使用
csvText.write( ,.join(row)+\\\
)
最后的换行是必要的,因为它不会按照打印自动添加。最后(即循环后)调用csvText.getvalue()将返回你想要的邮件。
我也建议不要自己粘合文件规范,而是调用os.path.join()。
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.
这篇关于通过Python发送电子邮件 - 将excel / csv的内容作为格式化表粘贴到邮件正文上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!