好开心啊,在旁边大神的帮助下,终于实现了发工资的 python 脚本,之前用 shell 写的老出错,刚才测试,发 80 个人工资详情,妥妥的,代码如下:
- from email.mime.multipart import MIMEMultipart
- from email.mime.text import MIMEText
- from email.mime.image import MIMEImage
- from email.header import Header
- #from handle_data_for_salary import main
- #import handle_data_for_salary
- import smtplib
- import xlrd
- import xdrlib,sys
- def open_excel(file='test1.xls'):
- try:
- data = xlrd.open_workbook(file)
- return data
- except Exception as e:
- print(str(e))
- def excel_table_byname(file='test1.xls',colnameindex=0,by_name='Sheet1'):
- data = open_excel(file)
- table = data.sheet_by_name(by_name)
- nrows = table.nrows #行数
- colnames = table.row_values(colnameindex) #某一行数据
- list = []
- for rownum in range(2,nrows):
- row = table.row_values(rownum)
- if row:
- app = {}
- for i in range(len(colnames)):
- app[colnames[i]] = row[i]
- list.append(app)
- return list
- def get_value():
- tables = excel_table_byname()
- for row in tables:
- global mail
- mail = row["邮箱地址"]
- global name
- name = row["姓名"]
- global context
- authInfo = {}
- authInfo['server'] = 'smtp.163.com'
- authInfo['user'] =
- authInfo['password'] = '邮箱密码'
- fromAdd =
- subject = 'Email Subject'
- context = str(row)
- toAdd = [mail, ]
- sendEmail(authInfo, fromAdd, toAdd, subject, context)
- def sendEmail(authInfo, fromAdd, toAdd, subject, plainText):
- strFrom = fromAdd
- strTo = '; '.join(toAdd)
- server = authInfo.get('server')
- smtpPort = 25
- sslPort = 465
- user = authInfo.get('user')
- passwd = authInfo.get('password')
- if not (server and user and passwd) :
- print('incomplete login info, exit now')
- return
- # 设定root信息
- msgRoot = MIMEMultipart('related')
- msgRoot['Subject'] = subject
- msgRoot['From'] = '%s<%s>' % (Header('工资详情', 'utf-8'), strFrom)
- msgRoot['To'] = strTo
- # 邮件正文内容
- msgText = MIMEText(plainText, 'plain', 'utf-8')
- msgRoot.attach(msgText)
- msgAlternative = MIMEMultipart('alternative')
- msgRoot.attach(msgAlternative)
- try:
- #发送邮件
- smtp = smtplib.SMTP()
- smtp.connect(server, smtpPort)
- #ssl加密方式,通信过程加密,邮件数据安全
- # smtp = smtplib.SMTP_SSL()
- # smtp.connect(server, sslPort)
- #设定调试级别,依情况而定
- # smtp.set_debuglevel(1)
- smtp.login(user, passwd)
- smtp.sendmail(strFrom, toAdd, msgRoot.as_string())
- smtp.quit()
- print("邮件发送给%s成功!"%(name))
- except Exception as e:
- print("失败:" + str(e))
- if __name__ == '__main__' :
- get_value()
注意:python 环境为 3.5,实验环境在 windows,使用工具为 pycharm,需要用到的模块: pip3 install xlrd,其中的工资表,如下图截图部分所示:后面还有很多列,看自己的需求加不,反正都是一列一列的数据
实验结果如下:
现在只是实现了需求,发的邮件多了估计有问题,还有邮件的格式太丑了,等下回家再改改,加油加油
来源: