gmail-getter
Version:
A simple tool that gets emails from the Gmail API
39 lines (38 loc) • 1.36 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchEmailById = void 0;
const axios_1 = __importDefault(require("axios"));
/**
* Get an email by its id
* @param {string} id Unique ID of the email
* @param {string} token OAuth Access token
* @returns {Promise<Email>} Email contents
* @example const email = await fetchEmailById('123456a123b1c1d1', 'ya01.a123456...')
*/
const fetchEmailById = async (id, token) => {
const config = {
method: 'get',
url: `https://gmail.googleapis.com/gmail/v1/users/me/messages/${id}`,
timeout: 15000,
headers: { Authorization: `OAuth ${token}` },
params: new URLSearchParams([['format', 'full']]),
};
let response;
try {
response = await axios_1.default.request(config);
}
catch (e) {
throw new Error(`Failed to fetch the email - API request to Google has failed.
\n${JSON.stringify(e, null, 2)}`);
}
const { data: body } = response;
if (!body) {
throw new Error(`Failed to fetch the email - unable to parse response body.
\n${JSON.stringify(response, null, 2)}`);
}
return body;
};
exports.fetchEmailById = fetchEmailById;