How To Send Attachment In Sendgrid

If you are looking to send various types of files such as reports, PDFs, or images, it is essential to understand how to utilize SendGrid’s API to attach these files. This article will guide you through the process of attaching a file to an email with SendGrid’s API.

Setting up

Before we get started, make sure you have an active SendGrid account and your API key handy. If you don’t have these yet, you can create an account on SendGrid’s website and create your API key from your account dashboard.

Attach a File Using SendGrid’s Mail Send API

To attach a file to an email using SendGrid’s API, we use the ‘attachments’ parameter. Each attachment must include three properties: ‘content’, ‘type’, and ‘filename’. ‘Content’ is the file content encoded in base64, ‘type’ is the MIME type of the file, and ‘filename’ is the name that will appear in the email.

First, let’s start with a simple mail sending function using the SendGrid API:

        const sgMail = require('@sendgrid/mail');
        sgMail.setApiKey(process.env.SENDGRID_API_KEY);
        const msg = {
            to: '[email protected]', 
            from: '[email protected]', 
            subject: 'Hello world',
            text: 'Hello plain world!',
            html: '</p><p>Hello HTML world!</p>',
        };
        sgMail.send(msg);
        

This is a basic email sending function. Now let’s add an attachment to it.

        const fs = require('fs');
        const path = require('path');
        const attachment = fs.readFileSync(path.resolve('path/to/your/file.pdf')).toString('base64');
        msg.attachments = [{
            content: attachment,
            filename: 'file.pdf',
            type: 'application/pdf',
            disposition: 'attachment'
        }];
        sgMail.send(msg);
        

In the above example, we read the file using Node.js’s fs module and convert it to base64. Then, we add it to ‘msg.attachments’. ‘file.pdf’ is the name that will be displayed in the email. The ‘type’ is ‘application/pdf’, which is the MIME type for PDF files. The ‘disposition’ is set to ‘attachment’ to indicate that this file should be downloaded rather than displayed inline.

Conclusion

Sending email attachments using SendGrid’s API is not difficult once you understand the process. Remember to encode your file in base64 and to specify the MIME type correctly. Happy emailing!