Sending emails to a mailing list with Mailgun - node.js

I am creating a personal app for email marketing/news letter/campaign, for this am using the Mailgun API with node.js and a simple HTML form to send emails.
As of now, sending emails is working fine when I give the "to"-address directly in my front part. But when I try to send to a mailing list, I encounter some issues.
I'm trying to send emails to a list which is already created in my Mailgun account.
My below post method is to send mails.
app.post('/', function(req, res) {
var api_key = 'key-here';
var domain = 'mydomin.in';
var Mailgun = require('mailgun-js');
var mailgun = new Mailgun({ apiKey: api_key, domain: domain });
var data = {
from: req.body.myname + "<" + req.body.email + ">",
to: req.body.to,
subject: req.body.subject,
text: req.body.plaintext,
'o:tag': req.body.tag
};
console.log(req.body);
mailgun.messages().send(data, function(error, body) {
console.log(body);
var list = mailgun.lists(req.body.to);
list.members().list(function (err, members) {
// `members` is the list of members
console.log(members);
});
if (error) {
// email not sent
res.render('index', { title: 'No Email', msg: 'Error. Something went wrong.', err: true })
} else {
// Yay!! Email sent
res.render('index', { title: 'Sent Email', msg: 'Yay! Message successfully sent.', err: false })
}
});
});
In the code I mention my mailing list. What happens is when I hit send, it shows success as in the following image:
Finally, here are some logs from the mailgun dashboard
Please point out what I did wrong and share your suggestions how to send emails to the list. My approach may be totally wrong, so any guidance will be appreciated.
NOTE: from my console.it shows "thank you,the messages are in queue". but am not receiving any mails yet. Many many thanks for any help.

Official docs
https://help.mailgun.com/hc/en-us/articles/217531258:
If you're on the Free plan without credit card information present or using your sandbox domain for testing, you're restricted to sending just to Authorized Recipients.

Related

Some emails from Nodemailer are not reaching the clients

I was sending register verification emails through Nodemailer using the code below, and it turns out that some of my clients are either not receiving anything or the email goes to spam. Some other clients can receive the email normally. I asked Google Support but they said it is not possible that the same kind of emails goes to some users' spam folder and some other users' inbox folder. That's why I am confused here.
BTW, Google confirmed with me that the DKIM and other verifications are good. And the emails that are sent have arrived at those clients' mailboxes. But without their approval, Google doesn't know if the email is not actually there or is sent to the spam folder.
function registerEmailSender(firstName, lastName, email, uuid) {
console.log('registerEmailSender is triggered');
console.log('email: ', email);
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'info#mydomain.com', // generated ethereal user
pass: 'mypassword' // generated ethereal password
},
});
const html = `
Hi ` + firstName + `,<br>
<br>
Please click the link to active your account: https://example.com/sessions/email-verification/` + uuid + `<br>
<br>
Sincerely, <br>
My Team<br>
`
const mailOptions = {
from: 'My Email <info#mydomain.com>', // sender address
to: email, // list of receivers
subject: 'Happy to have you here', // Subject line
html: html
};
return transporter.sendMail(mailOptions, function (err, info) {
console.log('sendMail is triggered');
// if(err)
// console.log('Error occurs: ', err)
// else
// console.log('Email sent: ', info);
if(err) {
console.log('Error occurs: ', err)
}
else {
console.log('Email sent: ', info);
}
});
}
It turns out nodemailer is not very reliable due to it is not recognized as a 'trusted application' unless your server itself is trusted by Google. And that seems to be reducing your reputation and cause the email to be rejected.
Best solution I can find for now is to use some paid mailing service like Mailchimp. Just don't use Nodemailer if you don't have to.

nodemailer not sending and returning error

I'm trying to setup a simple contact form using nodemailer. All i'm trying to do is send an email to my email from the contact form. My email is "myemail#mac.com"
When I do my axios post I get an error in the data object saying: 550 5.7.0 From address is not one of your addresses. but yet the status:200 and statusText:"OK"
When I use the same from email as the icloud email "myemail#mac.com" then it works ? I dont see anything where it says you have to use the same from address as the service address ?
Axios post:
const request = axios.post('http://localhost:3002/send', {'name':John Doe,'email':meme#gmail.com'});
request.then((result)=>{
console.log("request = ", result);
});
Error message from console.log("request = ", result);
error:{
code:"EMESSAGE",
command:"DATA",
response:"550 5.7.0 From address is not one of your addresses.",
responseCode:550
}
nodemailer is my node.js
const transporter = nodemailer.createTransport({
service: "iCloud",
auth: {
user: "myemail#mac.com",
pass: "myemailpassword"
}
})
app.use('/send', function(req, res){
var message = {
from: req.body.email,
to: 'myemail#mac.com',
subject: 'Message From Portfolio Contact Form',
//text: 'Plaintext version of the message',
html: '<p>'+req.body.description+'</p>'
};
transporter.sendMail(message, function(error, info){
if(error){
res.json({error: error});
}else{
res.json({success: info.response});
};
});
})
You configure nodemailer transport with iCloud Service and you are trying to send a mail with a gmail adresse.
from: req.body.email, // meme#gmail.com
to: 'myemail#mac.com'
Which logically produces the error:
response:"550 5.7.0 From address is not one of your addresses."
You probably want to do the inverse.

Using sendgrid how to know whether my email bounced or get succesfully delivered in my code

I am using Sendgrid npm module for sending emails to my customers with node.js, now i am facing a problem here, when i send an email to an email which does not exist then my email is getting bounced but in my response on my server code i am getting "success" but on my sendgrid's dashboard it is showing me email as bounced, now can anyone please tell me how can i know in my code that whether my code bounced or successfully sent.
My code is given below
var options = {
auth: {
api_user: 'abc',
api_key: 'pass'
}
}
var mailer = nodemailer.createTransport(sgTransport(options));
var email = {
to: email_id,
from: 'noreply#abc.com',
subject: 'ABC Verification Code',
text: "Your ABC Verification Code is " + totp
// html: '<b>Awesome sauce</b>'
};
mailer.sendMail(email, function(err, res) {
if (err) {
console.log(err);
res.json({success : 0, message : "Sorry Please try Again"});
return next();
} else {
console.log('res: ', res);
res.json({success : 1, message : "Successfully Sent Otp To Email Id"});
return next();
}
});
Also one more question here when i am sending my email using unsubscribed group id then my email is always getting delivered in gmail's "promotions" section can anyone please tell me how can i show my email to user in gmail's "updates" section.
The SendGrid API is asynchronous. Your request is accepted and then goes through several stages of processing including delivery. The API requests would take a very long time to respond if they had to wait for delivery to be attempted.
You have two options. The best option is to use the event webhook to receive events in real-time. There is some nodejs event webhook sample code:
var express = require('express');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.use(express.bodyParser());
});
app.post('/event', function (req, res) {
var events = req.body;
events.forEach(function (event) {
// Here, you now have each event and can process them how you like
processEvent(event);
});
});
var server = app.listen(app.get('port'), function() {
console.log('Listening on port %d', server.address().port);
});
Or you can poll your suppression lists via API, using e.g. the bounces endpoint.
There is no way to control which tab gmail uses to display your message, it's based on Google's analysis of the content of the messages and your sending habits.

Nodemailer doesn't send emails, and doesn't return an error message

I would like to know why nodemailer isn't sending emails, but it isn't returning any errors so I don't know what to do. Here's my code (pretty much copied from the nodemailer documentation):
var cors = require('cors');
var corsOptions = {
origin: 'http://davidmichael.me',
allowedHeaders: 'accept, content-type',
methods: 'GET, POST'
};
var nodemailer = require('nodemailer');
module.exports = function(app){
app.options('/email', cors(corsOptions));
app.post('/email', cors(corsOptions), function(req, res){
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'my-email',
pass: 'my-password'
}
});
var mailOptions = {
from: 'David Michael <my-email>',
to: 'recipient-email',
subject: 'Just verifying your email address ✔',
text: 'Hello to myself!',
html: '<p><b>Hello</b> to myself</p>'
};
var emailMessage = "";
transporter.sendMail(mailOptions, function(error, info){
if(error){
emailMessage = "there was an error :-(, and it was this: " + error.message;
}else{
emailMessage = "Message sent: " + info.response;
}
});
//transporter.close();
return res.json({
message: "success",
email: emailMessage
});
});
};
Every time I try it, it successfully returns the JSON object at the end as follows:
{"message":"success","email":""}
Perhaps I should note that I am using CORS because I want to take the user's email address. My client-side app sends a HTTP POST request with a JSON object containing their email address -- however, the current code doesn't do anything with that yet. I want to get the basic mechanism working first.
I am using Openshift. Could that make a difference?
Also, I have tried using non-Gmail email addresses, and the same thing happens.
Any ideas about where I'm going wrong?
Looks like you're returning your JSON response before the asynchronous method returns. Try putting the response inside the callback:
transporter.sendMail(mailOptions, function(error, info){
if(error){
emailMessage = "there was an error :-(, and it was this: " + error.message;
}else{
emailMessage = "Message sent: " + info.response;
}
return res.json({
message: "success",
email: emailMessage
});
});
//transporter.close();
You may not want to use this in practice though. Waiting for emails to send can be time-consuming and I suspect you'd see lots of timeouts. This should get you in the right direction though!
This also assumes your email address is all set up and you've entered real recipients as well. I know I had issues with Gmail because they're really good at detecting bots :)

Sending emails using Mailgun with NodeMailer package

A couple of days ago I realized that Google has changed the security of gmail accounts, particularly for the possibility of sending emails from applications. After Googling around for a while I couldn't find a fix for it.
So, I resorted to using Mailgun. I created an account and had it enabled with Business verification. However, I still can't send emails. I keep getting an error about the requested URL not being found.
I am suspecting that since I haven't set up a domain yet, it is not picking the mailgun domain it provided by default. Could someone show me how to test sending emails using Mailgun from NodeMailer indicating the sandbox name provided by mailgun.
thanks in advance
José
var nodemailer = require('nodemailer');
// send mail with password confirmation
var transporter = nodemailer.createTransport( {
service: 'Mailgun',
auth: {
user: 'postmaster#sandboxXXXXXXXXXXXXXXXX.mailgun.org',
pass: 'XXXXXXXXXXXXXXXX'
}
});
var mailOpts = {
from: 'office#yourdomain.com',
to: 'user#gmail.com',
subject: 'test subject',
text : 'test message form mailgun',
html : '<b>test message form mailgun</b>'
};
transporter.sendMail(mailOpts, function (err, response) {
if (err) {
//ret.message = "Mail error.";
} else {
//ret.message = "Mail send.";
}
});
I created the Nodemailer transport for mailgun.
Here it how it works.
You install the package with npm install as you would do with any package, then in an empty file:
var nodemailer = require('nodemailer');
var mg = require('nodemailer-mailgun-transport');
// This is your API key that you retrieve from www.mailgun.com/cp (free up to 10K monthly emails)
var auth = {
auth: {
api_key: 'key-1234123412341234',
domain: 'sandbox3249234.mailgun.org'
}
}
var nodemailerMailgun = nodemailer.createTransport(mg(auth));
nodemailerMailgun.sendMail({
from: 'myemail#example.com',
to: 'recipient#domain.com', // An array if you have multiple recipients.
subject: 'Hey you, awesome!',
text: 'Mailgun rocks, pow pow!',
}, function (err, info) {
if (err) {
console.log('Error: ' + err);
}
else {
console.log('Response: ' + info);
}
});
Replace your API key with yours and change the details and you're ready to go!
It worked me, when I added the domain also to the auth object (not only the api_key). Like this:
var auth = {
auth: {
api_key: 'key-12319312391',
domain: 'sandbox3249234.mailgun.org'
}
};

Resources