sendgrid email python 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='<p>My first mail using Sendgrid</p>'
        )
    
        try:
            sg = SendGridAPIClient('<SENDGRID_API_KEY>')
            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='<p>My first attachment sent with help of Sendgrid</p>'
        )
    
        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('<SENDGRID_API_KEY>')
            response = sg.send(message)
            print(response.status_code)
            print(response.body)
            print(response.headers)
        except Exception as e:
            #print(e.message)
            print(e)