How To Send Attachment In Mail Using Sendgrid

SendGrid offers a variety of features and one of them includes the option to send emails with attachments. With SendGrid, it is easy to send different types of files such as PDFs and images. This blog post provides a detailed tutorial on how to send attachments through SendGrid.

Prerequisites

Before you start, make sure you have the following:

  • An account with SendGrid. If you don’t have one and you need to create it, you can do so here.
  • SendGrid’s Python library installed. You can install it using pip by typing the following command in your terminal:
pip install sendgrid

Steps to Send an Attachment with SendGrid

Once you have the prerequisites ready, follow these steps to send an email with an attachment using SendGrid:

Step 1: Import SendGrid’s mail package

Start by importing SendGrid’s mail package in your Python script:

import sendgrid
from sendgrid.helpers.mail import Mail

Step 2: Create a new message

Next, you will need to create a new message. You will need to specify the sender’s email address, the recipient’s email address, the subject of the email, and the content of the email:

message = Mail(
    from_email='[email protected]',
    to_emails='[email protected]',
    subject='Sending with SendGrid is Fun',
    plain_text_content='and easy to do anywhere, even with Python')

Replace [email protected] and [email protected] with your own email addresses.

Step 3: Attach a file

To attach a file to the email, you will need to read the file in binary mode, encode it in base64, and then add it to the message. You can do this using SendGrid’s Attachment and FileContent helper classes:

import base64
from sendgrid.helpers.mail import Attachment, FileContent, FileName, FileType, Disposition

with open('example.pdf', 'rb') as f:
    data = f.read()
    f.close()
encoded = base64.b64encode(data).decode()

attachedFile = Attachment(
    FileContent(encoded),
    FileName('example.pdf'),
    FileType('application/pdf'),
    Disposition('attachment')
)
message.attachment = attachedFile

Replace ‘example.pdf’ with the path to the file you want to attach.

Step 4: Send the email

Finally, you can send the email by creating a new instance of SendGrid’s SendGridAPIClient and calling the send() method:

sg = sendgrid.SendGridAPIClient('SENDGRID_API_KEY')
response = sg.send(message)
print(response.status_code)

Replace ‘SENDGRID_API_KEY’ with your own SendGrid API key.

Conclusion

And that’s it! You have just sent an email with an attachment using SendGrid. As you can see, SendGrid’s Python library makes it easy to send emails with attachments. You can use this feature to send any type of file to your users, making it a great tool for a variety of use cases.