Created
April 8, 2021 14:23
-
-
Save raymondberg/6c20611551fb6bc2c594de6808e287ae to your computer and use it in GitHub Desktop.
Simple, full-featured sendgrid email sending
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from send import send_email | |
def main(sandbox_mode=True): | |
send_email( | |
to_emails=["[email protected]"], | |
from_email="my@email", | |
subject="Catchup", | |
html_content="Hello Umm Greg Universe,<br/>How are you?", | |
cc_emails=["an-email"], | |
reply_to=("[email protected]", "Me"), | |
sandbox_mode=sandbox_mode, | |
) | |
if __name__ == "__main__": | |
main(sandbox_mode=True) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sendgrid | |
from sendgrid.helpers.mail import ( | |
Content, | |
Email, | |
Mail, | |
MailSettings, | |
Personalization, | |
ReplyTo, | |
SandBoxMode, | |
) | |
def send_email( | |
to_emails, | |
from_email, | |
subject, | |
html_content, | |
sandbox_mode=True, | |
cc_emails=None, | |
bcc_emails=None, | |
reply_to=None, | |
): | |
""" | |
before using, configure environment variables | |
SENDGRID_MAIL_FROM={your-mail-from} | |
SENDGRID_API_KEY={your-sendgrid-api-key}. | |
""" | |
mail = Mail() | |
mail.from_email = Email(from_email) | |
if reply_to: | |
mail.reply_to = ReplyTo(*reply_to) | |
mail.subject = subject | |
mail.mail_settings = MailSettings() | |
if sandbox_mode: | |
print("SANDBOX MODE") | |
mail.mail_settings.sandbox_mode = SandBoxMode(enable=True) | |
personalization = Personalization() | |
for to_address in to_emails: | |
personalization.add_to(Email(to_address)) | |
if cc_emails: | |
for cc_address in cc_emails: | |
personalization.add_cc(Email(cc_address)) | |
if bcc_emails: | |
for bcc_address in bcc_emails: | |
personalization.add_bcc(Email(bcc_address)) | |
mail.add_personalization(personalization) | |
mail.add_content(Content("text/html", html_content)) | |
_post_sendgrid_mail(mail.get()) | |
def _post_sendgrid_mail(mail_data): | |
sg = sendgrid.SendGridAPIClient(api_key=os.getenv("SENDGRID_API_KEY")) | |
response = sg.client.mail.send.post(request_body=mail_data) | |
if response.status_code >= 200 and response.status_code < 300: | |
print( | |
"Email with subject {subject} was successfully sent to recipients: {personalizations}".format( | |
**mail_data | |
) | |
) | |
else: | |
print( | |
f"Failed to send out email with subject {mail_data['subject']}, status code: {response.status_code}" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment