You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sendgrid.py 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import logging
  2. import sendgrid # type: ignore
  3. from python_http_client.exceptions import ForbiddenError, UnauthorizedError
  4. from sendgrid.helpers.mail import Content, Email, Mail, To # type: ignore
  5. class SendGridClient:
  6. def __init__(self, sendgrid_api_key: str, _from: str):
  7. self.sendgrid_api_key = sendgrid_api_key
  8. self._from = _from
  9. def send(self, mail: dict):
  10. logging.debug("Sending email with SendGrid")
  11. try:
  12. _to = mail["to"]
  13. if not _to:
  14. raise ValueError("SendGridClient: Cannot send email: recipient address is missing.")
  15. sg = sendgrid.SendGridAPIClient(api_key=self.sendgrid_api_key)
  16. from_email = Email(self._from)
  17. to_email = To(_to)
  18. subject = mail["subject"]
  19. content = Content("text/html", mail["html"])
  20. mail = Mail(from_email, to_email, subject, content)
  21. mail_json = mail.get() # type: ignore
  22. response = sg.client.mail.send.post(request_body=mail_json)
  23. logging.debug(response.status_code)
  24. logging.debug(response.body)
  25. logging.debug(response.headers)
  26. except TimeoutError as e:
  27. logging.exception("SendGridClient Timeout occurred while sending email")
  28. raise
  29. except (UnauthorizedError, ForbiddenError) as e:
  30. logging.exception(
  31. "SendGridClient Authentication failed. "
  32. "Verify that your credentials and the 'from' email address are correct"
  33. )
  34. raise
  35. except Exception as e:
  36. logging.exception(f"SendGridClient Unexpected error occurred while sending email to {_to}")
  37. raise