Skip to content

Instantly share code, notes, and snippets.

@mdawaffe
Last active January 25, 2017 05:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdawaffe/f4c026ae6bbfe66499b1 to your computer and use it in GitHub Desktop.
Save mdawaffe/f4c026ae6bbfe66499b1 to your computer and use it in GitHub Desktop.
Gmail OAuth2 Transport for Nodemailer
config.json
.credentials
node_modules

Gmail OAuth2 Transport for Nodemailer

Nodemailer Transport for Sending Email or Creating Drafts with Gmail via OAuth2 Credentials.

For authentication example and bin script, see send-gmail.

Config

config.json

{
	"google": {
		"CLIENT_ID": "...",
		"CLIENT_SECRET": "...",
		"REDIRECT_URL": "urn:ietf:wg:oauth:2.0:oob"
		"RESTRICT_AUTH_DOMAIN" : "my-google-apps-domain.com", // optional
	}
}
var Google = Google = require( 'googleapis' );
/**
* options:
* client: (Google.auth.OAuth2) required. OAuth2 client for communicating with the Gmail API.
* Should already have credentials set.
* draft: (boolean) default=false. True to save a draft instead of sending an email
*/
function GmailTransport( options ) {
if ( ! ( this instanceof GmailTransport ) ) {
return new GmailTransport( options );
}
this.options = options || {};
this.name = 'Gmail';
this.version = '0.0.1';
this._gmail = Google.gmail( { version: 'v1', auth: options.client } )
}
GmailTransport.prototype.send = function( mail, callback ) {
// Build the message with the BCC header
mail.message.keepBcc = true;
if ( this.options.error ) {
setImmediate( function() {
callback( new Error( this.error ) );
}.bind( this ) );
return;
}
var message = mail.message.createReadStream();
var info = {
messageId: ( mail.message.getHeader( 'message-id' ) || '' ).replace( /[<>\s]/g, '' ),
envelope: mail.data.envelope || mail.message.getEnvelope(),
account: this.options.client.credentials.email
};
var send = this.options.draft ? this._gmail.users.drafts.create : this._gmail.users.messages.send;
send( {
userId: "me",
media: {
mimeType: "message/rfc822",
body: message
}
}, function( err, response ) {
info.response = response;
callback( err, info );
} );
};
module.exports = GmailTransport;
{
"name": "nodemailer-gmail-oauth2-transport",
"version": "0.0.5",
"description": "Nodemailer Transport for Sending Email or Creating Drafts with Gmail via OAuth2 Credentials.",
"main": "nodemailer-gmail-oauth2-transport.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "mdawaffe",
"license": "GPL2+",
"dependencies": {
"googleapis": "2.1.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment