利用python怎么實(shí)現(xiàn)一個(gè)定時(shí)發(fā)送郵件功能?針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。

全部代碼如下:
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 >工作事項(xiàng)</th>
<th >負(fù)責(zé)人</th>
<th >進(jìn)度</th>
<th >風(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 >{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) # 登錄郵箱服務(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' # 郵箱登錄用戶(hù)名
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"cellspacing="1"bordercolor="#D3D3D3"bgcolor="#9F9F9F">
<tr bgcolor="#D3D3D3" >
<th >工作事項(xiàng)</th>
<th >負(fù)責(zé)人</th>
<th >進(jìn)度</th>
<th >風(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 >{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) # 登錄郵箱服務(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' # 郵箱登錄用戶(hù)名
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()關(guān)于利用python怎么實(shí)現(xiàn)一個(gè)定時(shí)發(fā)送郵件功能問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
分享題目:利用python怎么實(shí)現(xiàn)一個(gè)定時(shí)發(fā)送郵件功能-創(chuàng)新互聯(lián)
文章分享:http://www.chinadenli.net/article6/iisig.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站設(shè)計(jì)、網(wǎng)站制作、網(wǎng)站設(shè)計(jì)公司、營(yíng)銷(xiāo)型網(wǎng)站建設(shè)、靜態(tài)網(wǎng)站、企業(yè)網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容