python 读excel 发送邮件

2019年3月21日 0 条评论 1.4k 次阅读 0 人点赞

使用mutt发送邮件,请提前配置好

excel内格式如下:

image.png

Python需使用xlrd模块,默认文件名称为:test.xls,默认工作表名称为:Sheet1

图中邮箱所在列数为E,第五列,python脚本中修改为4

#!/usr/bin/env python
# -*- coding: utf-8 -*-  
#调用mutt 发送邮件,请提前配置好
import os
import xlrd
import sys
data = xlrd.open_workbook('test.xls')
table = data.sheet_by_name(u'Sheet1')
mailNum = 4 #邮箱地址所在excel行数-1

nrows_num = table.nrows
ncols_num = table.ncols
res=[]

for nrows in range(nrows_num):
    for ncols in range(ncols_num):
        
        cell_value = table.cell(nrows,ncols).value
        
        if cell_value=='':
            cell_value='__'
            res.append(cell_value)
        elif isinstance(cell_value,unicode):
                cell_value=cell_value
                res.append(cell_value)
        elif isinstance(cell_value,float):
                cell_value = str(cell_value)
                cell_value = cell_value.decode('utf-8')
                res.append(cell_value)
        elif isinstance(cell_value,int):
                cell_value = str(cell_value)
                cell_value = cell_value.decode('utf-8')
                res.append(cell_value)
    res.append('|')
    
res = '</td><td>'.join(res)
res = res.split('|')
content = '<table>'
for i in range(len(res)-1):
    if i == 0:
        content = content+'<tr><td>'+res[i].strip('</td><td>')+'</td></tr>'
    else:
        print i
        os.system("cd . > /tmp/mytxt")
        content1 = content+'<tr><td>'+res[i].strip('</td><td>')+'</td></tr>'
        mail = str(table.cell(i,mailNum).value)
        content1 = content1+'</table>'
        output = open('/tmp/mytxt', 'w')
        output.write(content1.encode('UTF-8'))
        output.close()
        os.system("cat /tmp/mytxt | mutt -s 'excel' -e 'set content_type=\"text/html\"' "+mail)

Sevenfal

这个人太懒什么东西都没留下

文章评论(0)