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