标签:为什么 header exe while -- server mail receive pytho
1. 自动任务的功能为:
定时扫描数据库中的记录,然后发邮件
代码如下
scheduleMail.py
import pymysql import smtplib from email.mime.text import MIMEText from email.header import Header import time def sendMail(body): sender = ‘xxx@163.com‘ receiver = [‘abc@xxx.com‘, ‘def@xxx.com‘, ‘ghi@xxx.com‘] subject = ‘邮件主题‘ smtpserver = ‘smtp.163.com‘ username = ‘your username‘ password = ‘your password‘ msg = MIMEText(body,‘plain‘,‘utf-8‘) #中文需参数‘utf-8‘,单字节字符不需要 msg[‘Subject‘] = Header(subject, ‘utf-8‘) msg[‘From‘] = ‘xxx<xxx@163.com>‘ msg[‘To‘] = "abc@xxx.com‘, ‘def@xxx.com‘, ‘ghi@xxx.com" smtp = smtplib.SMTP() smtp.connect(‘smtp.163.com‘) smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit() def scanLogic(): conn = pymysql.connect(host=‘服务器IP‘, user=‘数据库用户名‘, passwd=‘数据库密码‘, db=‘数据库名‘, port=3306, charset=‘utf8‘) cur = conn.cursor() sql = "select * from ..." cur = conn.cursor() cur.execute(sql) alldata = cur.fetchall() mailBody = "" separator = "----------------------------------------------\n" for rec in alldata: field1 = rec[0] field2 = rec[1] line = "field1: %s \t field2: %s \n" % (field1, field2) mailBody = mailBody + line + separator print(‘邮件正文: %s‘ % mailBody) if (mailBody != ""): sendMail(mailBody) else: print("无可发送邮件") def main(): while (True): time.sleep(1800) scanLogic() main()
2. 把它做成后台任务的shell脚本如下
scheduleMail.sh
#!/bin/bash cd /home/yourfolder python -u scheduleMail.py
3. 如何杀死后台任务
这里有个坑,很多网上的博客没有说,我在这里提一下,以免大家重复去踩。
杀死该任务,就像杀死传统Linux进程一样
利用python制作在Linux服务器后台定时运行的任务-邮件提醒
标签:为什么 header exe while -- server mail receive pytho
原文地址:http://www.cnblogs.com/davidgu/p/7617102.html