我是靠谱客的博主 柔弱棒球,这篇文章主要介绍用python实现定时发送邮件的功能,现在分享给大家,希望可以做个参考。

像python这种库丰富又不需要接触到底层的语言,用来做定时邮件的功能再适合不过。

代码如下,目的是为了每天上班下班(9点Check in, 19点Check out)发送一封邮件,且邮件标题带日期。

邮件目前是整点发送,且没有排除周末,若想改得更随机一点,可以增加sleep的间隔,或者用分钟来判断。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/python # -*- coding: UTF-8 -*- import smtplib from email.mime.text import MIMEText from email.utils import formataddr import time, os import pytz import datetime import logging my_sender='xxxxxxxx' # 发件人邮箱账号 mail_sender='xxxxxxxx@xxxxxxxxx.com' my_pass = 'xxxxxxxx' # 发件人邮箱密码 cc_user='xxxxxxxx@xxxxxxxxx.com' test_receiver='xxxxxxxxxx@xxxxxxxx.com' gmail_user='xxxxxxx@qq.com' # 加入bcc的好处是可以自己确认是否发送成功,以及邮件的格式 def mail(status): ret=True try: msg=MIMEText('Check '+status+' for work. Thanks!','plain','utf-8') msg['From']=formataddr(["xxxxx",mail_sender]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号 msg['To']=formataddr(["xxxxx",test_receiver]) # 括号里的对应收件人邮箱昵称、收件人邮箱账号 msg['Cc']=formataddr(["xxxxx",cc_user]) msg['Bcc']=formataddr(["xxxxx", gmail_user]) today=datetime.date.today() title = "xxxxxxxxx-xxxxxx-"+ datetime.date.today().strftime('%Y%m%d') +" Check "+status msg['Subject']=title server=smtplib.SMTP("smtp.xxxxxxxx.com", 25) # 发件人邮箱中的SMTP服务器,端口是25,这里需要关注自己邮箱的设置,如果是SSL要调用定外的接口 server.login(my_sender, my_pass) # 括号中对应的是发件人邮箱账号、邮箱密码 server.sendmail(mail_sender,[test_receiver,cc_user,gmail_user],msg.as_string()) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件 server.quit() # 关闭连接 except Exception: # 如果 try 中的语句没有执行,则会执行下面的 ret=False ret=False print 4 return ret def check_time(): in_mail_sent = False out_mail_sent = False sent_day=datetime.date.today() tz=pytz.timezone('Asia/Shanghai') # 很多机器的时区是GMT+0, 因此要设置城东八区 while True: ts_start = datetime.datetime.now(tz) print ts_start print ts_start.hour if ts_start.hour==9 and not in_mail_sent: ret=mail("in") if ret: print("Check in邮件发送成功") else: print("Check in邮件发送失败") in_mail_sent = True elif ts_start.hour==19 and not out_mail_sent: ret=mail("out") if ret: print("Check out邮件发送成功") else: print("Check out邮件发送失败") out_mail_sent = True else: print("waiting...") if datetime.date.today() != sent_day: print("reset for new day") in_mail_sent = False out_mail_sent = False sent_day = datetime.date.today() time.sleep(100) check_time() print("quit!")

最后

以上就是柔弱棒球最近收集整理的关于用python实现定时发送邮件的功能的全部内容,更多相关用python实现定时发送邮件内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(50)

评论列表共有 0 条评论

立即
投稿
返回
顶部