Skip to content

Instantly share code, notes, and snippets.

@broland07
Created January 24, 2021 11:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save broland07/28c7e2601a6e7949d4eceb96fe9bc9f7 to your computer and use it in GitHub Desktop.
Save broland07/28c7e2601a6e7949d4eceb96fe9bc9f7 to your computer and use it in GitHub Desktop.
Make sure you have the SENDGRID_API_KEY environment variable set. (export SENDGRID_API_KEY="SG.xxxxxxxx")
import os
import base64
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import (Mail, Attachment, FileContent, FileName, FileType, Disposition)
message = Mail(
from_email='from@example.com',
to_emails='to@example.com',
subject='Attachment test',
html_content='<strong>Attachment test with Python</strong>'
)
with open('test.pdf', 'rb') as f:
data = f.read()
f.close()
encoded_file = base64.b64encode(data).decode()
attachedFile = Attachment(
FileContent(encoded_file),
FileName('test.pdf'),
FileType('application/pdf'),
Disposition('attachment')
)
message.attachment = attachedFile
sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
response = sg.send(message)
print(response.status_code, response.body, response.headers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment