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('
', '<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 = '[email protected]' # password = 'mima' # smtp_server = 'smtp.com' # , 25 to_addr = '[email protected]' # 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) C 4-digit year month (int|str) C month (1-12) day (int|str) C day of the (1-31) week (int|str) C ISO week (1-53) day_of_week (int|str) C number or name of weekday (0-6 or mon,tue,wed,thu,fri,sat,sun) hour (int|str) C hour (0-23) minute (int|str) C minute (0-59) econd (int|str) C second (0-59) start_date (datetime|str) C earliest possible date/time to trigger on (inclusive) end_date (datetime|str) C latest possible date/time to trigger on (inclusive) timezone (datetime.tzinfo|str) C 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('
', '<br>'), person_name=person_name.replace('
', '<br>'), progress=progress.replace('
', '<br>'), issue=issue.replace('
', '<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 = '[email protected]' # password = 'mima' # smtp_server = 'smtp.com' # , 25 to_addr = '[email protected]' # 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) C 4-digit year month (int|str) C month (1-12) day (int|str) C day of the (1-31) week (int|str) C ISO week (1-53) day_of_week (int|str) C number or name of weekday (0-6 or mon,tue,wed,thu,fri,sat,sun) hour (int|str) C hour (0-23) minute (int|str) C minute (0-59) econd (int|str) C second (0-59) start_date (datetime|str) C earliest possible date/time to trigger on (inclusive) end_date (datetime|str) C latest possible date/time to trigger on (inclusive) timezone (datetime.tzinfo|str) C 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()
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。