1const express = require('express')
2const {google} = require('googleapis');
3const path = require('path');
4const nodemailer = require('nodemailer');
5
6
7const router=express.Router()
8
9
10
11
12
13
14const creds={
15 client_email:"email1@gmail.com",
16 client_id:"client_id",
17 client_secret:"your client secret",
18 serveruri: "http://localhost:4000",
19 uirui: "http://localhost:3000",
20 redirectURL: "http://localhost:4000/auth/creds",
21 access_token: 'your access token',
22 refresh_token: 'your refresh token',
23
24}
25
26const oauth2Client = new google.auth.OAuth2(
27 creds.client_id,
28 creds.client_secret,
29 creds.redirectURL
30);
31const scopes = [
32 'https://mail.google.com/'
33];
34
35
36const sendMail=async()=>{
37 try{
38
39 const transport = nodemailer.createTransport({
40 service: 'gmail',
41 auth: {
42 type: 'OAuth2',
43 user:creds.client_email,
44 clientId: creds.client_id,
45 clientSecret: creds.client_secret,
46 accessToken: creds.access_tokenfb,
47
48 },
49 });
50
51
52
53 const mailOptions = {
54 from: `FRONT <${creds.client_email}>`,
55 to: "email2@gmail.com",
56 subject: `[FRONT]- Here is your e-Book!`,
57 html: `Enjoy learning!`,
58
59 };
60
61
62 const result = await transport.sendMail(mailOptions);
63 console.log("success === ",result)
64 return result;
65
66 } catch (error) {
67 console.log("error sendng mail === ",error)
68 return error;
69 }
70}
71
72
73router.get('/',async(req,res)=>{
74 console.log("hit auth route")
75res.send("auth route")
76
77})
78
79
80
81
82router.get('/google',async(req,res)=>{
83
84const url = oauth2Client.generateAuthUrl({
85
86 access_type: 'offline',
87
88 scope: scopes
89})
90console.log("url returned ======= ",url)
91
92if(url){
93
94res.render('authorize',{url:url})
95}
96})
97
98
99
100
101router.get('/creds',async(req,res)=>{
102
103const code = req.query.code
104console.log("query ==== ",code)
105
106const {tokens} = await oauth2Client.getToken(code)
107console.log("query token response==== ",tokens)
108
109
110
111oauth2Client.setCredentials(tokens);
112
113
114res.render('done')
115
116})
117
118
119
120
121router.get('/mail',async(req,res)=>{
122let email=""
123await sendMail().then((result)=>email=result).catch((err)=>email=err)
124console.log("email sent or error === ",email)
125
126await res.json(email)
127
128
129})
130
131
132module.exports=router