您好,登錄后才能下訂單哦!
利用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"cellspacing="1"bordercolor="#D3D3D3"bgcolor="#9F9F9F"> <tr bgcolor="#D3D3D3" > <th >工作事項</th> <th >負責人</th> <th >進度</th> <th >風險與問題</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 >{workdata}</td> <td >{person_name}</td> <td >{progress}</td> <td >{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"cellspacing="1"bordercolor="#D3D3D3"bgcolor="#9F9F9F"> <tr bgcolor="#D3D3D3" > <th >工作事項</th> <th >負責人</th> <th >進度</th> <th >風險與問題</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 >{workdata}</td> <td >{person_name}</td> <td >{progress}</td> <td >{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怎么實現一個定時發送郵件功能問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。