Python根据excel 自动发邮件--自动化小工具
import smtplib
from email.mime.text import MIMEText #邮件内容
from openpyxl import load_workbook # excel库
from email.header import Header # 邮件抬头
# 加载excel文件,data_only=True是只取数值 excel 文件地址可改,注意在同一文件夹
wb = load_workbook('case .xlsx', data_only=True)
sheet = wb.active # 激活当前excel的表格
count = 0
table_col_html = '<thead>' # HTML表头,成对出现
for row in sheet.iter_rows(min_row=1):
count += 1
if count == 1: # first row
for col in row:
table_col_html += f'<th>{col.value}</th>'
table_col_html += '</thead>'
continue
else:
row_text = "<tr>"
for cell in row:
row_text += f"<td>{cell.value}</td>"
row_text += "</tr>" # 注意循环 丢了加号了
name = row[2]
staff_email = row[1].value
print(staff_email, name.value)#打印邮件地址,收件人名
#邮件内容HTML格式
mail_body_contxt = f'''
<h3>{name.value},你好:</h3>
<p>请查收工单</p>
<table border ="1px solid black">
{table_col_html}
{row_text}
</table>
'''
print(mail_body_contxt)
msg_body = MIMEText(mail_body_contxt, "html", 'utf-8')
msg_body["from"] = Header("公司", 'utf-8')
msg_body["to"] = Header('hero', 'utf-8')
msg_body["subject"] = Header("项目", 'utf-8')
# 发邮件
# 加载邮箱信息
smtp_obj = smtplib.SMTP_SSL('smtp.qq.com', 465)
smtp_obj.login('w447505---@qq.com', '授权码')#通过qq邮箱-设置-账户-POP3/SMTP服务开启获得授权码
smtp_obj.sendmail('w447505---@qq.com', [staff_email], msg_body.as_string())
print(F'成功发送工资条到{staff_email}')
|