python实现用程序给自己发邮件

之前跑的实验总是很耗时,有时候让程序跑着自己出去玩,又得经常回来看它有没有跑完。

于是干脆写个监测程序,让它每隔一段时间就给我发个邮件。


当然,你要设置一个监测条件。

比如我的主程序运行后会生成一些新文件,那么监测程序就每隔一段时间向我的邮箱报告一下现在生成了多少文件。

这样我在手机上就能知道主程序运行的怎么样了。


代码在:https://github.com/SunnyCat2013/useful-tools.git

使用注意事项:

1. 使用前,首先要有两个邮箱,一个用于发送信息,一个接收。当然这两个邮箱可以是同一个。

2. 然后修改程序里面的邮箱和邮箱密码。

3. 设置自己的发送间隔和发送信息等。


下面是一个简化的版本。


发信息的python程序:

# -*- coding:utf-8 -*-
# Author: cslzy
# Email: lizhenyang_2008@163.com
# Description:send something to someone.
# Date: 20151104 18:33:08
import smtplib
from email.mime.text import MIMEText as mt

# some information should be changed to you own
mail_host = "you email server such as: smtp.163.com" # set you mail host
host_user = "chang to you email address as a host, such as: lizhenyang_2008@163.com" # host to send email
host_password = "XXXXXthis is not useableXXXXXXchang to you own" # password of host

email_subject = "test message" # the subject of you email


reciever_address = "such as: lizhenyang_2008@163.com" #
send_message = "This is a test. oops..."



def sendTo(address, message):
    msg = mt(message, _subtype='plain')
    msg['Subject'] = email_subject
    msg['Form'] = host_user
    msg['To'] = address
    try:
        server = smtplib.SMTP()
        server.connect(mail_host)
        server.login(host_user, host_password)
        server.sendmail(host_user, address, msg.as_string())
        server.close()
        return True
    except Exception, e:
        print str(e)
        return False

if __name__ == '__main__':
    sendTo(reciever_address,send_message)


监测文件数量的程序:

# -*- coding:utf-8 -*-
# Author: cslzy
# Email: lizhenyang_2008@163.com
# Description: if the files number is enough, send email to me.
# Date: 20151104 18:52:45
from send_email import sendTo
import os
import time

flag = True

reciever_email = 'lizhenyang_2008@163.com' # you should change to you own
sleepy_time = 3 * 3600
print 'send message to %s every %d seconds'%(reciever_email, sleepy_time)

i = 0
while flag:
    i += 1
    print 'the %d\'th time to check'%i
    message = ''
    dirPath = '.'
    if os.path.exists(dirPath):
        listdir = os.listdir(dirPath)
        message += 'there are %d file in %s\n'%(len(listdir), dirPath)
    sendTo(reciever_email, message)
    # sleep
    time.sleep(sleepy_time)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值