python脚本定时发送邮件
作者:缘自天方 时间:2023-08-07 16:36:02
本文实例为大家分享了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('\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"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('\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()
来源:https://blog.csdn.net/qq_35956041/article/details/102574867
标签:python,发送邮件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python清除字符串前后空格函数的方法
2023-10-14 07:12:57
python编辑用户登入界面的实现代码
2022-02-07 20:24:08
![](https://img.aspxhome.com/file/2023/4/99124_0s.png)
利用ASP+JMAIL进行邮件群发的新思路
2008-03-20 13:30:00
如何利用Python随机从list中挑选一个元素
2023-08-04 00:05:54
MySQL如何导入SQL数据库的实战举例
2024-01-21 23:44:53
![](https://img.aspxhome.com/file/2023/0/128060_0s.png)
vue实现输入框的模糊查询的示例代码(节流函数的应用场景)
2024-05-08 09:33:35
![](https://img.aspxhome.com/file/2023/2/130272_0s.png)
十分钟利用Python制作属于你自己的个性logo
2021-08-25 05:12:41
![](https://img.aspxhome.com/file/2023/2/80762_0s.jpg)
Go语言实现的简单网络端口扫描方法
2024-04-26 17:23:06
使用Perl语言去存取mSQL和MySQL数据库的内容
2009-10-23 09:11:00
yolov5 win10 CPU与GPU环境搭建过程
2021-07-17 15:21:11
![](https://img.aspxhome.com/file/2023/1/72961_0s.jpg)
缓存是如何实现的?
2009-11-01 15:35:00
Pandas库之DataFrame使用的学习笔记
2023-07-03 23:34:28
![](https://img.aspxhome.com/file/2023/1/97371_0s.png)
如何查看SQLSERVER中某个查询用了多少TempDB空间
2024-01-16 06:40:21
![](https://img.aspxhome.com/file/2023/6/94426_0s.png)
七个生态系统核心库[python自学收藏]
2021-09-17 03:51:12
![](https://img.aspxhome.com/file/2023/9/101699_0s.jpg)
MySQL之information_schema数据库详细讲解
2024-01-16 18:56:54
Python3.6基于正则实现的计算器示例【无优化简单注释版】
2023-07-19 05:29:25
![](https://img.aspxhome.com/file/2023/3/79603_0s.png)
Python输出带颜色的字符串实例
2023-08-20 05:28:03
![](https://img.aspxhome.com/file/2023/9/101719_0s.png)
javascript实现小型区块链功能
2024-04-18 09:29:10
![](https://img.aspxhome.com/file/2023/9/136609_0s.png)
如何对python的字典进行排序
2023-01-28 10:47:31
python 文本单词提取和词频统计的实例
2022-10-25 04:53:03