Skip to content

Instantly share code, notes, and snippets.

@JasonOffutt
Last active September 8, 2018 00:50
Show Gist options
  • Save JasonOffutt/26e9c6347f4d46f0e62f1f2713c58e75 to your computer and use it in GitHub Desktop.
Save JasonOffutt/26e9c6347f4d46f0e62f1f2713c58e75 to your computer and use it in GitHub Desktop.
Thinking through how we might fetch email messages from google's api
const { google } = require('googleapis');
const moment = require('moment');
// Assuming we have authed against Google's API and we have permission...
const getRecentEmails = (auth, from, daysAgo = 14) => {
const gmail = google.gmail({ version: 'v1', auth });
const date = moment().subtract(daysAgo, 'days').format('YYYY/MM/DD');
gmail.users.messages.list({ userId: 'me', q: `label:inbox from:${from} newer:${date}` }, handleListResponse(gmail));
};
const handleListResponse = (gmail) => {
return (err, res) => {
if (err != null) {
console.error(err);
return;
}
const messages = res.data.messages;
if (!messages.length) {
console.log('no results found');
return;
}
messages.forEach(({ id }) => {
gmail.users.messages.get({ userId: 'me', id }, handleMessageResponse(gmail));
});
};
};
const fromHeader = (name, { headers }) => headers.find((header) => header.name === name);
const fromMimeType = (mimeType, { parts }) => parts.find((part) => part.mimeType === mimeType);
const fromBase64 = (string) => string != null ? Buffer.from(string, 'base64') : null;
const handleMessageResponse = (gmail) => {
return (err, res) => {
if (err != null) {
console.error(err);
return;
}
const { message } = res.data;
if (message == null) {
console.log('message not found');
return;
}
const { id, payload, snippet } = message;
// Dangerously assume email mimeType is multipart
const textBody = fromBase64(fromMimeType(payload, 'text/plain'));
const htmlBody = fromBase64(fromMimeType(payload, 'text/html'));
const subject = fromHeader(payload, 'subject');
const sentDate = fromHeader(payload, 'date');
console.log({
id,
snippet, // NOTE: snippet (preview text) comes accross the wire as plain text
subject,
sentDate,
textBody,
htmlBody,
});
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment