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.
Related
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.
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?
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'}
})
Nodemailer sendMail function doesn't seem to do anything
I've tried debugging to see where it gets stuck
function sendEmail(){
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'email',
pass: 'password'
}
});
var mailOptions = {
from: 'email',
to: 'different email',
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 = {
sendEmail
};
I expect the email to be sent
I am doing a project based on firebase and I need to link a server-side function that sends an email to the client-side script.
This is my server-side index.js file
const functions = require('firebase-functions');
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'xxx#gmail.com',
pass: 'password'
}
});
var mailOptions = {
from: 'xxx#gmail.com',
to: 'xxx#gmail.com',
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);
}
});
I am wondering how I could have a button in html call a function in the script that will call the transporter.sendMail. I have never touched node js before so please excuse my lack of knowledge.
If this helps firebase setup my folders to be separated by functions and public for the server-side and client-side files
First initialize your HTML page with jQuery and on submitting the form send an Ajax request to the server as follows
$(document).ready(function() {
$("#formoid").submit(function(event) {
event.preventDefault();
$.ajax({
url: 'http://xxxxxxx.com/contact', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#formoid").serialize(), // post data || get data
success : function(result) {
$('#formoid')[0].reset();
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
Create a route called contact in your NodeJS server and listen for the contact request with All parameters required for your need. In the following case am using an express server and body parser to parse the data from incoming request
app.post('/contact', (req, res) => {
var transporter = nodemailer.createTransport({
service: "Gmail",
auth: {
user: "xxxxx",
pass: "xxxxx"
}
});
var mailOptions = {
from: req.body.email,
to: 'xxxxx#xx.com',
subject: 'Contact form',
text: 'From: ' + req.body.name + '\n Email: ' + req.body.email + '\nMessage: ' + req.body.msg
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
res.status(500).json({
message: "Error",
error: error
})
} else {
res.status(200).json({
message: "Its working",
response: info.response
})
}
});
});
In the above request am sending the name:as name, email: as email and message: as msg