email_utils.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # using SendGrid's Python Library
  2. # https://github.com/sendgrid/sendgrid-python
  3. from email.message import EmailMessage
  4. from smtplib import SMTP
  5. from sendgrid import SendGridAPIClient
  6. from sendgrid.helpers.mail import Mail
  7. from app.config import SUPPORT_EMAIL, SENDGRID_API_KEY, NOT_SEND_EMAIL
  8. from app.log import LOG
  9. def send_by_sendgrid(to_email, subject, html_content, plain_content=None):
  10. # On local only print out email content
  11. if NOT_SEND_EMAIL:
  12. LOG.d(
  13. "send mail to %s, subject:%s, content:%s", to_email, subject, html_content
  14. )
  15. return
  16. if not plain_content:
  17. plain_content = subject
  18. message = Mail(
  19. from_email=SUPPORT_EMAIL,
  20. to_emails=to_email,
  21. subject=subject,
  22. html_content=html_content,
  23. plain_text_content=plain_content,
  24. )
  25. sg = SendGridAPIClient(SENDGRID_API_KEY)
  26. response = sg.send(message)
  27. LOG.d("sendgrid res:%s, email:%s", response.status_code, to_email)
  28. def send_by_postfix(to_email, subject, content):
  29. # host IP, setup via Docker network
  30. smtp = SMTP("1.1.1.1", 25)
  31. msg = EmailMessage()
  32. msg["Subject"] = subject
  33. msg["From"] = SUPPORT_EMAIL
  34. msg["To"] = to_email
  35. msg.set_content(content)
  36. smtp.send_message(msg, from_addr=SUPPORT_EMAIL, to_addrs=[to_email])
  37. def notify_admin(subject, html_content=""):
  38. send_by_postfix(SUPPORT_EMAIL, subject, html_content)