Created
September 1, 2021 15:24
-
-
Save palnabarun/a42d88c6745f0dee25c04e383e907cc2 to your computer and use it in GitHub Desktop.
Example to send email using SendGrid API to multiple recipients
This file contains 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
<h2>Hi!</h2> | |
<p>This is a very important email!</p> | |
<h3>Thank you!</h3> |
This file contains 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 | |
from sendgrid import SendGridAPIClient | |
from sendgrid.helpers.mail import Mail | |
# Edit the following | |
RECIPIENTS_FILE = 'recipients.txt' | |
CONTENT_FILE = 'content.html' | |
SENDER = 'foo@bar.com' | |
SUBJECT = 'This is an interesting email!' | |
def read_recipient_emails(filename): | |
with open(filename) as f: | |
return [l.strip() for l in f.readlines()] | |
def read_content(filename): | |
with open(filename) as f: | |
return f.read() | |
def send_email(recipient, subject, content): | |
print('sending email to {}'.format(recipient)) | |
message = Mail( | |
from_email=SENDER, | |
to_emails=recipient, | |
subject=subject, | |
html_content=content | |
) | |
try: | |
sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) | |
response = sg.send(message) | |
print(response.status_code) | |
print(response.body) | |
print(response.headers) | |
except Exception as e: | |
print(e.message) | |
def main(): | |
recipients = read_recipient_emails(RECIPIENTS_FILE) | |
content = read_content(CONTENT_FILE) | |
for recipient in recipients: | |
send_email(recipient, SUBJECT, content) | |
if __name__ == "__main__": | |
main() |
This file contains 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
baz@quu.com |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment