python腳本定時(shí)發(fā)送郵件
本文實(shí)例為大家分享了python定時(shí)發(fā)送郵件的具體代碼,供大家參考,具體內(nèi)容如下
全部代碼如下:
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">工作事項(xiàng)</th>
<th style="padding:6;font-size:16">負(fù)責(zé)人</th>
<th style="padding:6;font-size:16">進(jìn)度</th>
<th style="padding:6;font-size:16">風(fēng)險(xiǎn)與問(wèn)題</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) # 浮點(diǎn)轉(zhuǎn)成百分比
updateTime = xldate_as_tuple(work[4], 0)
value = datetime(*updateTime)
# 先轉(zhuǎn)換為時(shí)間數(shù)組,然后轉(zhuǎn)換為其他格式
timeStruct = time.strptime(str(value), "%Y-%m-%d %H:%M:%S")
uptTime = str(time.strftime("%Y%m%d", timeStruct))
if uptTime != nowDate:
raise RuntimeError('有人沒(méi)有更新最新記錄:' + 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('發(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) # 登錄郵箱服務(wù)器
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' # 服務(wù)器地址,默認(rèn)端口號(hào)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__':
# 該示例代碼生成了一個(gè)BlockingScheduler調(diào)度器,使用了默認(rèn)的任務(wù)存儲(chǔ)MemoryJobStore,以及默認(rèn)的執(zhí)行器ThreadPoolExecutor,并且最大線程數(shù)為10。
# BlockingScheduler:在進(jìn)程中運(yùn)行單個(gè)任務(wù),調(diào)度器是唯一運(yùn)行的東西
scheduler = BlockingScheduler()
# 采用阻塞的方式
# 采用corn的方式,每天18點(diǎn)發(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í)行成功,是因?yàn)閷?duì)編碼等有要求,全部更新代碼如下:
#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">工作事項(xiàng)</th>
<th style="padding:6;font-size:16">負(fù)責(zé)人</th>
<th style="padding:6;font-size:16">進(jìn)度</th>
<th style="padding:6;font-size:16">風(fēng)險(xiǎn)與問(wèn)題</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) # 浮點(diǎn)轉(zhuǎn)成百分比
updateTime = xldate_as_tuple(work[4], 0)
value = datetime(*updateTime)
# 先轉(zhuǎn)換為時(shí)間數(shù)組,然后轉(zhuǎn)換為其他格式
timeStruct = time.strptime(str(value), "%Y-%m-%d %H:%M:%S")
uptTime = str(time.strftime("%Y%m%d", timeStruct))
if uptTime != nowDate:
raise RuntimeError('有人沒(méi)有更新最新記錄:' + 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('發(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) # 登錄郵箱服務(wù)器
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' # 服務(wù)器地址,默認(rèn)端口號(hào)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__':
# 該示例代碼生成了一個(gè)BlockingScheduler調(diào)度器,使用了默認(rèn)的任務(wù)存儲(chǔ)MemoryJobStore,以及默認(rèn)的執(zhí)行器ThreadPoolExecutor,并且最大線程數(shù)為10。
# BlockingScheduler:在進(jìn)程中運(yùn)行單個(gè)任務(wù),調(diào)度器是唯一運(yùn)行的東西
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()
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 自動(dòng)在Windows中運(yùn)行Python腳本并定時(shí)觸發(fā)功能實(shí)現(xiàn)
- 實(shí)現(xiàn)Windows下設(shè)置定時(shí)任務(wù)來(lái)運(yùn)行python腳本
- 如何給windows設(shè)置定時(shí)任務(wù)并運(yùn)行python腳本
- python 實(shí)現(xiàn)定時(shí)任務(wù)的四種方式
- python獲取指定時(shí)間段內(nèi)特定規(guī)律的日期列表
- python中用Scrapy實(shí)現(xiàn)定時(shí)爬蟲(chóng)的實(shí)例講解
- Python爬蟲(chóng)定時(shí)計(jì)劃任務(wù)的幾種常見(jiàn)方法(推薦)
- python實(shí)現(xiàn)定時(shí)發(fā)送郵件到指定郵箱
- python實(shí)現(xiàn)定時(shí)發(fā)送郵件
- Python實(shí)現(xiàn)FTP文件定時(shí)自動(dòng)下載的步驟
- python爬蟲(chóng)調(diào)度器用法及實(shí)例代碼
- scrapy處理python爬蟲(chóng)調(diào)度詳解
- 簡(jiǎn)單的Python調(diào)度器Schedule詳解
- python編寫(xiě)網(wǎng)頁(yè)爬蟲(chóng)腳本并實(shí)現(xiàn)APScheduler調(diào)度
- Python使用定時(shí)調(diào)度任務(wù)的方式
相關(guān)文章
Python?程序通過(guò)可執(zhí)行文件部署方式
這篇文章主要介紹了Python?程序通過(guò)可執(zhí)行文件部署方式,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-04-04
python opencv實(shí)現(xiàn)運(yùn)動(dòng)檢測(cè)
這篇文章主要為大家詳細(xì)介紹了python opencv實(shí)現(xiàn)運(yùn)動(dòng)檢測(cè),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-07-07
基于python3實(shí)現(xiàn)socket文件傳輸和校驗(yàn)
這篇文章主要為大家詳細(xì)介紹了基于python3實(shí)現(xiàn)socket文件傳輸和校驗(yàn),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-07-07
python將一個(gè)英文語(yǔ)句以單詞為單位逆序排放的方法
今天小編就為大家分享一篇python將一個(gè)英文語(yǔ)句以單詞為單位逆序排放的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-12-12
Anaconda虛擬環(huán)境中安裝cudatoolkit和cudnn包并配置pytorch-gpu的配置教程
這篇文章詳細(xì)介紹了如何在Anaconda虛擬環(huán)境中安裝和配置TensorFlow,特別是針對(duì)CUDA和cuDNN的版本管理,文章首先解釋了為什么需要更新TensorFlow版本,然后指導(dǎo)如何創(chuàng)建新的虛擬環(huán)境,需要的朋友可以參考下2025-02-02
使用python進(jìn)行文本預(yù)處理和提取特征的實(shí)例
今天小編就為大家分享一篇使用python進(jìn)行文本預(yù)處理和提取特征的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06
python中的decimal類(lèi)型轉(zhuǎn)換實(shí)例詳解
decimal 模塊實(shí)現(xiàn)了定點(diǎn)和浮點(diǎn)算術(shù)運(yùn)算符,使用的是大多數(shù)人所熟悉的模型,而不是程序員熟悉的模型,即大多數(shù)計(jì)算機(jī)硬件實(shí)現(xiàn)的 IEEE 浮點(diǎn)數(shù)運(yùn)算。這篇文章主要介紹了python里的decimal類(lèi)型轉(zhuǎn)換,需要的朋友可以參考下2019-06-06

