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 socket.error: [Errno 98] Address already in use的原因和解决方法
Aug 25 Python
python二分查找算法的递归实现方法
May 12 Python
Python字符串处理实例详解
May 18 Python
解决Spyder中图片显示太小的问题
Apr 27 Python
pandas将numpy数组写入到csv的实例
Jul 04 Python
Ubuntu下Python2与Python3的共存问题
Oct 31 Python
Python 图像对比度增强的几种方法(小结)
Sep 25 Python
centos+nginx+uwsgi+Django实现IP+port访问服务器
Nov 15 Python
tensorboard实现同时显示训练曲线和测试曲线
Jan 21 Python
Django 404、500页面全局配置知识点详解
Mar 10 Python
Python实现删除某列中含有空值的行的示例代码
Jul 20 Python
Python descriptor(描述符)的实现
Nov 15 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
抓取并下载CSS中所有图片文件的php代码
2011/09/26 PHP
解析二进制流接口应用实例 pack、unpack、ord 函数使用方法
2013/06/18 PHP
yiic命令时提示“php.exe”不是内部或外部命令的解决方法
2014/12/18 PHP
PHP基于mssql扩展远程连接MSSQL的简单实现方法
2016/10/08 PHP
基于JQuery的多标签实现代码
2012/09/19 Javascript
jQuery中slice()方法用法实例
2015/01/07 Javascript
js给网页加上背景音乐及选择音效的方法
2015/03/03 Javascript
详解JavaScript异步编程中jQuery的promise对象的作用
2016/05/03 Javascript
JS实现图片的不间断连续滚动的简单实例
2016/06/03 Javascript
使用Angular缓存父页面数据的方法
2017/01/03 Javascript
JavaScript实现定时页面跳转功能示例
2017/02/14 Javascript
Angular.js指令学习中一些重要属性的用法教程
2017/05/24 Javascript
Angular 通过注入 $location 获取与修改当前页面URL的实例
2017/05/31 Javascript
web前端vue filter 过滤器
2018/01/12 Javascript
如何从零开始利用js手写一个Promise库详解
2018/04/19 Javascript
JS实现二维数组元素的排列组合运算简单示例
2019/01/28 Javascript
前端天气插件tpwidget使用方法详解
2019/06/24 Javascript
vue-week-picker实现支持按周切换的日历
2019/06/26 Javascript
原生js实现随机点餐效果
2019/12/10 Javascript
[03:16]DOTA2完美大师赛主赛事首日集锦
2017/11/23 DOTA
[01:22]DOTA2神秘商店携大量周边降临完美大师赛
2017/11/07 DOTA
python读文件逐行处理的示例代码分享
2013/12/27 Python
linux系统使用python获取cpu信息脚本分享
2014/01/15 Python
Python编码类型转换方法详解
2016/07/01 Python
Python标准库06之子进程 (subprocess包) 详解
2016/12/07 Python
python用Pygal如何生成漂亮的SVG图像详解
2017/02/10 Python
在Pandas中给多层索引降级的方法
2018/11/16 Python
python如何基于redis实现ip代理池
2020/01/17 Python
意大利宠物用品购物网站:Bauzaar
2018/09/15 全球购物
Bonprix法国:时尚、鞋子、家居
2020/12/29 全球购物
一套C#面试题
2013/10/09 面试题
副处级干部考察材料
2014/05/17 职场文书
省级优秀班集体申报材料
2014/05/25 职场文书
业务员年终工作总结2015
2015/05/28 职场文书
只需要12页,掌握撰写一流商业计划书的技巧
2019/05/07 职场文书
Python接口自动化之文件上传/下载接口详解
2022/04/05 Python