Possible issue when sending email with SMTP.js - javascript

I am using smtp.js to send mails to my email id whose credentials i made using smtp.js.I made a contact form where i want the user to enter his info and email and that should be sent to my email.So according to this logic, my mail should be in To property and sender's mail should be in the From property.However, when i run the code, it throws an error as
"Mailbox name not allowed. The server response was: Envelope FROM 'sendername#gmail.com' email address not allowed.".
If not possible,can u tell me some other alternative using js.Thanks
Code:
function sendmail()
{
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var address = $('#address').val();
var postal = $('#postal').val();
console.log(typeof(email))
// var body = $('#body').val();
var Body='Subject: '+"Estimated Quote"+'<br>Name: '+name+'<br>Email: '+email+'<br>Phone: '+phone+'<br>Address: '+address+'<br>Postal Code: '+postal+'<br>Quote exl VAT: '+vat_excl+'<br>Quote incl VAT: '+vat_incl;
//console.log(name, phone, email, message);
Email.send({
SecureToken:"2d019ac3-046b-4c4f-94e2-f4f3bf08fb1f",
To: 'receivermail#gmail.com',
From: email,
Subject: "New mail from "+name,
Body: Body
}).then(
message =>{
console.log (message);
if(message=='OK'){
alert('Thanks for submitting details.We will contact you soon.');
}
else{
console.error (message);
alert('Error submitting form.')
}

I don't know which library are you using to stablish the SMTP connection, but first of all make sure that the SMTP sever accepts all the domains that you're requiring.
I'd suggest you to use nodemailer which is fairly easy to use.
Example:
// CONFIG SETUP
import { createTransport } from 'nodemailer';
const Transporter = createTransport({
host: process.env.SMTP_HOST || 'localhost',
port: Number(process.env.SMTP_PORT) || 25,
secure: false,
tls: { rejectUnauthorized: false }, // THIS WILL BE ACCORDING TO YOUR SMTP CONFIG
});
// EXAMPLE OF USAGE
const info = Transporter.sendMail({
from: 'sender#test.com',
to: 'to#test.com',
subject: 'TEST',
text: 'TEST',
});

Related

NodeMailer - Username and Password not accepted

I am getting this in postman -
{
"code": "EAUTH",
"response": "535-5.7.8 Username and Password not accepted. Learn more at\n535 5.7.8
https://support.google.com/mail/?p=BadCredentials x7-
20020aa784c7000000b005058d220b37sm21945855pfn.64 - gsmtp",
"responseCode": 535,
"command": "AUTH PLAIN"
}
Email And password not accepted , I have already gone through this question, and tried possible way to resolve this problem, but nothing worked out.
nodemailer code section -
let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: 'mygmail#gmail.com',
pass: 'mypassword'
}
})
const info = await transporter.sendMail({
from: 'mygmail#gmail.com',
to: "person#gmail.com",
subject: "subject",
text: "text",
html: `<h1> hello </h1>`
})
I have tried -
generate an app-specific password and use that in place of your actual password.
enabled the captcha (link)
enabled the IMAP setting in gmail->setting->Forwarding and POP/IMAP
I Read this - less secure app and google account
Any help would be appreciated.
First, You need to use a valid Gmail account with your credentials.
You need to allow less secure apps from your google account to send emails. Through this link. Allow less secure apps From your Google Account
const nodemailer = require('nodemailer');
const sendEmail = async () => {
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'sender gmail',
pass: 'sender password',
},
});
const options = {
from: 'sender gmail',
to: 'receiver gmail',
subject: 'subject',
text: 'text',
};
await transporter.sendMail(options);
};
module.exports = sendEmail;
You can not login to the smtp server using a login and password anymore. You could try using an apps password but as Less secure apps & your Google Account is being removed shortly this is probably not the best option.
I recommend looking into Xoauth2 this way you can authorize the user rather than relying upon their password. I would try adapting javascript-implicit-flow to see if this will work.

Setting nodemailer from address using request data

When nodemailer sends out an email from a contact form, it goes to an admin, who then responds to the email address found in req.body.email
I'd like to set the reply-to address as this value, so that the admin can simply hit reply to send a reply with the message data, without having to copy paste the email into the 'to' field. Here's what I've got:
Send email util
const sendEmail = async options => {
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT,
auth: {
user: process.env.SMTP_EMAIL,
pass: process.env.SMTP_PASSWORD
}
});
// send mail with defined transport object
let message = {
// from: `${options.fromName} <${process.env.FROM_EMAIL}>`,
from: `${options.fromName} <${options.fromEmail}>`,
to: options.email,
subject: options.subject,
text: options.message,
html: options.body
};
const info = await transporter.sendMail(message);
console.log('Message sent: %s', info.messageId);
};
module.exports = sendEmail;
Send email function
try {
await sendEmail({
fromName: emailBody.name,
fromEmail: emailBody.email,
email: 'admin#email.com',
subject: `${emailBody.name} sent a message!`,
body: emailBodyText
});
} catch (err) {
console.log(err);
return next(new ErrorResponse('Email could not be sent', 500));
}
Here's what I get:
response: '553 5.7.1 <user#gmail.com>: Sender address rejected: not owned by user admin#email.com'
I get that admin#email.com cannot send email from user#gmail.com, but I'd like to have that ux of being able to simply hit reply and have the email directed to the user. Is there a good way to make it work like this?

Email sent but not recieved, I'm using nodemailer

I'm using nodemailer v^6.4.17 and I'm having trouble getting it to send emails. I do not get the issue cause in the console, it is showing that the emails has been sent. But when I go to client side and check inbox, I don't see the email.
let transporter = nodemailer.createTransport({
name: 'www.example.com',
host: '******************',
port: 465,
secure: true,
auth: {
user: ''sender#email.com'',
pass: '**********',
},
});
let info = await transporter.sendMail({
from: 'sender#email.com',
to: "reciever#email.com",
subject: "Hi",
text: "Hello world!",
html: '<h1>2021</h1>',
});
What I'm I missing here? Thanks.
Make sure you enable the less secure app in your Gmail account.
enable your Gmail account less secure app
Also, make sure to check email in spam emails.
Try doing it like this -
var mailOptions = {
from: "----------",
to: "-------",
subject: "------------",
text: "------------",
html: "-----------"
};
smtpTransport.sendMail(mailOptions, function (error, response) {
if (error) {
console.log(error);
console.log("Cannot connect to SMTP server right now");
} else {
console.log("Success" + response);
}
});

How can I send emails from a user's account using Node.js?

i'm working in a program that saves contacts. I want to add a new fuction that lets you send emails to your contacts form your email account.
I tried to do it with nodemailer, taking the login data from a form that users need to fill in.
But nodemailer sends me a error, look this:
Error: Invalid login: 535-5.7.8 Username and Password not accepted.
I tried with applcation password and activating the less secure option, but the error continues. Look my code:
Here i take the user's email and password:
router.post('/email', isLoggedIn, async (req, res) => {
var { email } = req.body;
var { password } = req.body;
var parts = email.substring(email.lastIndexOf('#')+ 1);
exports.email = email;
exports.password = password;
res.redirect('/links/message')
});
Here i take de message:
router.post('/sendmessage', isLoggedIn, async (req, res) => {
const { message } = req.body;
const { assumpt } = req.body;
exports.message = message;
exports.assumpt = assumpt;
res.redirect('/links/contactsemail')
});
Finally, i take the category contact that you need to send the email and i send the email with the message and data login that users give me:
router.post('/contactsend', isLoggedIn, async (req, ress) => {
const { contacts } = req.body;
const row = await pool.query('SELECT count(email) AS email FROM links WHERE user_id=? AND category=? AND email IS NOT NULL',[req.user.id, contacts]);
const rows = row[0].email;
const assumpt = myModule.assumpt;
const message = myModule.message;
const email = myModule.email;
const password = myModule.password
var parts = email.substring(email.lastIndexOf('#')+ 1);
const hosts = 'smtp.' + parts;
var transporter = nodemailer.createTransport({
host: hosts,
port: 587,
auth: {
user: email,
pass: password
}
});
for (i = 1; i <= rows; i++ ){
var email1 = await pool.query('SELECT email AS email FROM (SELECT email, ROW_NUMBER() OVER (ORDER BY email) AS rn FROM links WHERE user_id= ? AND category=?) q WHERE rn = ?', [req.user.id, contacts, i]);
var email1 = email1[0].email;
var mailOptions = {
from: email,
to: email1,
subject: assumpt,
text: message
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
res.flash('success', 'Missatge enviat correctament');
res.redirect('/links');
}
});
};
});
My questions are:
How can I fix the error?
I can do it in different way that's it's easier and better?
Am I understanding this correctly that you want your users to enter their credentials for their private/external e-mail provider so you can send an e-mail using that provider?
In that case there is no generic answer to your question since the specifics of the required configuration highly depends on the e-mail provider. For example in your code:
var parts = email.substring(email.lastIndexOf('#')+ 1);
const hosts = 'smtp.' + parts;
var transporter = nodemailer.createTransport({
host: hosts,
port: 587,
auth: {
user: email,
pass: password
}
});
This block already has some hard-coded assumptions, i.e. that the smtp host for john.doe#example.net is smtp.example.org and that the username for that e-mail is also john.doe#example.net which - both - is not necessarily the case for many e-mail providers.
So even if this would work for you it is very likely it won't work for all of your users!
Instead you should use a single smtp gateway/relay your application can forward e-mails to. Then you also won't need the credentials of the users themselves but can use the login credentials for your application to that smtp gateway.
But it depends on the configuration of your smtp gateway whether you'll be allow to send with arbitrary sender addresses. And even if your gateway might allow this the mails may be blocked due to spam filters since your gateway may not be allowed to send e-mails for the users' domain, see SPF.
Therefor I would advise you - besides using a dedicated smtp gateway - to send with an e-mail address/domain you own and control. You may still augment the mail coming directly from the user, e.g. by setting the display name and Reply-To header appropriately:
From: "John Doe" <myapp#example.com>
To: jane.doe#example.org
Reply-To: "John Doe" <john.doe#example.org>
Subject: "A message from John Doe via MyApp"
For this mail the recipient would get the sending user's name displayed as sender (but your app's e-mail and not the user's) and when hitting the reply button the reply would by default - depending on the e-mail client - be sent back to the user, i.e. in this case john.doe#example.org.

How to change sender name different form authenticated email?

var nodemailer = require('nodemailer');
// Not the movie transporter!
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '*****#gmail.com', // Your email id
pass: '*******' // Your password
}
});
var mailOptions = {
from: varfrom_name, // sender address
to: varto, // list of receivers
subject: varsubject, // Subject line
text: vartext, // plaintext body
html: varhtml // html body
};
console.log(mailOptions);
// send mail with defined transport object
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
return console.log(error);
}else{
return console.log(info);
}
});
I want different sender address from the authenticated one ?
Suppose I authenticated data with abc#gmail.com, but I want to send the mail from xyz#gmail.com to def#gmail.com.
How to do that in node-mailer ?
// Using send mail npm module
var sendmail = require('sendmail')({silent: true})
sendmail({
from: ' xyz#gmail.com',
to: 'def#gmail.comh',
subject: 'MailComposer sendmail',
html: 'Mail of test sendmail ',
attachments: [
]
}, function (err, reply) {
console.log(err && err.stack)
console.dir(reply)
})
But the mails coming in the span box and the mails that we are sending is won't showing in the sent mail of sender mail address ?
I hope i will able to elaborate my question
I don't think you can. Gmail does not allow the change of the sender address.
However, you can look for another service, like postmark, sendgrid, or create your own smtp server.

Categories