-
Notifications
You must be signed in to change notification settings - Fork 0
/
send_mail.js
74 lines (61 loc) · 2.13 KB
/
send_mail.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*jshint esversion: 6*/
var fs = require('fs');
const {google} = require('googleapis');
function getOAuth2Client(cb) {
fs.readFile('authKeys.json', function(err,data) {
if(err) {
return cb(err);
}
var credentials = JSON.parse(data);
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var oauth2Client = new google.auth.OAuth2(clientId, clientSecret, redirectUrl);
//Load authentication data
fs.readFile('authenticationTokenFile.json', function(err,token) {
if(err) {
return cb(err);
}
else {
oauth2Client.credentials = JSON.parse(token);
return cb(null, oauth2Client);
}
});
});
}
function sendSampleMail(auth,cb) {
var gmailClass = google.gmail('v1');
var email_Lines = [];
email_Lines.push('From: "<your identity goes here>" <[email protected]>');
email_Lines.push('To: receivers gmail address');
email_Lines.push('Content-type: text/html;charset=iso-8859-1');
email_Lines.push('MIME-Version: 1.0');
email_Lines.push('Subject: <subject here>');
email_Lines.push('');
email_Lines.push('A sample body which is to be written and edited using HTML.');
var email = email_Lines.join('\r\n').trim();
var base64EncodedEmail = new Buffer(email).toString('base64');
base64EncodedEmail = base64EncodedEmail.replace(/\+/g, '-').replace(/\//g, '-');
gmailClass.users.messages.send({
auth: auth,
userId: 'me',
resource: {
raw: base64EncodedEmail
}
}, cb);
}
getOAuth2Client(function(err, oauth2Client) {
if(err) {
console.log('err: ',err);
}
else {
sendSampleMail(oauth2Client, function(err, results) {
if(err) {
console.log('err: ',err);
}
else {
console.log(results);
}
});
}
});