感觉yagmail比smtplib的代码更简洁,不过简洁版也有些没法实现。
实现效果:
from openpyxl import load_workbook
import yagmail
import keyring
from datetime import *
wb = load_workbook('【薪资总表_20200607】.xlsx', data_only=True)
sheet = wb['工资条-2020']
yagmail.register('***@qq.com','******') #登录邮箱(邮箱地址和授权码)
pwd = keyring.get_password('yagmail','***@qq.com') #登录的邮箱地址
yag = yagmail.SMTP(user='***@qq.com',host='smtp.qq.com',password=pwd) #三个邮箱地址一致
count = 0
table_header = '<thead>'
for row in sheet:
count += 1
if count == 1:
for cell in row:
if cell.column != 'C': #判断是否是邮箱地址列
table_header += f'<th>{cell.value}</th>'
table_header += '</thead>'
continue
else:
row_text = '<tr>'
for cell in row:
if cell.column == 'C':
continue
if not isinstance(cell.value, str): #Excel中浮点数限制小数位数
cell.value = round(cell.value, 2)
else:
cell.value = cell.value
row_text += f'<td align=center valign=middle font-size=12px>{cell.value}</td>'
row_text += '</tr>'
name = row[0].value
email = row[2].value
mail_content = f'''
<h3>{name}:</h3>
<p>你好!
请查收你{date.today().year}-{date.today().month}月的工资条,如有问题,请私信我。</p>
<table border=1px black rules=all cellpadding=5px>{table_header}{row_text}</table>
<br>
<p align=right>人力资源部
{date.today()}</p>
'''
yag.send(f'{email}',f'公司{date.today().year}-{date.today().month}月工资条',mail_content)
print(f'{name}的工资条发送完毕')