How to successfully send mail using a different domain than SMTP credentials? - javascript

I want to send out an email as myemail#domain2.com while being connected to domain1.com using domain1.com SMTP credentials. Both domain1.com and domain2.com have SPF records.
I did quite a bit of research and found that you should be able to achieve this by adding "a:domain1.com" into domain2.com's SPF record. I have done as such but I still cannot successfully send out an email.
I created a test code using node.js and nodemailer to test sending out the email.
const nodemailer = require('nodemailer');
let transport = nodemailer.createTransport({
host: 'mail.domain1.com',
port: 465,
auth: {
user: 'myemail#domain1.com',
pass: 'password'
}
});
const message = {
from: 'myemail#domain2.com',
to: 'test#gmail.com',
subject: 'Testing 123',
text: 'Testing One Two Three....'
};
transport.sendMail(message, function (err, info) {
if (err) {
console.log('err: ', err);
} else {
console.log('info: ', info);
}
});
{ Error: Message failed: 550 Error458 block
at SMTPConnection._formatError (C:\Users\Admin\Desktop\testsendmail\node_modules\nodemailer\lib\smtp-connection\index.js:784:19)
at SMTPConnection._actionSMTPStream (C:\Users\Admin\Desktop\testsendmail\node_modules\nodemailer\lib\smtp-connection\index.js:1661:34)
at SMTPConnection._responseActions.push.str (C:\Users\Admin\Desktop\testsendmail\node_modules\nodemailer\lib\smtp-connection\index.js:1146:22)
at SMTPConnection._processResponse (C:\Users\Admin\Desktop\testsendmail\node_modules\nodemailer\lib\smtp-connection\index.js:942:20)
at SMTPConnection._onData (C:\Users\Admin\Desktop\testsendmail\node_modules\nodemailer\lib\smtp-connection\index.js:749:14)
at TLSSocket.SMTPConnection._onSocketData.chunk (C:\Users\Admin\Desktop\testsendmail\node_modules\nodemailer\lib\smtp-connection\index.js:195:44)
at TLSSocket.emit (events.js:182:13)
at addChunk (_stream_readable.js:283:12)
at readableAddChunk (_stream_readable.js:264:11)
at TLSSocket.Readable.push (_stream_readable.js:219:10)
code: 'EMESSAGE',
response: '550 Error458 block',
responseCode: 550,
command: 'DATA' }
Here are the SPF Records for the 2 domains:
domain1.com:
v=spf1 mx a ~all
domain2.com:
v=spf1 a a:domain1.com mx ?all

The right way to add a second domain as a mail source is to use the include mechanism:
v=spf1 a mx include:domain2.com ~all
I can't tell from what you've posted whether this is actually the cause of the error you're getting.
You might want to look into DKIM signing and DMARC as well.
While I'm here, there's no point in having a ?all default mechanism; it's equivalent to not having an SPF record at all; use ~all if you're using DMARC, -all otherwise (though be sure that all your mail sources are nailed down before doing that).

Related

nodemailer timing out when trying to send email

I have this:
app.post('/sendSessionConformationEmail', (req, res) => {
if (!req.session.loggedin) {
res.redirect('/login')
req.session.destroy()
}
var email = req.body.email;
var name = req.body.name;
var trainername = req.body.trainername;
var sessionDate = new Date().toLocaleString();
console.log(email)
console.log(name)
console.log(trainername)
console.log(sessionDate)
// async..await is not allowed in global scope, must use a wrapper
async function main() {
// Generate test SMTP service account from ethereal.email
// Only needed if you don't have a real mail account for testing
let testAccount = await nodemailer.createTestAccount();
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: "myemail#gmail.com",
pass: "myauthpassword",
},
tls:{
rejectUnauthorized:false
}
});
// send mail with defined transport object
let info = await transporter.sendMail({
from: 'my2email#gmail.com', // sender address
to: "gianluca#my3email.com", // list of receivers
subject: "Hello ✔", // Subject line
text: "Hello world?", // plain text body
});
console.log("Message sent: %s", info.messageId);
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321#example.com>
// Preview only available when sending through an Ethereal account
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}
main().catch(console.error);
})
I copied the code straight from the nodemailer website, and made the necessary changes. However, when I run this code, nothing sends, and it actually gives me this error:
Error: connect ETIMEDOUT 13.49.22.0:443
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {
errno: -60,
code: 'ETIMEDOUT',
syscall: 'connect',
address: '13.49.22.0',
port: 443,
type: 'FETCH',
sourceUrl: 'https://api.nodemailer.com/user'
}
I've been using nodemailer with this code for over 2 years, never gotten this error, and it is killing me. Is anyone able to help?
you should allow third party apps use your gmail.
https://support.google.com/accounts/answer/3466521?hl=en
ethereal.email (13.49.22.0) is down today. Runs on AWS.

Docker Image issues: TypeError: c.charCodeAt(...).toString(...).padStart is not a function for html-to-text

i have issues on nodemailer transport using smtp which i developed in nodejs, it has no issues in local server and email sent correctly, but when i'm dockerize them and deploy to AWS ECS, the API still return status 200 without any error but email is not send to the clients email. how do i overcome this issues? i tried port 25 and 465 as well but still its not sending anything to client email.
const transporter = await nodemailer.createTransport({
host: 'smtp.office365.com',
port: 587,
auth: {
user: 'email#company.com.my',
pass: 'password'
},
})
const templates = new EmailTemplates()
await templates.render(template, context, async (err, html, text, subject) => {
await transporter.sendMail({
from: '"Company Name" <email#company.com.my>',
to: email,
subject: subjects,
html: html,
text: text
}).then(() => {
console.log(`Email sent to ${email}`)
}).catch((err) => {
console.log('error: ', err)
})
})
at first i though it's nodemailer issues, but then when i'm test run my local docker image, it's return an error
/srv/node_modules/html-to-text/lib/whitespace-processor.js:11
.map(c => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0'))
^
TypeError: c.charCodeAt(...).toString(...).padStart is not a function
at map.c (/srv/node_modules/html-to-text/lib/whitespace-processor.js:11:52)
at Array.map (native)
at charactersToCodes (/srv/node_modules/html-to-text/lib/whitespace-processor.js:11:6)
at new WhitespaceProcessor (/srv/node_modules/html-to-text/lib/whitespace-processor.js:32:29)
at new BlockTextBuilder (/srv/node_modules/html-to-text/lib/block-text-builder.js:28:31)
at htmlToText (/srv/node_modules/html-to-text/lib/html-to-text.js:146:19)
at Object.fromString (/srv/node_modules/html-to-text/lib/html-to-text.js:289:44)
at /srv/node_modules/swig-email-templates/index.js:50:29
at FSReqWrap.cb [as oncomplete] (fs.js:260:19)
i wonder what is the actual error and how to solve this html-to-text error?

Mailing with Node.js. Issue with the host property

I know there are many posts like this here, but I couldn't find any information that would solve my issue. So I tried using both nodemailer and emailjs.
I have this code:
This is for nodemailer
var nodemailer = require('nodemailer');
nodemailer.createTestAccount((err, account) => {
if (err) console.log(err);
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport({
host: "smtp.Hotmail.com", // Just Hotmail doesn't work either
// port: 587,
auth: {
user: 'xxx#outlook.com',
pass: 'xxx'
}
});
// setup email data with unicode symbols
let mailOptions = {
from: `${req.body.fullName} ${req.body.email}`, // sender address
to: 'alexander.ironside#mygeorgian.ca', // list of receivers
subject: 'Email from SMWDB contact form', // Subject line
html: `<h4>Name: ${req.body.fullName}</h4>
<h4>Company: ${req.body.company}</h4>
<h4>Phone: ${req.body.phone}</h4>
<p>Message: ${req.body.message}</p>`
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId);
// Preview only available when sending through an Ethereal account
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
// Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321#example.com>
// Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
});
});
And this for emailjs
var email = require("emailjs");
var server = email.server.connect({
user: "xxx#outlook.com",
password: "xxx",
host: "smtp-mail.outlook.com",
tls: {ciphers: "SSLv3"}
});
var message = {
text: `Test`,
from: `${req.body.fullName} <${req.body.email}>`,
to: `Alex <alexander.ironside#mygeorgian.ca>`, // list of receivers
// cc: "else <else#your-email.com>",
subject: 'Email from SMWDB contact form', // Subject line
attachment:
[
{
data: `
<h4>Name: ${req.body.fullName}</h4>
<h4>Company: ${req.body.company}</h4>
<h4>Phone: ${req.body.phone}</h4>
<p>Message: ${req.body.message}</p>`
, alternative: true
},
]
};
// send the message and get a callback with an error or details of the message that was sent
server.send(message, (err, message) => {
console.log(err || message);
});
The problem I think is that as host both docs say something like this: smtp.your-email.com, meanwhile all code examples say this: host: "Hotmail". What's the correct way?
I don't really care which package I'm using.
I have to use Hotmail/Yahoo and cannot use Gmail (Too many accounts activated with one phone number)
Now to the errors:
Emailjs throws this:
{ Error: bad response on command '
.': 5.2.0 STOREDRV.Submission.Exception:SendAsDeniedException.MapiExceptionSendAsDenied; Failed to process message due to a permanent exception with message Cannot submit message. and then there is a lot of numbers and a callback trace.
Nodemailer throws this:
{ Error: getaddrinfo ENOTFOUND smtp.Hotmail.com smtp.Hotmail.com:587
at errnoException (dns.js:50:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:92:26)
code: 'ECONNECTION',
errno: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'smtp.Hotmail.com',
host: 'smtp.Hotmail.com',
port: 587,
command: 'CONN' }
I used to do this in PHP and have no idea why it's so complicated with Node, but I guess there must be a reason.
I asked a friend to create a Gmail account and it worked right away. If you hit the same problem, don't bother with anything else. Just use Google.
That's the transporter code that worked for me
var transporter = nodemailer.createTransport({
host: "smtp.gmail.com", // hostname
auth: {
user: 'xxx#gmail.com',
pass: 'xxx'
}
});

Use smtp client to send email without providing password

I'm using nodemailer to try to send an email to myself via commandline:
var nodemailer = require('nodemailer');
// config
var smtpConfig = {
host: 'smtp.myhost.com',
port: 465,
secure: false, // dont use SSL
tls: {rejectUnauthorized: false}
};
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport(smtpConfig);
// setup e-mail data with unicode symbols
var mailOptions = {
from: '"Fred Foo 👥" <foo#blurdybloop.com>', // sender address
to: 'person#gmail.com', // list of receivers
subject: 'Hello ✔', // Subject line
text: 'Hello world 🐴', // plaintext body
html: '<b>Hello world 🐴</b>' // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
When I try to run this code I get the following error:
Error: Invalid login: 535-5.7.8 Username and Password not accepted. Learn more at\n535 5.7.8 https://support.google.com/mail/answer/14257
The link takes you to a page that tells you to register your app inside Google Console. But this is not what I'm trying to do.
There are loads of email clients that can send an email to a gmail inbox without having to sign into that email account. This is what I'm trying to do. I'm trying to turn my terminal into an smtp client that can send a mail message to any inbox. This shouldn't require extensive authentication. How do I do this?
NOTE
Just to provide some perspective, I'm trying to replicate in node whats possible with the unix sendmail command:
sendmail person#gmail.com < testemail.txt
How can I do this using nodemailer?
Try port 587.
Here are my gmail settings.
smtpServerName="smtp.gmail.com"
portNumber="587"
authenticationMode="SSL"
smtpUserName="somebody#gmail.com"
smtpUserPassword="xxxxxxxxxx"
I would experiment with ssl: false and ssl: true
nodemailer.SMTP = {
host: 'smtp.gmail.com',
port: 587,
ssl: false,
use_authentication: true,
user: 'my.username#gmail.com',
pass: 'my.password'
}
Make sure you read this:
https://support.google.com/accounts/answer/6010255
It looks like there are two ways with gmail.
Port 587 is (non ssl) but with TLS.
Port 465 is SSL (but not TLS).
Go figure.
//singleServer = new SmtpServerSettings("smtp.gmail.com",
// "myname#gmail.com", "587", AuthenticationType.Basic,
// "myname#gmail.com", "mypassword", "");
//singleServer = new SmtpServerSettings("smtp.gmail.com",
// "myname#gmail.com", "465", AuthenticationType.SSL,
// "myname#gmail.com", "mypassword", "");

NodeJS nodemailer - IIS SMTP Virtual Server

I'm trying to use nodemailer (https://www.npmjs.com/package/nodemailer) to send e-mail using a local windows server we have, with an SMTP Virtual Server.
The SMTP Virtual Server works fine, we already use Jmail in Classic ASP, pass it the server name, and email gets sent.
var nodemailer = require('nodemailer');
var options = {
host: 'SERVERNAME'
};
var transporter = nodemailer.createTransport(options);
var email = {
from: 'no-reply#domain.co.uk',
to: 'webmaster#domain.co.uk',
subject: 'hello',
text: 'hello world!'
};
var callback = function(err, info){
if (err) { throw err }
console.log('sent');
}
transporter.sendMail(email, callback);
The error I get back from this is:
Can't send mail - all recipients were rejected: 550 5.7.1 Unable to
relay for webmaster#domain.co.uk
If I update the options object to include auth, like this:
var options = {
host: 'SERVERNAME',
auth: {
user: '...',
pass: '...'
}
};
I get this error:
Invalid login: 504 5.7.4 Unrecognized authentication type
How can I use nodemailer to send e-mail using our IIS SMTP Virtual Server..?
I still don't know why the above doesn't work, pointing nodemailer to our SMTP Virtual Server. However I've worked around it.
Our SMTP Virtual Server is setup to use our Office 365 account, so I've updated my nodemailer code to go to Office 365 direct, rather than via our local server.
var options = {
host: 'SMTP.office365.com',
port: 25,
secure: false,
ignoreTLS: false,
auth: {
user: '...',
pass: '...'
},
tls: {
ciphers: 'SSLv3'
}
}
This works.

Categories

Resources