mailsender.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. import datetime
  2. import smtplib
  3. import os
  4. import logging
  5. from sim.config import Configuration
  6. import ssl
  7. config = Configuration()
  8. class Emailer():
  9. def __init__(self, hostname, port, auth_user, auth_pass):
  10. self.hostname = hostname
  11. self.port = port
  12. self.auth_user = auth_user
  13. self.auth_pass = auth_pass
  14. self.logger = logging.getLogger(__name__)
  15. def read_template(self, filename):
  16. from string import Template
  17. with open(filename, 'r', encoding='utf-8') as template_file:
  18. template_file_content = template_file.read()
  19. return Template(template_file_content)
  20. def send_success_email(self, from_address, to_address, alert_message, subject, type=None, report_count=0):
  21. from email.mime.multipart import MIMEMultipart
  22. from email.mime.text import MIMEText
  23. self.logger.info("Preparando para enviar correo electrónico")
  24. head_color = "#6bab01"
  25. message_template = self.read_template(os.path.join(config.TEMPLATES_PATH,'success-message-inline.html'))
  26. message = message_template.substitute(fecha=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  27. alert_message=alert_message,
  28. cuenta_reportes=report_count,
  29. head_color=head_color)
  30. msg = MIMEMultipart()
  31. msg['From'] = from_address
  32. msg['To'] = to_address
  33. msg['Subject'] = subject
  34. msg.attach(MIMEText(message, 'html'))
  35. self.logger.debug("Conectando con el servidor SMTP: {0}".format(self.hostname))
  36. context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
  37. server = smtplib.SMTP(self.hostname, self.port)
  38. server.starttls(context=context)
  39. server.login(self.auth_user,self.auth_pass)
  40. self.logger.debug("Enviando correo electrónico")
  41. server.sendmail(msg['From'], msg['To'], msg.as_string())
  42. self.logger.debug("Correo Electrónico enviado")
  43. self.logger.debug("Desconectando del servidor SMTP")
  44. server.quit()
  45. self.logger.info("Correo electrónico enviado con éxito a la dirección {0}".format(to_address))
  46. def send_warning_email(self, from_address, to_address, alert_message, subject):
  47. from email.mime.multipart import MIMEMultipart
  48. from email.mime.text import MIMEText
  49. self.logger.info("Preparando para enviar correo electrónico")
  50. head_color = "#ffaa00"
  51. message_template = self.read_template(os.path.join(config.TEMPLATES_PATH, 'warning-message-inline.html'))
  52. message = message_template.substitute(fecha=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  53. alert_message=alert_message,
  54. head_color=head_color)
  55. msg = MIMEMultipart()
  56. msg['From'] = from_address
  57. msg['To'] = to_address
  58. msg['Subject'] = subject
  59. msg.attach(MIMEText(message, 'html'))
  60. self.logger.debug("Conectando con el servidor SMTP: {0}".format(self.hostname))
  61. context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
  62. server = smtplib.SMTP(self.hostname, self.port)
  63. server.starttls(context=context)
  64. server.login(self.auth_user,self.auth_pass)
  65. self.logger.debug("Enviando correo electrónico")
  66. server.sendmail(msg['From'], msg['To'], msg.as_string())
  67. self.logger.debug("Correo Electrónico enviado")
  68. self.logger.debug("Desconectando del servidor SMTP")
  69. server.quit()
  70. self.logger.info("Correo electrónico enviado con éxito a la dirección {0}".format(to_address))
  71. def send_success_email_by_api(self, from_address, to_address, alert_message, subject, type=None, report_count=0):
  72. import requests
  73. message_template = self.read_template(os.path.join(config.TEMPLATES_PATH,'success-message-inline.html'))
  74. self.logger.info("Preparando para enviar correo electrónico")
  75. head_color = "#6bab01"
  76. message = message_template.substitute(fecha=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  77. alert_message=alert_message,
  78. cuenta_reportes=report_count,
  79. head_color=head_color)
  80. url = config.SB_URL
  81. api_key = config.SB_API_KEY
  82. self.logger.debug("url: "+ url)
  83. self.logger.debug("key: "+ api_key)
  84. payload = {
  85. "sender":
  86. {
  87. "email":from_address,
  88. "name":"BOT DESCARGA DF"
  89. },
  90. "to":[{"email":to_address}],
  91. "htmlContent":message,
  92. "subject":subject
  93. }
  94. headers = {
  95. 'accept': "application/json",
  96. 'content-type': "application/json",
  97. 'api-key': api_key
  98. }
  99. self.logger.debug("Enviando correo electrónico")
  100. response = requests.request("POST", url, json=payload, headers=headers, verify=False)
  101. self.logger.debug("Correo Electrónico enviado")
  102. self.logger.info("Correo electrónico enviado con éxito a la dirección {0}".format(to_address))
  103. def send_warning_email_by_api(self, from_address, to_address, alert_message, subject):
  104. import requests
  105. message_template = self.read_template(os.path.join(config.TEMPLATES_PATH, 'warning-message-inline.html'))
  106. self.logger.info("Preparando para enviar correo electrónico")
  107. head_color = "#ffaa00"
  108. message = message_template.substitute(fecha=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  109. alert_message=alert_message,
  110. head_color=head_color)
  111. url = config.SB_URL
  112. api_key = config.SB_API_KEY
  113. self.logger.debug("url: "+ url)
  114. self.logger.debug("key: "+ api_key)
  115. payload = {
  116. "sender":
  117. {
  118. "email":from_address,
  119. "name":"BOT DESCARGA DF"
  120. },
  121. "to":[{"email":to_address}],
  122. "htmlContent":message,
  123. "subject":subject
  124. }
  125. headers = {
  126. 'accept': "application/json",
  127. 'content-type': "application/json",
  128. 'api-key': api_key
  129. }
  130. self.logger.debug("Enviando correo electrónico")
  131. response = requests.request("POST", url, json=payload, headers=headers, verify=False)
  132. self.logger.debug("Correo Electrónico enviado")
  133. self.logger.info("Correo electrónico enviado con éxito a la dirección {0}".format(to_address))