Download All Inbox Attachments

This is a step by step coding guide for downloading all of the attachments in a Mailsac email inbox.

Prerequisites

Setup

Choose a folder to work in, and navigate to the folder in your terminal.

Configure the npm package.json:

npm init -y
npm install --save request request-promise-native

Create a file:

touch download-inbox-attachments.js

Now open the .js file and put the following code in. Change the string value of MAILSAC_API_KEY from ‘YOUR API KEY GOES HERE’ to your actual API key.

const fs = require('fs')
const request = require('request');
const requestp = require('request-promise-native')

const MAILSAC_API_KEY = 'YOUR API KEY GOES HERE';
const address = process.argv[2];

requestp(`https://mailsac.com/api/addresses/${address}/messages`, {
        json: true,
        headers: {
            'Mailsac-Key': MAILSAC_API_KEY
        },
    })
    .then((messages) => {
        console.log(`fetched ${messages.length} messages for ${address}`);

        messages.forEach((message) => {
            if (!message.attachments) {
                console.log(`${message.subject.substring(0, 10)}... ${message._id} - has no attachments`);
                return
            }
            if (message.attachments) {
                console.log(`${message.subject.substring(0, 10)}... ${message._id} - has ${message.attachments.length} attachments`);
                message.attachments.forEach((checksum) => {
                    const file = fs.createWriteStream(`${checksum}.eml`);
                    request(`https://mailsac.com/api/addresses/${address}/messages/${message._id}/attachments/${checksum}`)
                        .pipe(file);
                });
            }
        });
    })
    .catch((err) => {
        console.error('Something broke!', err.message, err.stack);
    });

The script can be run in the terminal like this:

node download-inbox-attachments.js address@mailsac.com

This Node script does a few things:

  1. Takes takes the email address ‘address@mailsac.com’ as an input argument. You can change this to any email address.
  2. It fetches the metadata for all messages in the inbox address@mailsac.com.
  3. It loops through the list of messages and prints part of the subject, the unique message identifier, and how many attachments it has.
  4. When messages have attachments, the attachment is downloaded into the current folder, using it’s MD5 checksum as an identifier.

That’s it! Read more about message attachment APIs in the docs.