python脚本定时发送邮件


Posted in Python onDecember 22, 2020

本文实例为大家分享了python定时发送邮件的具体代码,供大家参考,具体内容如下

全部代码如下:

import time
from datetime import datetime
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
 
import xlrd
from apscheduler.schedulers.blocking import BlockingScheduler
from xlrd import xldate_as_tuple
 
ISOTIMEFORMAT = '%Y%m%d'
import smtplib
 
 
def read_file(file_path):
  file_list = []
  work_book = xlrd.open_workbook(file_path)
  sheet_data = work_book.sheet_by_name('Sheet1')
  print('now is process :', sheet_data.name)
  Nrows = sheet_data.nrows
 
  for i in range(1, Nrows):
    file_list.append(sheet_data.row_values(i))
 
  return file_list
 
 
def _format_addr(s):
  name, addr = parseaddr(s)
  return formataddr((Header(name, 'utf-8').encode(), addr))
 
 
def sendEmail(from_addr, password, to_addr, smtp_server, file_list):
  nowDate = str(time.strftime(ISOTIMEFORMAT, time.localtime()))
  html_content_start = \
    '''
    <html>
    <body>
      <p>hi,All:</p>
      <table border="0"width="95%"height="50%"cellpadding="1"style="margin:15px"cellspacing="1"bordercolor="#D3D3D3"bgcolor="#9F9F9F">
        <tr bgcolor="#D3D3D3" style="margin:10px">
          <th style="padding:6;font-size:16">工作事项</th>
          <th style="padding:6;font-size:16">负责人</th>
          <th style="padding:6;font-size:16">进度</th>
          <th style="padding:6;font-size:16">风险与问题</th>
        </tr>
    '''
  for i in range(len(file_list)):
    work = file_list[i]
    workdata, person_name, progress, issue = str(work[0]), str(work[1]), str(work[2]), str(work[3])
    if '.' in str(work[2]): # 填的数字
      progress = "%.0f%%" % (work[2] * 100) # 浮点转成百分比
 
    updateTime = xldate_as_tuple(work[4], 0)
    value = datetime(*updateTime)
    # 先转换为时间数组,然后转换为其他格式
    timeStruct = time.strptime(str(value), "%Y-%m-%d %H:%M:%S")
    uptTime = str(time.strftime("%Y%m%d", timeStruct))
    if uptTime != nowDate:
      raise RuntimeError('有人没有更新最新记录:' + str(work[1]))
 
    html_content_suffer = \
      '''
          <tr bgcolor="#FFFFFF" >
            <td style="padding:6;font-size:14">{workdata}</td>
            <td style="padding:6;font-size:14">{person_name}</td>
            <td style="padding:6;font-size:14">{progress}</td>
            <td style="padding:6;font-size:14">{issue}</td>
          </tr>
      '''.format(workdata=workdata.replace('\n', '<br>'), person_name=person_name, progress=progress, issue=issue)
    html_content_start += html_content_suffer
 
  html_content_end = \
    '''
      </table>
    </body>
    </html>
    '''
  html_content = html_content_start + html_content_end
 
  try:
    msg = MIMEMultipart()
    msg.attach(MIMEText(html_content, 'html', 'utf-8'))
    msg['From'] = _format_addr('发送方 <%s>' % from_addr)
    msg['To'] = _format_addr(to_addr + '<%s>' % to_addr)
    msg['Subject'] = Header('主题' + nowDate, 'utf-8').encode()
 
    server = smtplib.SMTP_SSL(smtp_server, 465)
    server.login(from_addr, password) # 登录邮箱服务器
    server.sendmail(from_addr, [to_addr], msg.as_string()) # 发送信息
    server.quit()
    print("from_addr:" + str(from_addr), " to_addr:", to_addr, "已发送成功!")
  except Exception as e:
    print("发送失败" + e)
 
 
def job():
  root_dir = 'D:\\develop\\python\\file'
  file_path = root_dir + "\\excel.xlsx"
  from_addr = 'aaa@163.com' # 邮箱登录用户名
  password = 'mima' # 登录密码
  smtp_server = 'smtp.com' # 服务器地址,默认端口号25
  to_addr = 'aaa@163.com' # 接收方邮箱
 
  file_list = read_file(file_path)
  sendEmail(from_addr, password, to_addr, smtp_server, file_list)
  print('发送完成')
 
 
if __name__ == '__main__':
  # 该示例代码生成了一个BlockingScheduler调度器,使用了默认的任务存储MemoryJobStore,以及默认的执行器ThreadPoolExecutor,并且最大线程数为10。
 
  # BlockingScheduler:在进程中运行单个任务,调度器是唯一运行的东西
  scheduler = BlockingScheduler()
  # 采用阻塞的方式
 
  # 采用corn的方式,每天18点发送
  scheduler.add_job(job, 'cron', hour='18')
  '''
    year (int|str) ? 4-digit year
    month (int|str) ? month (1-12)
    day (int|str) ? day of the (1-31)
    week (int|str) ? ISO week (1-53)
    day_of_week (int|str) ? number or name of weekday (0-6 or mon,tue,wed,thu,fri,sat,sun)
    hour (int|str) ? hour (0-23)
    minute (int|str) ? minute (0-59)
    econd (int|str) ? second (0-59)
    start_date (datetime|str) ? earliest possible date/time to trigger on (inclusive)
    end_date (datetime|str) ? latest possible date/time to trigger on (inclusive)
    timezone (datetime.tzinfo|str) ? time zone to use for the date/time calculations (defaults to scheduler timezone)
    *  any  Fire on every value
    */a  any  Fire every a values, starting from the minimum
    a-b  any  Fire on any value within the a-b range (a must be smaller than b)
    a-b/c  any  Fire every c values within the a-b range
    xth y  day  Fire on the x -th occurrence of weekday y within the month
    last x  day  Fire on the last occurrence of weekday x within the month
    last  day  Fire on the last day within the month
    x,y,z  any  Fire on any matching expression; can combine any number of any of the above expressions
    '''
  scheduler.start()

表格如下:

python脚本定时发送邮件

如果放在linux系统中执行,上述脚本不能执行成功,是因为对编码等有要求,全部更新代码如下:

#coding=utf-8
import time
from datetime import datetime
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
 
import sys
 
import xlrd
from apscheduler.schedulers.blocking import BlockingScheduler
from xlrd import xldate_as_tuple
 
ISOTIMEFORMAT = '%Y%m%d'
import smtplib
import logging
logging.basicConfig()
 
def read_file(file_path):
  file_list = []
  work_book = xlrd.open_workbook(file_path)
  sheet_data = work_book.sheet_by_name('Sheet1')
  print('now is process :', sheet_data.name)
  Nrows = sheet_data.nrows
 
  for i in range(1, Nrows):
    file_list.append(sheet_data.row_values(i))
 
  return file_list
 
 
def _format_addr(s):
  name, addr = parseaddr(s)
  return formataddr((Header(name, 'utf-8').encode(), addr))
 
 
def sendEmail(from_addr, password, to_addr, smtp_server, file_list):
  nowDate = str(time.strftime(ISOTIMEFORMAT, time.localtime()))
  html_content_start = \
    '''
    <html>
    <body>
      <p>hi,All:</p>
      <table border="0"width="95%"height="50%"cellpadding="1"style="margin:15px"cellspacing="1"bordercolor="#D3D3D3"bgcolor="#9F9F9F">
        <tr bgcolor="#D3D3D3" style="margin:10px">
          <th style="padding:6;font-size:16">工作事项</th>
          <th style="padding:6;font-size:16">负责人</th>
          <th style="padding:6;font-size:16">进度</th>
          <th style="padding:6;font-size:16">风险与问题</th>
        </tr>
    '''
  for i in range(len(file_list)):
    work = file_list[i]
    workdata, person_name, progress, issue = str(work[0]), str(work[1]), str(work[2]), str(work[3])
    if '.' in str(work[2]): # 填的数字
      progress = "%.0f%%" % (work[2] * 100) # 浮点转成百分比
 
    updateTime = xldate_as_tuple(work[4], 0)
    value = datetime(*updateTime)
    # 先转换为时间数组,然后转换为其他格式
    timeStruct = time.strptime(str(value), "%Y-%m-%d %H:%M:%S")
    uptTime = str(time.strftime("%Y%m%d", timeStruct))
    if uptTime != nowDate:
      raise RuntimeError('有人没有更新最新记录:' + str(work[1]))
 
    html_content_suffer = \
      '''
          <tr bgcolor="#FFFFFF" >
            <td style="padding:6;font-size:14">{workdata}</td>
            <td style="padding:6;font-size:14">{person_name}</td>
            <td style="padding:6;font-size:14">{progress}</td>
            <td style="padding:6;font-size:14">{issue}</td>
          </tr>
      '''.format(workdata=workdata.replace('\n', '<br>'), person_name=person_name.replace('\n', '<br>'), progress=progress.replace('\n', '<br>'), issue=issue.replace('\n', '<br>'))
    html_content_start += html_content_suffer
 
  html_content_end = \
    '''
      </table>
    </body>
    </html>
    '''
  html_content = html_content_start + html_content_end
 
  try:
    msg = MIMEMultipart()
    msg.attach(MIMEText(html_content, 'html', 'utf-8'))
    msg['From'] = _format_addr('发送方 <%s>' % from_addr)
    msg['To'] = _format_addr(to_addr + '<%s>' % to_addr)
    msg['Subject'] = Header('主题' + nowDate, 'utf-8').encode()
 
    server = smtplib.SMTP_SSL(smtp_server, 465)
    server.login(from_addr, password) # 登录邮箱服务器
    server.sendmail(from_addr, [to_addr], msg.as_string()) # 发送信息
    server.quit()
    print("from_addr:" + str(from_addr), " to_addr:", to_addr, "已发送成功!")
  except Exception as e:
    print("发送失败" + e)
 
 
def job():
  root_dir = 'D:\\develop\\python\\file'
  file_path = root_dir + "\\excel.xlsx"
  from_addr = 'aaa@163.com' # 邮箱登录用户名
  password = 'mima' # 登录密码
  smtp_server = 'smtp.com' # 服务器地址,默认端口号25
  to_addr = 'aaa@163.com' # 接收方邮箱
 
  file_list = read_file(file_path)
  sendEmail(from_addr, password, to_addr, smtp_server, file_list)
  print('发送完成')
 
 
if __name__ == '__main__':
  # 该示例代码生成了一个BlockingScheduler调度器,使用了默认的任务存储MemoryJobStore,以及默认的执行器ThreadPoolExecutor,并且最大线程数为10。
 
  # BlockingScheduler:在进程中运行单个任务,调度器是唯一运行的东西
  scheduler = BlockingScheduler()
  # 采用阻塞的方式
 
  reload(sys)
 
  sys.setdefaultencoding("utf8")
 
  # 采用corn的方式
  scheduler.add_job(job, 'cron', hour='21', minute='0')
  '''
    year (int|str) ? 4-digit year
    month (int|str) ? month (1-12)
    day (int|str) ? day of the (1-31)
    week (int|str) ? ISO week (1-53)
    day_of_week (int|str) ? number or name of weekday (0-6 or mon,tue,wed,thu,fri,sat,sun)
    hour (int|str) ? hour (0-23)
    minute (int|str) ? minute (0-59)
    econd (int|str) ? second (0-59)
    start_date (datetime|str) ? earliest possible date/time to trigger on (inclusive)
    end_date (datetime|str) ? latest possible date/time to trigger on (inclusive)
    timezone (datetime.tzinfo|str) ? time zone to use for the date/time calculations (defaults to scheduler timezone)
    *  any  Fire on every value
    */a  any  Fire every a values, starting from the minimum
    a-b  any  Fire on any value within the a-b range (a must be smaller than b)
    a-b/c  any  Fire every c values within the a-b range
    xth y  day  Fire on the x -th occurrence of weekday y within the month
    last x  day  Fire on the last occurrence of weekday x within the month
    last  day  Fire on the last day within the month
    x,y,z  any  Fire on any matching expression; can combine any number of any of the above expressions
    '''
  scheduler.start()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python 代码性能优化技巧分享
Aug 07 Python
python数据处理实战(必看篇)
Jun 11 Python
Python3实战之爬虫抓取网易云音乐的热门评论
Oct 09 Python
对Python中9种生成新对象的方法总结
May 23 Python
多个应用共存的Django配置方法
May 30 Python
深入理解Django自定义信号(signals)
Oct 15 Python
对python调用RPC接口的实例详解
Jan 03 Python
详解Python中的format格式化函数的使用方法
Nov 20 Python
Django多进程滚动日志问题解决方案
Dec 17 Python
python 实现多维数组(array)排序
Feb 28 Python
python实现电子词典
Mar 03 Python
用python获取txt文件中关键字的数量
Dec 24 Python
如何用python批量调整视频声音
Dec 22 #Python
分享一个python的aes加密代码
Dec 22 #Python
解决PyCharm无法使用lxml库的问题(图解)
Dec 22 #Python
去除python中的字符串空格的简单方法
Dec 22 #Python
Python lxml库的简单介绍及基本使用讲解
Dec 22 #Python
Python中过滤字符串列表的方法
Dec 22 #Python
python中@property的作用和getter setter的解释
Dec 22 #Python
You might like
Yii结合CKEditor实现图片上传功能
2014/06/13 PHP
ThinkPHP框架实现数据增删改
2017/05/07 PHP
对php 判断http还是https,以及获得当前url的方法详解
2019/01/15 PHP
window.print打印指定div指定网页指定区域的方法
2014/08/04 Javascript
面向切面编程(AOP)的理解
2015/05/01 Javascript
jquery实现表单输入时提示文字滑动向上效果
2015/08/10 Javascript
AngularJs基本特性解析(一)
2016/07/21 Javascript
javascript中replace使用方法总结
2017/03/01 Javascript
Spring Boot+AngularJS+BootStrap实现进度条示例代码
2017/03/02 Javascript
解决Vue2.0自带浏览器里无法打开的原因(兼容处理)
2017/07/28 Javascript
解决微信二次分享不显示摘要和图片的问题
2017/08/18 Javascript
fullpage.js最后一屏滚动方式
2018/02/06 Javascript
webstrom Debug 调试vue项目的方法步骤
2018/07/17 Javascript
详解Vue源码学习之callHook钩子函数
2018/07/25 Javascript
在小程序中使用Echart图表的示例代码
2018/08/02 Javascript
VUE预渲染及遇到的坑
2018/09/03 Javascript
vue cli4下环境变量和模式示例详解
2020/04/09 Javascript
让你30分钟快速掌握vue3教程
2020/10/26 Javascript
[01:34]DOTA2 7.22版本新增神杖效果一览(敏捷英雄篇)
2019/05/28 DOTA
在Python的Django框架中编写错误提示页面
2015/07/22 Python
Python 通过pip安装Django详细介绍
2017/04/28 Python
Python基于Matplotlib库简单绘制折线图的方法示例
2017/08/14 Python
彻底搞懂python 迭代器和生成器
2020/09/07 Python
详解Sticky Footer 绝对底部的两种套路
2017/11/03 HTML / CSS
Alba Moda德国网上商店:意大利时尚女装销售
2016/11/14 全球购物
个人求职简历的自我评价范文
2013/10/09 职场文书
应届生妇产科护士求职信
2013/10/27 职场文书
创业计划书中要认真思考的问题
2013/12/28 职场文书
演讲稿怎么写才完美
2014/01/02 职场文书
2014领导干部学习焦裕禄同志先进事迹思想汇报
2014/09/19 职场文书
区政府领导班子个人对照检查材料
2014/09/25 职场文书
党的群众路线领导班子整改方案
2014/09/27 职场文书
2014年学生管理工作总结
2014/12/20 职场文书
学雷锋感言
2015/08/03 职场文书
阿里云服务器搭建Php+Apache运行环境的详细过程
2021/05/15 PHP
MySQL优化之慢日志查询
2022/06/10 MySQL