python脚本定时发送邮件

 更新时间:2020年12月22日 17:01:42   作者:缘自天方  
这篇文章主要为大家详细介绍了python脚本定时发送邮件,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了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()

表格如下:

如果放在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 RuntimeWarning:invalid value encountered in double_scalars处理

    Python RuntimeWarning:invalid value encounter

    这篇文章主要介绍了Python RuntimeWarning:invalid value encountered in double_scalars处理,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-06-06
  • 解决Pytorch半精度浮点型网络训练的问题

    解决Pytorch半精度浮点型网络训练的问题

    这篇文章主要介绍了解决Pytorch半精度浮点型网络训练的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-05-05
  • 从零开始学Python第八周:详解网络编程基础(socket)

    从零开始学Python第八周:详解网络编程基础(socket)

    本篇文章主要介绍了从零开始学Python第八周:详解网络编程基础(socket) ,具有一定的参考价值,有兴趣的可以了解一下。
    2016-12-12
  • 解决tensorflow读取本地MNITS_data失败的原因

    解决tensorflow读取本地MNITS_data失败的原因

    这篇文章主要介绍了解决tensorflow读取本地MNITS_data失败的原因,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-06-06
  • VsCode终端激活anconda环境问题解决

    VsCode终端激活anconda环境问题解决

    本文主要介绍了VsCode终端激活anconda环境问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-01-01
  • 如何使用python进行pdf文件分割

    如何使用python进行pdf文件分割

    这篇文章主要介绍了如何使用python进行pdf文件分割,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • 记一次django内存异常排查及解决方法

    记一次django内存异常排查及解决方法

    这篇文章主要给大家介绍了关于一次django内存异常排查记解决方法,文中通过示例代码介绍的非常详细,对大家学习或者使用django具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2020-08-08
  • Python实现考试自动答题的脚本分享

    Python实现考试自动答题的脚本分享

    最近这段时间天气正正好,不冷不热,是学习考驾照的好时机。为了帮助大家能够顺利获得驾照,小编为大家准备了驾照考试的自动答题小程序,希望对大家有所帮助
    2023-03-03
  • 解读python cvxpy下SDP问题编程

    解读python cvxpy下SDP问题编程

    这篇文章主要介绍了解读python cvxpy下SDP问题编程,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-12-12
  • Python对口红进行数据分析来选定情人节礼物

    Python对口红进行数据分析来选定情人节礼物

    情人节送小仙女什么礼物?让我们来用Python对口红进行数据分析,那个女孩子会拒绝这样精心挑选的礼物,感兴趣的小伙伴快来看看吧
    2022-02-02

最新评论