How to send an confirmation email after registration nodejs - javascript

I want to add the code to send email in this function.
I've also installed 2 libraries: jsonwebtoken and nodemailer.
I've seen some code related to this topic but I'm new to javascript and nodejs and i could not seem to make the code work. I could use some help!
Thanks in advance!
This is my code.
app.post('/insertuser',function(_req,res){
var data =JSON.parse(_req.body.data);
var username = data.username;
var age = data.age;
var password = data.password;
var fname = data.fname;
var lname = data.lname;
var address = data.address;
var city = data.city;
var email = data.email;
var sq = data.sq;
var answer = data.answer;
var pnumber = data.pnumber;
var dataentered = data.dataentered;
mysqlConnection.connect(function(){
var query = "Insert into Customer (Username,Age,Password,First_Name,Last_Name,Email,Address,City,Phone_No,SQ,Answer,Date_Entered) values('"+username+"','"+age+"','"+sha1(password)+"','"+fname+"','"+lname+"','"+email+"','"+address+"','"+city+"','"+pnumber+"','"+sq+"','"+answer+"','"+dataentered+"')";
mysqlConnection.query (query,function(err,results,_fields){
if(err)
{
console.log(err);
res.send('Please try again!');
}
else{
if(results.affectedRows>0)
{
res.send('Thanks for registering! Please confirm your email! We have sent a link!');
//the code for affirmation
}
else{
res.send('Please try again!');
}
}
})
})
});

You can use nodemailer library for sending emails. I will explain how to send emails from a gmail account. First you need to enable Less Secure App Access in your gmail account security section.
After that, create a transporter using nodemailer:
const nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'myemail#gmail.com',
pass: 'password'
}
});
Then in your code, use created transporter to send mails.
mysqlConnection.query (query,function(err,results,_fields){
if(err) {
console.log(err);
res.send('Please try again!');
} else {
if(results.affectedRows>0) {
//the code for affirmation
var mailOptions = {
from: 'myemail#gmail.com',
to: 'toemail#gmail.com',
subject: 'Sending Email using Node.js',
text: 'That was easy!'
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
//Handle error here
res.send('Please try again!');
} else {
console.log('Email sent: ' + info.response);
res.send('Thanks for registering! Please confirm your email! We have sent a link!');
}
});
} else {
res.send('Please try again!');
}
}
})
You can refer to nodemailer documentation for more info.

Related

ask question in a channel, save the answer, and depend of that answer do something, discord.js

i would like to ask a question, so here its my code to make myself as clear as possible:
const Discord = require ("discord.js")
const config = require('../config.json')
var nodemailer = require('nodemailer');
const prompts = require('prompts');
module.exports.run = async (bot, message, args) => {
const memberTarget = message.mentions.members.first();
const general = message.guild.channels.cache.find(channel => channel.name === "general");
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'user#gmail.com',
pass: 'password123'
}
});
let response = prompt(`please give me your mail `);
let mailOptions = {
from: 'user#gmail.com',
to: `${response}`,
subject: 'Sending Email using Node.js',
text: 'That was easy!'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
}
module.exports.help = {
name: 'mail'
}
so here i want to ask the Mail, and i will send a mail to him!, i followed the steps at this pague:
https://www.npmjs.com/package/prompts
i downloaded:
npm i prompts, npm install --save prompts
and in this part of the code is where i get the question:
let response = prompt(`please give me your mail `);
i think im using wrong that part, so i would aprreciate your help and i hope i was clear :)

I have issue with sending emails using nodemailer

When I am trying to send an email through my contact form I am getting an error that says
'address you are using is not belonging to this platform' <- I am using e-mail from another platform to send message. The O2.pl platform I use only to receive the message but it seems like every person who wants to send an e-mail has to send from account registered in o2.pl platform.
Here is my code
const transporter = nodemailer.createTransport({
host: 'poczta.o2.pl',
port: 587,
secure: false,
auth: {
user: 'email#o2.pl',
pass: 'password'
}
})
const mailOptions = {
from: req.body.email,
to: 'email#o2.pl',
subject: `message from ${req.body.email}: ${req.body.subject}`,
text: req.body.message
}
transporter.sendMail(mailOptions, (error, info) => {
if(error){
console.log(error);
res.send('error');
}
else{
console.log('Email sent: ' + info.response);
res.send('success')
}
})
})
here is another code
const contactForm = document.querySelector('.contactFormm');
let email = document.getElementById('email');
let name = document.getElementById('name');
let subject = document.getElementById('subject');
let message = document.getElementById('message');
contactForm.addEventListener('submit', (e)=>{
e.preventDefault();
let formData = {
email: email.value,
name: name.value,
subject: subject.value,
message: message.value
}
let xhr = new XMLHttpRequest();
xhr.open('POST', '/');
xhr.setRequestHeader('content-type', 'application/json');
xhr.onload = function(){
console.log(xhr.responseText);
if(xhr.responseText =='success'){
alert('Email sent');
email.value = '';
name.value = '';
subject.value = '';
message.value = '';
}
else{
alert('Something went wrong!')
}
}
xhr.send(JSON.stringify(formData))
})
The first part of your snippet looks good. Have you tried using gmail to test in order to ascertain if there is an issue with poczta?

Nodemailer transporter seems to break when used a script function

i came here with a nodemailer situation, i'm building a contact form and to avoid php i was trying to use nodemailer on js however i found a problem.
When i use nodemailer on a simples mailer.js and use "node mailer.js" it works:
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'email',
pass: 'password'
}
});
var mailOptions = {
from: 'person',
to: 'email',
subject: 'Teste nodemailer',
text: `Teste`
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
but when i try to insert it on the script that validades the form:
async function sendIT(){
var email = document.getElementById('email').value;
var name = document.getElementById('name').value;
var msg= document.getElementById('msg').value;
var error = false;
if(name == ""){
document.getElementById('nameError').classList.add('error');
error = true;
}else{
document.getElementById('nameError').classList.remove('error');
}
if(msg == ""){
document.getElementById('msgError').classList.add('error');
error = true;
}else{
document.getElementById('msgError').classList.remove('error');
}
if (!(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(email))){
document.getElementById('emailError').classList.add('error');
error = true;
}else{
document.getElementById('emailError').classList.remove('error');
}
if(!error){
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'email',
pass: 'passwor'
}
});
var mailOptions = {
from: 'person',
to: email,
subject: 'Test nodemailer',
text: 'The ' +name+ ' sent the following message:\n\n\n' + msg
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
alert('e-mail failed')
console.log(error);
} else {
alert('E-mail sent');
console.log('Email sent: ' + info.response);
}
});
}
}
And the error seems to be on the 'transporter' because it is when i create the transporter or when i try to use it to send an e-mail that the scripts breaks.
Does anyone know why this happens? Thank you for the time spent reading and responding to this question
Edit.:
The line
var nodemailer = require('nodemailer');
at the top of the script file gives an error on the browser Uncaught ReferenceError: require is not defined, an error that it should not happen since i'm using nodejs.

nodemailer email not sent and no errors logged

I'm trying to use nodemailer to send email but it's not sending any email and the strange thing is that it's also not logging any error.
Here's the code of my route:
router.post("/form", async (req, res) => {
try {
let { name, email, password } = req.body;
let user = await User.create({
name,
email,
password,
});
if (!user) return res.status(501).send("Something went wrong");
let token = await user.getSignedToken();
try {
user.emailToken = await user.verifyEmail();
} catch (ex) {
console.log(ex);
}
try {
await user.save({ validateBeforeSave: false });
} catch (ex) {
console.log(ex);
}
const options = {
expires: new Date(
Date.now() + process.env.JWT_COOKIE_EXPIRE * 24 * 60 * 60 * 1000
),
};
var smtpTransport = nodemailer.createTransport({
service: "Gmail",
auth: {
user: "myEmail",
pass: "myPass",
},
});
var mailOptions = {
from: "myEmail",
to: req.body.email,
subject: "Verify Email Token",
text: `go to the below link\nhttp://localhost:3000/verifyEmail/${emailToken}`,
};
smtpTransport.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log("Email sent: " + info.response);
}
});
res.cookie("token", token, options);
res.send("Check email for activation");
} catch (ex) {
res.send(ex);
}
});
So, it's not sending any email and after it, the res.cookie and the res.send line is also not working. But, the server is not logging any error/exceptions. So, what could be the issue? I used nodemailer in another route (with the same gmail account as this one) and it was working. So, what could be the problem that the code here isn't working?
In the mailoptions object, you are using emailToken and that variable is never defined. Instead, you might wanna use user.emailToken

How to use nodemailer with claudia-api-builder

I am trying to create a simple REST API I can post an email to, to then email myself. I am using nodemailer and had set it up as an express app and it all worked fine confirming my authentication etc. is fine. I wanted to host it online so I have used claudia.js to create a lambda and API gateway setup but this seems to have broken it.
The Code
const nodemailer = require('nodemailer');
const secrets = require('./secret');
const apiBuilder = require('claudia-api-builder');
api = new apiBuilder();
module.exports = api;
var mailOptions;
var logMsg = "none";
api.post('/email', async (req, res) => {
mailOptions = {
from: secrets.email,
to: secrets.email,
subject: 'Email From: ' + req.body.senderEmail + ' | ' + req.body.subject,
text: req.body.content,
};
sendMail(mailOptions);
return logMsg;
})
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: secrets.email,
pass: secrets.pwd
}
});
function sendMail(mailOptions) {
logMsg="Starting Send Function";
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
logMsg = error;
return error;
} else {
logMsg = "Send Complete";
return true;
}
});
logMsg="Function finished";
}
When I debug via postman, by posting a raw JSON
{
"senderEmail": "test2",
"subject": "test",
"content":"test"
}
I receive "Function Finished" Which I dont really see how it is possible as surely the if or else should've fired under transporter.sendMail(..., returning from the function. I also don't receive an email which is my end goal
I had the same problem until I started returning the transporter
return transporter.sendMail(mailOptions)
.then(info => {
console.log('email sent: ', info)
return {'status': 'OK'}
})
.catch(err => {
console.log('email error: ', err)
return {'status': 'ERROR'}
})

Categories

Resources