Nodemailer Email sending not working - meanjs

I'm trying to send an email from my application. I tried the below code. Can someone please help me where I'm wrong?
When I'm submitting my form, I'm not getting any error. But, I'm not able to get the email on the recipient side.
Thank you
'use strict';
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
// host: 'smtp.gmail.com',
service: "Gmail",
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: 'xyz#gmail.com',
pass: '**********'
}
});
/**
* Module dependencies.
*/
var path = require('path'),
mongoose = require('mongoose'),
Enquire = mongoose.model('Enquire'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
_ = require('lodash');
exports.sendMail = function(req, res) {
var data = req.body;
rand=Math.floor((Math.random() * 100) + 54);
host=req.get('host');
console.log("send MailData :: " + data)
var link="http://"+req.get('host')+"/verify?id="+rand;
var mailOptions={
from: data.contactEmail,
to : 'abc#gmail.com',
subject : "Please confirm your Email account",
html : "Hello,<br> This is your test email for the Inquiry Form."
}
console.log(mailOptions);
transporter.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.end("error");
}else{
console.log("Message sent: " + response.message);
res.end("sent");
}
});
res.json(data);
};

Related

Connection closed unexpectedly: Nodemailer

const express = require('express');
const app = express();
const nodemailer = require('nodemailer');
//Middleware
app.use(express.static('frontend'));
app.use(express.json());
app.get('/',(req,res)=>{
res.sendFile(__dirname + '/frontend/index.html');
});
app.post('/', (req,res)=>{
console.log(req.body);
const transporter1 = nodemailer.createTransport({
service:"gmail",
host: "smtp.gmail.com", // hostname
secure: false, // use SSL
port: 587, // port for secure SMTP
auth: {
user: "my email id",
pass: "mypassword"
},
tls: {
ciphers: "SSLv3",
rejectUnauthorized: false,
},
});
const mailOptions = {
from:req.body.email,
to: 'prahlad.hsrao#gmail.com',
cc: '24septanjali#gmail.com',
subject: 'Form Information',
text:"firstName: "+ req.body.fname+"\n" + "lastName"+req.body.lname+"email" + req.body.email+"phone"+req.body.phone+"message"+req.body.message,
}
transporter1.sendMail(mailOptions,(error,info)=>{
if(error){
console.log(error);
res.send('error');
transporter1.close();
}
else{
console.log('Email sent' + info.response);
res.send('success');
res.redirect('/');
transporter1.close();
}
})
})
app.listen(3000,()=>console.log('Server started...'));
firstly it was working perfectly, I send the email successfully 5-6 time, then while trying to send the mail, it is giving following error.
Error: Connection closed unexpectedly
at SMTPConnection._onClose (D:\official\SendEmailProject\nodeContactForm\node_modules\nodemailer\lib\smtp-connection\index.js:827:34)
at TLSSocket.SMTPConnection._onSocketClose (D:\official\SendEmailProject\nodeContactForm\node_modules\nodemailer\lib\smtp-connection\index.js:193:42)
at Object.onceWrapper (node:events:628:26)
at TLSSocket.emit (node:events:525:35)
at node:net:757:14
at TCP.done (node:_tls_wrap:584:7) {
code: 'ECONNECTION',
command: 'CONN'
I also got this error. After searching I guess it's a problem with the email server. I got about 5% of all my auto emails to fail. Maybe we can try to change one.

message": "Webhook call failed. Error: UNAVAILABLE, State: URL_UNREACHABLE, Reason: UNREACHABLE_5xx, HTTP status code: 500." in dialogflow fulfillment

I am trying to send email using dialogflow intents from my gmail. But it throws the same error every time and I am unable to understand the issue behind this. The same thing stand alone from my code is able to send emaail to various email addresses. So i guess the code works just fine . Please have a look at my code .
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const nodemailer = require("nodemailer");
const admin = require("firebase-admin");
const axios = require("axios");
admin.initializeApp({
credential:admin.credential.applicationDefault(),
databaseUrl:'ws://***************/'
});
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function welcome(agent) {
agent.add(`Welcome to my agent!`);
}
function fallback(agent) {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
function emailSend(){
const email= agent.parameters.email;
const name= agent.parameters.name;
const subject= agent.parameters.subject;
const message = agent.parameters.message;
}
const nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '*****#gmail.com',
pass: '***********'
}
});
var mailOptions = {
from: 'Mamuni',
to: 'email' ,
subject: 'subject' ,
text: 'message'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
let intentMap = new Map();
intentMap.set('emailSend',emailSend);
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
agent.handleRequest(intentMap);
});
The error probably is indicative that your code is not reachable or probably not being served via a HTTPS endpoint. I suggest the following:
Is the code available over a publicly accessible endpoint?
If the above is yes, is it being served over a secure channel i.e. HTTPS?

I have a form page that I want to send emails from but

function Getqueryandsend(){
alert("!")
const params = new URLSearchParams(window.location.search);
const fname = params.get("fname")
const lname = params.get("lname")
const email = params.get("email")
const messeage = params.get("fname")
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'example#gmail.com',
pass: 'example'
}
});
var mailOptions = {
from: 'example#gmail.com',
to: "example#gmail.com",
subject: 'from' + fname + ' ' +lname,
text: 'Dear Rashed <br></br>' + messeage
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
alert("something went wrong")
} else {
alert("messeage sent")
}
});
}
The code that in there is JSX it is out of the main function with the return I adde'd the email minute ago could that have affect or if anyone has another solution like SMTP please send it to me. for some reason it only runs a part of the code not the entirety it also doesn't give error message.

node server not returning any response after API request

I am building an API with Node.js, Express, MYSQL and with the help of sequelize. I am using MVC pattern.
The problem I am encountering however is the server cannot send back any http response after request. When sending a post request for example with postman, the request keeps on loading and will terminate after around 2 minutes with COULD NOT GET ANY RESPONSE exception. While this is happening, data is correctly saved in the database.
This is my AuthController user registration method:
'use strict';
// AuthController.js
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: false }));
router.use(bodyParser.json());
var jwt = require('jsonwebtoken');
var bcrypt = require('bcryptjs');
const Model = require('../models/index');
const User = Model.sequelize.import('../models/user');
// Register new User.
exports.register = function(req, res) {
var hashedPassword = bcrypt.hashSync(req.body.password, 8);
User.create({
name : req.body.name,
email : req.body.email,
password : hashedPassword
},
function (err, user) {
if (err)
{
return res.status(500).send("There was a problem registering the user. "+err)
}
else{
// create a token
var token = jwt.sign({ id: user._id }, process.env.AUTH0_CLIENT_SECRET, {
expiresIn: 86400 // expires in 24 hours
});
res.status(200).json({ auth: true, token: token });
}
});
};
// App.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const cors = require('cors');
var app = express();
var indexRoutes = require('./routes/index');
var userRoutes = require('./routes/users');
var courseRoutes = require('./routes/courses');
var authRoutes = require('./routes/auth');
// view engine setup
// Currently I am not using view-templates
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(cors()); //enable CORS
app.use(express.static(path.join(__dirname, 'public')));
//User Routes
app.use('/', indexRoutes);
app.use('/api', userRoutes);
app.use('/api', courseRoutes);
app.use('/api/auth', authRoutes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
//ROUTES
//auth.js
var express = require('express');
var router = express.Router();
//Require Controller Modules
var controller = require('../controllers/AuthController');
//Register new user
router.post('/register', controller.register);
router.get('/user', controller.me);
router.post('/login', controller.login);
router.get('/logout', controller.logout);
module.exports = router;
//User Model
'use strict';
module.exports = (sequelize, DataTypes) => {
var User = sequelize.define('User', {
//id: DataTypes.INTEGER,
name: DataTypes.STRING,
email: {type: DataTypes.STRING, allowNull: false, unique: true, validate: { isEmail: {msg: "Invalid Email"} }},
password: DataTypes.STRING
}, {});
User.associate = function(models) {
// associations can be defined here
};
return User;
};
DB Connection //in models/index.js
'use strict';
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(__filename);
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/../config/config.json')[env];
var db = {};
const Op = Sequelize.Op;
if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
var sequelize = new Sequelize(config.database,
config.username,
config.password,
{
host: config.host,
dialect: config.dialect,
operatorsAliases: false,
}
);
//check if connection is established
sequelize
.authenticate()
.then(() => {
console.log('Database Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
}
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
I think there is something wrong I am committing or missing out something. I am experiencing this problem when sending POST REQUESTS. Data is saved in mysql table but no response is sent back.
Please assist. Thanks.
Thank you guys for trying to assist. After working around I discovered that problem was with the controller method. The way it was structured was not sending back response after data is persisted in the database.
This is how I recoded my register method in AuthController:
//Old one
// Register new User.
exports.register = function(req, res) {
var hashedPassword = bcrypt.hashSync(req.body.password, 8);
User.create({
name : req.body.name,
email : req.body.email,
password : hashedPassword
},
function (err, user) {
if (err)
{
return res.status(500).send("There was a problem registering the user. "+err)
}
else{
// create a token
var token = jwt.sign({ id: user._id }, process.env.AUTH0_CLIENT_SECRET, {
expiresIn: 86400 // expires in 24 hours
});
res.status(200).json({ auth: true, token: token });
}
//Rewrite:
// Register new User.
exports.register = function(req, res) {
var hashedPassword = bcrypt.hashSync(req.body.password, 8);
User.create({
name : req.body.name,
email : req.body.email,
password : hashedPassword
})
.then(user=>{
// create a token
var token = jwt.sign({ id: user._id }, config.secret, {
expiresIn: 86400 // expires in 24 hours
});
return res.status(200).json({ auth: true, token: token });
}).catch(err=>{
return res.status(500).send("There was a problem registering the user. "+err)
});
};
This worked for me and the code now works as expected.

Nodemailer Sendgrid on Compute Engine

i trying to send emails from my compute engine instance but nothing happen(no error message). When i send mails from my local pc i get the emails.
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var options = {};
var transporter = nodemailer.createTransport(smtpTransport({
service: 'SendGrid',
auth: {
user: 'username',
pass: 'password'
}
}));
module.exports = {
sendmailto : sendmailto
}
function sendmailto(emailfrom,emailto, message){
var mailOptions = {
from: emailfrom, // sender address
to: emailto, // list of receivers
subject: 'Monitoring', // Subject line
text: message, // plaintext body
html: '<b>Monitoring</b>' +
'<p> '+message+'<p>' // html body
};
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}else{
console.log('Message send: ', + info.response);
}
});
};
I found the reason be myself:) Service "Sendgrid use as standard port the 25 but is does not work with compute engine so i need to add the port 2525.
var transporter = nodemailer.createTransport(smtpTransport({
service: 'SendGrid',
port: '2525',
auth: {
user: 'username',
pass: 'password'
}
}));