您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

sendgrid.py 1.7KB

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