python sending email with sendgrid with attachment code example

Example 1: python sending email with sendgrid

from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import (Mail, Attachment, FileContent, FileName, FileType, Disposition)

message = Mail(
        from_email='[email protected]',
        to_emails='[email protected]',
        subject='Sending email with Sengrid',
        html_content='

My first mail using Sendgrid

' ) try: sg = SendGridAPIClient('') response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: #print(e.message) print(e)

Example 2: python sending email with sendgrid with attachment

import base64

from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import (Mail, Attachment, FileContent, FileName, FileType, Disposition)

message = Mail(
        from_email='[email protected]',
        to_emails='[email protected]',
        subject='Sending email with attachment with Sengrid',
        html_content='

My first attachment sent with help of Sendgrid

' ) with open('attachment.pdf', 'rb') as f: data = f.read() f.close() encoded_file = base64.b64encode(data).decode() attachedFile = Attachment( FileContent(encoded_file), FileName('attachment.pdf'), FileType('application/pdf'), Disposition('attachment') ) message.attachment = attachedFile try: sg = SendGridAPIClient('') response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: #print(e.message) print(e)

Tags:

Misc Example