標籤:smtp email postgresql python
代碼如下:
#!/usr/bin/env python
import smtplib
from email.mime.text import MIMEText
import psycopg2
import datetime
mail_host= "smtp.XXX.com" mail_user= "XXX" mail_pass= "XXX" mail_postfix="XXX.com"
def send_mail(to_list,sub,content): me="Remind Email"+"<"+mail_user+"@"+mail_postfix+">" msg = MIMEText(content,_subtype=‘plain‘,_charset=‘gb2312‘) msg[‘Subject‘] = sub msg[‘From‘] = me msg[‘To‘] = ";".join(to_list) try: server = smtplib.SMTP() server.CONNECT(mail_host) server.login(mail_user,mail_pass) server.sendmail(me, to_list, msg.as_string()) server.close() return True except Exception, e: print str(e) return False ## 取本地時間與資料庫專案時間作比較 ##today=strftime(‘%Y-%m-%d‘,localtime())today_date=datetime.datetime(today,‘%Y-%m-%d‘) ## 與postgresql資料庫連結 ## pgdb_conn = psycopg2.CONNECT(database = ‘test‘,user = ‘username‘, password = ‘123456‘, host = ‘1.1.1.1‘)pg_cursor = pgdb_conn.cursor()sql_desc = "select * from tbl_product3"pg_cursor.execute(sql_desc)for row in pg_cursor: date=row[0] to_list=row[1] sub=row[2] content=row[3] Other_date=datetime.datetime(date,‘%Y-%m-%d‘) delta=Other_date-today_date if delta.days == 1: send_mail(to_list,sub,content) pg_cursor.close() pgdb_conn.close()
本文出自 “藍鰭豚” 部落格,請務必保留此出處http://likunheng.blog.51cto.com/9527645/1569445
python讀取postgresql資料庫並發送相關提醒郵件