I am trying to send email from my server using nodemailer. Unfortuantely, I have been unabe to test it due to this error:
D:\Full Stack\Node\NodeLoginJWT\functions\password.js:58
'This token is valid only within two minutes.'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected string
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\Full Stack\Node\NodeLoginJWT\routes.js:9:18)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
[nodemon] app crashed - waiting for file changes before starting...
This is the code block causing the error:
const transporter = nodeMailer.createTransport(`smtps://${config.email}:${config.password}#smtp.gmail.com`);
const mailOptions = {
from: `"${conifg.name}" <${config.email}>`,
to: email,
subject: 'Reset Password',
html: `Hello ${user.name}`,
'Your account password token is ${random}'
'This token is valid only within two minutes.'
'Thanks,'
'Team. '
};
return transporter.sendMail(mailOptions);
I am using Nodemailer and here is my code:
var express = require('express');
var router = express.Router();
var nodemailer = require('nodemailer');
router.post('/', handleSendEmail); // handle the route at yourdomain.com/sayHello
function handleSendEmail(req, res) {
// Not the movie transporter!
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: '', // Your email id
pass: ‘’// Your password
}
});
var text = 'Hello from \n\n' + req.body.user_name;
var mailOptions = {
from: 'sender#gmail.com', // sender address
to: 'receiver#gmail.com', // list of receivers
subject: 'Appointment Email Example', // Subject line
text: text,
html: '<!DOCTYPE html>'+
'<html><head><title>Appointment</title>'+
'</head><body><div>'+
'<img src="http://evokebeautysalon1.herokuapp.com/main/img/logo.png" alt="" width="160">'+
'<p>Thank you for your appointment.</p>'+
'<p>Here is summery:</p>'+
'<p>Name: James Falcon</p>'+
'<p>Date: Feb 2, 2017</p>'+
'<p>Package: Hair Cut </p>'+
'<p>Arrival time: 4:30 PM</p>'+
'</div></body></html>'
};
transporter.sendMail(mailOptions, function(error, info){
if(error){
console.log(error);
res.json({yo: 'error'});
}else{
console.log('Message sent: ' + info.response);
res.json({yo: info.response});
};
});
}
module.exports = router;
I think there is a problem in your interpolation .
const mailOptions = {
from: `"${conifg.name}" <${config.email}>`,
to: email,
subject: 'Reset Password',
html: `Hello ${user.name}, // the tick should not come here
'Your account password token is ${random}'
'This token is valid only within two minutes.'
'Thanks,'
'Team. '` // the tick should come here
};
Related
I am extremely new to Azure Bot Services and the Azure platform as a whole.
I am trying to create a Chatbot using node.js but I am getting the below error while trying to connect to CosmosDB.
The bot was running fine before I added the below code to connect to CosmosDB.
Any help or guidance on this would be appreciated!
P.S. - I have added the '#azure/cosmos' package and the code runs without any error if I just remove the try-catch segment.
Code for connecting to CosmosDB:
var async=require("async");
var await=require("await");
const CosmosClientInterface = require("#azure/cosmos").CosmosClient;
const databaseId = "ToDoList";
const containerId = "custInfo";
const endpoint = "<Have provided the Endpoint URL here>";
const authKey = "<Have provided the AuthKey here>";
const cosmosClient = new CosmosClientInterface({
endpoint: endpoint,
auth: {
masterKey: authKey
},
consistencyLevel: "Session"
});
async function readDatabase() {
const { body: databaseDefinition } = await cosmosClient.database(databaseId).read();
console.log(`Reading database:\n${databaseDefinition.id}\n`);
}
Error Message:
Sat Jan 12 2019 03:40:08 GMT+0000 (Coordinated Universal Time): Application has thrown an uncaught exception and is terminated:
D:\home\site\wwwroot\app.js:40
async function readDatabase() {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\Program Files (x86)\iisnode\interceptor.js:459:1)
at Module._compile (module.js:570:32)
Application has thrown an uncaught exception and is terminated:
D:\home\site\wwwroot\app.js:40
async function readDatabase() {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\Program Files (x86)\iisnode\interceptor.js:459:1)
at Module._compile (module.js:570:32)
You can't await without being in an async function.
Dump all your code into a async function main(){} method, then call main().catch((err) => console.log(err)); or some similar thing to start the promise and handle errors.
You can see a sample of that kind of pattern here in this sample: https://github.com/Azure/azure-cosmos-js/blob/master/samples/ChangeFeed/app.js#L33
--- EDIT 1 ---
Here's your sample rewritten with Promises:
const CosmosClientInterface = require("#azure/cosmos").CosmosClient;
const databaseId = "ToDoList";
const containerId = "custInfo";
const endpoint = "<Have provided the Endpoint URL here>";
const authKey = "<Have provided the AuthKey here>";
const cosmosClient = new CosmosClientInterface({
endpoint: endpoint,
auth: {
masterKey: authKey
},
consistencyLevel: "Session"
});
cosmosClient.database(databaseId).read().then(({body: databaseDefinition}) => {
console.log(`Reading database:\n${databaseDefinition.id}\n`);
}).catch((err) {
console.err("Something went wrong" + err);
});
For your sample above, you don't need to import async/await, they are keywords in JavaScript now.
Here's a blog post that compares and contrasts Async/Await and Promises: https://hackernoon.com/should-i-use-promises-or-async-await-126ab5c98789
I want to add the push notification thing using FCM in Node.js .For that I tried this
and this and also this
My nodejs code
var FCM = require('fcm-node');
var serverkey = 'SERVERKEY';
var fcm = new FCM(serverkey);
var message = {
to : req.body.userToken,
collapse_key : 'XXX',
data : {
my_key: 'my value', contents: "abcv/"
},
notification : {
title : 'Title of the notification',
body : 'Body of the notification'
}
};
fcm.send(message, function(err,response){
if(err) {
console.log(message);
console.log("Something has gone wrong !");
} else {
console.log("Successfully sent with resposne :",response);
}
});
Whenever I try to run this code and start my server,I get this error in the console always.
/var/www/html/chatApp/node_modules/fcm-node/lib/fcm.js:10
function FCM(accountKey, proxy_url=null) {
^
SyntaxError: Unexpected token =
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/var/www/html/chatApp/node_modules/fcm-node/index.js:1:80)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
Can anybody please explain what I'm doing wrong?
I used the firebase-admin package for sending the notifications (https://firebase.google.com/docs/cloud-messaging/admin/send-messages)
var admin = require("firebase-admin");
var serviceAccount = require("./firebase-adminSDK.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
const messaging = admin.messaging()
var payload = {
notification: {
title: "This is a Notification",
body: "This is the body of the notification message."
},
topic: 'topic'
};
messaging.send(payload)
.then((result) => {
console.log(result)
})
The firebase-adminSDK.json can be download following the steps in https://firebase.google.com/docs/admin/setup#add_firebase_to_your_app
This code will send a notification to the topic 'topic', however, the firebase-admin package allows sending notifications to a specific device.
throw new Error(this.constructor.name + ' has been removed from this
version of the library. Please refer to
https://www.twilio.com/docs/libraries/node for more information.')
^ Error: RestClient has been removed from this version of the library. Please refer to https://www.twilio.com/docs/libraries/node
for more information.
at RestClient.ObsoleteClient (C:\carsapp\node_modules\twilio\lib\base\obsolete.js:7:9)
at new RestClient (C:\carsapp\node_modules\twilio\lib\base\obsolete.js:12:21)
at Object. (C:\carsapp\helpers\twilio_restful_client_connection.ts:6:34)
at Module._compile (module.js:643:30)
at Module.m._compile (C:\Users\Andrey Radkevich\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:422:23)
at Module._extensions..js (module.js:654:10)
at Object.require.extensions.(anonymous function) [as .ts] (C:\Users\Andrey
Radkevich\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:425:12)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Module.require (module.js:587:17)
at require (internal/module.js:11:18)
at Object. (C:\carsapp\helpers\sing-in-up-helper.ts:8:1)
at Module._compile (module.js:643:30)
at Module.m._compile (C:\Users\Andrey Radkevich\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:422:23)
at Module._extensions..js (module.js:654:10)
const accountSid = 'AC2a54bb2c4ea4992593cc9f0ca2f720c0';
const authToken = 'your_auth_token';
const Client = require('twilio').RestClient;
const client = new Client(accountSid, authToken);
client.outgoingCallerIds.create(
{
friendlyName: 'My Home Phone Number',
phoneNumber: '+14158675310',
},
(err, callerId) => {
if (err) {
console.error(err);
} else {
console.log(callerId.sid);
}
}
);
I have got this error when I tried to create this part of the code above. I tried to add a number to Twilio whitelist ( verify phone number).How can I make it in another way? I use for this Node js
Link on this part of the code in the documentation :
https://www.twilio.com/docs/api/voice/outgoing-caller-ids
const accountSid = 'AC2a54bb2c4ea4992593cc9f0ca2f720c0';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);
client.validationRequests
.create({
friendlyName: 'My Home Phone Number',
phoneNumber: '+14158675310',
})
.then(data => console.log(data.validationCode));
https://www.twilio.com/docs/api/voice/outgoing-caller-ids#add-an-outgoing-caller-id
Here answer on my own question
I am trying to create a email verification mailer following the example from here. I added both email-template and nodemailer packages. I made the transporter available as an adapter throughout my application. Below is the code for mailer.ts:
import * as mailer from 'nodemailer';
import * as dotenv from 'dotenv';
dotenv.load({ path: '.env' });
var mailConfig = {
host: process.env.MAIL_HOST,
port: process.env.MAIL_PORT,
auth: {
user: process.env.MAIL_USERNAME,
pass: process.env.MAIL_PASSWORD
}
};
var transporter = mailer.createTransport(mailConfig);
module.exports = transporter;
I am trying to build a wrapper around email-template like below signup.ts:
const EmailTemplate = require('email-templates');
var mailer = require('../mailer');
var sendEmailVerficationLink = mailer.templateSender(
new EmailTemplate({
views: { root: './verify' }
}), {
from: process.env.MAIL_FROM,
});
exports.sendVerficationLink = function (obj) {
sendEmailVerficationLink({
to: obj.email,
subject: 'Verify your Email'
}, {
name: obj.username,
token: obj.otp
}, function (err, info) {
if (err) {
console.log(err)
} else {
console.log('Sign up mail sent to ' + obj.email + ' for verification.');
}
});
};
In my actual controller, I try to send the mail as below user.ts:
var verify = require('../utils/mailer-templates/signup');
signup = (req, res) => {
..
verify.sendVerficationLink(obj); // send the actual user object
..
}
But I keep getting this error:
Error: Transport option must be a transport instance or configuration object
[1] at new Email (C:\Users\User\Documents\Vivavii-REST\node_modules\email-templates\lib\index.js:82:83)
[1] at Object.<anonymous> (C:\Users\User\Documents\Vivavii-REST\dist\utils\mailer-templates\signup.js:3:54)
[1] at Module._compile (module.js:641:30)
[1] at Object.Module._extensions..js (module.js:652:10)
[1] at Module.load (module.js:560:32)
[1] at tryModuleLoad (module.js:503:12)
[1] at Function.Module._load (module.js:495:3)
[1] at Module.require (module.js:585:17)
[1] at require (internal/module.js:11:18)
[1] at Object.<anonymous> (C:\Users\User\Documents\Vivavii-REST\dist\controllers\user.js:14:14)
[1] at Module._compile (module.js:641:30)
[1] at Object.Module._extensions..js (module.js:652:10)
[1] at Module.load (module.js:560:32)
[1] at tryModuleLoad (module.js:503:12)
[1] at Function.Module._load (module.js:495:3)
[1] at Module.require (module.js:585:17)
Main issue You used outdated example. In the example nodemailer has 2.7.2 version and unknown email-templates. Current nodemailer version is 4.4.1.
In the latest email-templates version you don't need directly work with nodemailer. You can pass configuration in transport params. Here is fixed version of your code:
const EmailTemplate = require('email-templates');
const dotenv = require('dotenv');
dotenv.load({ path: '.env' });
const emailTemplate = new EmailTemplate({
message: {
from: process.env.MAIL_FROM
},
transport: {
host: process.env.MAIL_HOST,
port: process.env.MAIL_PORT,
auth: {
user: process.env.MAIL_USERNAME,
pass: process.env.MAIL_PASSWORD
}
}
});
function sendVerficationLink(obj) {
return emailTemplate.send({
template: 'verify',
message: {
to: obj.email
},
locals: {
name: obj.username,
token: obj.otp
}
});
};
exports.sendVerficationLink = sendVerficationLink;
Some details:
mailer.ts is redundant
in project there is folder emails with templates. More infomation
Trying to send message to slack from Node.js app
I have used following package https://github.com/xoxco/node-slack
For Detailed reference full source code is in https://github.com/sudanvellakovilkanakavel/attendence-app
I couldn't understand
what is hook_url
How to define it
Error output
CJBTDLDD0003:backend kanaks$ node readingFile.js
/Users/kanaks/Desktop/backend/readingFile.js:2
var slack = new Slack(hook_url,options);
^
ReferenceError: hook_url is not defined
at Object.<anonymous> (/Users/kanaks/Desktop/backend/readingFile.js:2:23)
at Module._compile (module.js:410:26)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:442:10)
at startup (node.js:136:18)
at node.js:966:3
My Code
var Slack = require('node-slack');
var slack = new Slack(hook_url,options);
//var slack = new Slack(hook_url,{proxy: http_proxy});
//Trying to send message to slack from Node.js app
//I have used following package https://github.com/xoxco/node-slack
slack.send({
text: 'Meassage from node.js app to slack!',
channel: '#attendance',
username: 'Bot'
});
var fs = require("fs");
//reading the file
fs.readFile('Attendance01-04-2016.dat','utf8',function (err,data){
if (err) {
return console.error(err);
}
//spliting each line
var lines = data.split("\n");
//storeing in array and printing the file
for (i=0;i<=lines.length;)
{
console.log(lines[i]);
i=i+1;
}
});