利用python怎么實現(xiàn)一個定時發(fā)送郵件功能?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
我們一直強調(diào)成都網(wǎng)站建設、做網(wǎng)站對于企業(yè)的重要性,如果您也覺得重要,那么就需要我們慎重對待,選擇一個安全靠譜的網(wǎng)站建設公司,企業(yè)網(wǎng)站我們建議是要么不做,要么就做好,讓網(wǎng)站能真正成為企業(yè)發(fā)展過程中的有力推手。專業(yè)網(wǎng)站設計公司不一定是大公司,創(chuàng)新互聯(lián)建站作為專業(yè)的網(wǎng)絡公司選擇我們就是放心。全部代碼如下:
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]): # 填的數(shù)字 progress = "%.0f%%" % (work[2] * 100) # 浮點轉成百分比 updateTime = xldate_as_tuple(work[4], 0) value = datetime(*updateTime) # 先轉換為時間數(shù)組,然后轉換為其他格式 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('發(fā)送方 <%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()) # 發(fā)送信息 server.quit() print("from_addr:" + str(from_addr), " to_addr:", to_addr, "已發(fā)送成功!") except Exception as e: print("發(fā)送失敗" + 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('發(fā)送完成') if __name__ == '__main__': # 該示例代碼生成了一個BlockingScheduler調(diào)度器,使用了默認的任務存儲MemoryJobStore,以及默認的執(zhí)行器ThreadPoolExecutor,并且較大線程數(shù)為10。 # BlockingScheduler:在進程中運行單個任務,調(diào)度器是運行的東西 scheduler = BlockingScheduler() # 采用阻塞的方式 # 采用corn的方式,每天18點發(fā)送 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系統(tǒng)中執(zhí)行,上述腳本不能執(zhí)行成功,是因為對編碼等有要求,全部更新代碼如下:
#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]): # 填的數(shù)字 progress = "%.0f%%" % (work[2] * 100) # 浮點轉成百分比 updateTime = xldate_as_tuple(work[4], 0) value = datetime(*updateTime) # 先轉換為時間數(shù)組,然后轉換為其他格式 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('發(fā)送方 <%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()) # 發(fā)送信息 server.quit() print("from_addr:" + str(from_addr), " to_addr:", to_addr, "已發(fā)送成功!") except Exception as e: print("發(fā)送失敗" + 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('發(fā)送完成') if __name__ == '__main__': # 該示例代碼生成了一個BlockingScheduler調(diào)度器,使用了默認的任務存儲MemoryJobStore,以及默認的執(zhí)行器ThreadPoolExecutor,并且較大線程數(shù)為10。 # BlockingScheduler:在進程中運行單個任務,調(diào)度器是運行的東西 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怎么實現(xiàn)一個定時發(fā)送郵件功能問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關知識。
分享題目:利用python怎么實現(xiàn)一個定時發(fā)送郵件功能-創(chuàng)新互聯(lián)
文章分享:http://vcdvsql.cn/article6/iisig.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站設計、網(wǎng)站制作、網(wǎng)站設計公司、營銷型網(wǎng)站建設、靜態(tài)網(wǎng)站、企業(yè)網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容