I have issue with sending emails using nodemailer - javascript

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?

Related

Node.js (nodemailer) contact form works on a local host server but not when the site is live. What can I do?

I have a contact form on my website that I created with Node.js. When I run the site as a local host (localhost:5000), everything works fine. I fill out the contact form and when I hit send, I get a thank you alert and the email goes through.
However, once I connected my site to a domain and had it live, it no longer works - I get the "invalid login" message. I wrote an "if statement" in JS to return this "invalid login" error if the request does not go through, which is what I keep getting.
Could it be that I am not connecting to the correct server?
I'm guessing the xhr variable I use in my code is not valid once I begin using an actual hosting service. If so, how can I fix that?
Here is my code.
form.addEventListener('submit', (e)=>{
e.preventDefault();
console.log('submit clicked')
let formData = {
email: email.value,
level: password.value,
amount: amount.value,
service: service.value,
details: details.value,
email: email.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('Thank you! An Ogma representative will contact you shortly.');
email.value = '';
password.value = '';
amount.value = '';
service.value = '';
details.value = '';
email.value = '';
}else{
alert('Invalid login')
}
}
xhr.send(JSON.stringify(formData));
})
Edit: Here is my code with nodemailer. It is my Server.js file.
const express = require('express');
const app = express();
const nodemailer = require("nodemailer");
const PORT = process.env.PORT || 5000;
//Middleware
app.use(express.static('public'));
app.use(express.json())
app.get('/', (req, res)=>{
res.sendFile(__dirname + '/public/Request.html')
})
app.post('/', (req, res)=>{
console.log(req.body);
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '//kept hidden',
pass: //kept hidden
}
})
const mailOptions = {
from: req.body.email,
to: '//kept hidden',
subject: 'New message from Ogma',
text: [req.body.email, req.body.password, req.body.amount, `req.body.service, req.body.details].join('\n\n')`
}
transporter.sendMail(mailOptions, (error, info) =>{
if(error){
console.log(error);
res.send('error');
} else {
console.log('Email sent: ' + info.response);
res.send('success')
}
})
})
app.listen(PORT, ()=>{
console.log('Server running on port ${PORT}')
})

How to send an confirmation email after registration nodejs

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.

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.

Why am I getting this 404 error with axios.post()? Using Express/Node?

I'm trying to make a contact form with Nodemailer (first time), and I'm running into a 404 error.
I hope this isn't an obnoxious amount of code to share, I'll try to trim it down as much as I can.
Server.js
const transporter = nodemailer.createTransport({
host: "smtp.ethereal.email",
port: 587,
secure: false,
auth: {
user: creds.USER, // Generated by ethereal
pass: creds.PASS // Generated by ethereal
}
});
transporter.verify((err, success) => {
if(err) {
console.log(err)
} else {
console.log("Server is ready to take messages")
}
})
router.post("/send", (req, res, next) => {
let name = req.body.name
let email = req.body.email
let message = req.body.message
let content = `name: ${name} \n email: ${email} \n message: ${message}`
let mail = {
from: name,
to: "jlbroughton88#gmail.com",
subject: "Test from contact form",
text: content
}
transporter.sendMail(mail, (err, data) => {
if (err) {
res.json({
msg: "Message failed"
})
} else {
res.json({
msg: "Message succeeded!"
})
}
})
})
ContactForm.js (React Component)
I've trimmed the JSX part, the submit trigger works fine. It breaks once it reaches the axios.post() method.
handleSubmit(e) {
e.preventDefault();
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const message = document.getElementById('message').value;
axios.post("http://localhost:3002/send", {
name,
email,
message
})
.then((response) => {
// console.log(response)
if (response.data.msg === 'success') {
alert("Message Sent.");
this.resetForm()
} else if (response.data.msg === 'fail') {
alert("Message failed to send.")
}
})
}
resetForm() {
document.getElementById('contact-form').reset();
}

Calling NodeJS function from JS function

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

Categories

Resources