1. # -*- coding: utf-8 -*-
  2. import datetime
  3. import sys,time
  4. import sys
  5. from odps import options
  6. import smtplib
  7. from email.header import Header
  8. from email.mime.text import MIMEText
  9. # 设置编码(此设置可修复数据库查询结果中文乱码的问题)
  10. reload(sys)
  11. sys.setdefaultencoding(\'utf-8\')
  12. # 第三方 SMTP 服务
  13. # SMTP服务器
  14. mail_host = "smtp.126.com"
  15. # 用户名
  16. mail_user = "123@126.com"
  17. # 授权密码,非登录密码
  18. mail_pass = "123456"
  19. # 发件人邮箱(最好写全, 不然会失败)
  20. sender = \'123@126.com\'
  21. # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
  22. receivers = [\'abc@qq.com\',\'bcd@qq.com\']
  23. # 邮件主题
  24. title = \'邮件标题\'
  25. # 发送邮件方法
  26. def sendEmail(content):
  27. # 内容, 格式, 编码
  28. message = MIMEText(content, \'plain\', \'utf-8\')
  29. message[\'From\'] = "{}".format(sender)
  30. message[\'To\'] = ",".join(receivers)
  31. message[\'Subject\'] = title
  32. try:
  33. # 启用SSL发信, 端口一般是465
  34. smtpObj = smtplib.SMTP_SSL(mail_host, 465)
  35. # 登录验证
  36. smtpObj.login(mail_user, mail_pass)
  37. # 发送
  38. smtpObj.sendmail(sender, receivers, message.as_string())
  39. print("mail has been send successfully.")
  40. except smtplib.SMTPException as e:
  41. print(e)
  42. # 设置ODPS参数
  43. options.sql.settings = {\'odps.sql.allow.fullscan\': \'true\'}
  44. qcc_sql = """
  45. SELECT DISTINCT * FROM
  46. (
  47. SELECT
  48. case WHEN flag1=1 then \'正常\'
  49. ELSE concat(db_name,\'中文乱码测试\') end as result
  50. FROM
  51. (select
  52. t2.db_name,t2.code,COUNT(1) as flag1
  53. from ods_com_t_organization t2
  54. where t2.is_company=1
  55. and t2.is_deleted=0
  56. AND nvl(t2.code,\'\')!=\'\'
  57. group by t2.db_name,t2.code
  58. )t1
  59. )t3
  60. WHERE result != \'正常\'
  61. ;
  62. """
  63. # 查询SQL获取结果
  64. resdata = []
  65. with o.execute_sql(qcc_sql).open_reader() as reader:
  66. resdata = [record.values for record in reader]
  67. # 判断结果是否有数据,如无则正常,如有则发送邮件并报错退出
  68. if resdata == []:
  69. print("数据正常")
  70. else:
  71. result = "|".join(resdata[0])
  72. print(result)
  73. sendEmail(result)
  74. sys.exit(-1)

 

版权声明:本文为chenzechao原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/chenzechao/p/12501876.html