欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python脚本定时发送邮件

程序员文章站 2022-04-29 21:39:00
本文实例为大家分享了python定时发送邮件的具体代码,供大家参考,具体内容如下全部代码如下:import timefrom datetime import datetimefrom email.he...

本文实例为大家分享了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 发送邮件