MailGun results in 401 forbidden using nodeJs - node.js

I am trying to send an email using mailgun and nodejs.
I took the code MailGun provides you and added my domain name and api key:
const mailgun = require('mailgun-js');
const DOMAIN = 'mail.mywebsite.com';
const mg = mailgun({apiKey: "this-is-myApiKey", domain: DOMAIN});
const data = {
from: 'Support <support#mywebsite.com>',
to: 'myemail#gmail.com',
subject: 'Hello',
text: 'Testing some Mailgun awesomness!'
};
mg.messages().send(data, function (error, body) {
console.log(1, error);
console.log(2, body);
});
This results in a 401 forbidden, but if I change to my sandbox domain name, then it works. Does anyone have some helpful tips to fix this?
mail.mywebsite.com = domain name set under sending domains
this-is-myApiKey = my private api key found here: https://app.mailgun.com/app/account/security/api_keys

It could be due to incorrect domain name of mailgun. Make sure that you are using the correct apikey and domain name.

Might your Domain Name issue.
const mailgun = require("mailgun-js")({
apiKey: 'your_api_key',
domain: 'mg.yourDomainName.com'
});
const data = {
from: "no-reply#yourDomainName.com",
to: 'abcd#gmail.com',
subject: 'Hello',
text: 'Testing some Mailgun awesomeness!'
};
mailgun.messages().send(data, (error, body) => {
console.log(body);
if(!error)
res.status(200).json({
message:"mail sent"
})
});

That's because in new mailgun api v3 you have to follow a different approach:
See my sample code below its working:
var formData = require('form-data');
const Mailgun = require('mailgun.js');
const mailgun = new Mailgun(formData);
const mg = mailgun.client({
username: 'api',
key: process.env.EMAIL_MAILGUN_API_KEY
});
mg.messages.create(process.env.EMAIL_MAILGUN_HOST, {
from: "sender na,e <"+process.env.EMAIL_FROM+">",
to: ["dan#dominic.com"],
subject: "Verify Your Email",
text: "Testing some Mailgun awesomness!",
html: "<h1>"+req+"</h1>"
})
.then(msg => {
console.log(msg);
res.send(msg);
}) // logs response data
.catch(err => {
console.log(err);
res.send(err);
}); // logs any error

make sure to utilize the DNS name you verified. i was trying to use my domain name (as everything in their documentation seems to dictate) and repeatedly faced HTTP 401 errors. as soon as i changed DOMAIN_NAME to VERIFIED_DNS_NAME it worked.
e.g., my domain was blahblah.com. however, the DNS name i verified was mg.blahblah.com. when i changed my client to utilize that verified DNS name, it all worked

Related

how do i send emails using mail-gun in my express app

i new to mail-gun i'm trying to send an email after successful payment, but each time the payment is cofirmed , i don't get an email
this how i use it
const domain = 'https://app.mailgun.com/app/sending/domains/sandbox18d7fe3d7f4c6baf525.mailgun.org ';
var mailgun = require('mailgun-js')({
apiKey: "MY_APIKEY",
domain: domain
});
this is my email template
stripe.charges
.create(newCharge, function(err, charge) {
// send response
if (err) {
console.error(err);
res.json({ error: err, charge: false });
} else {
var emailTemplate = `Hello ${newCharge.shipping.name}, \n
Amount: ${newCharge.amount} \n
Thank you!`;
// compose email
var emailData = {
from: "no-reply#YOUR-DOMAIN.com",
to: req.body.email,
subject: "Bundle of Sticks Receipt - " + charge.id,
text: emailTemplate
};
// send email to customer
mailgun.messages().send(emailData);
emailData["to"] = "your_support_email#gmail.com";
emailData["subject"] = `New Order: Bundle of Sticks - ${charge.id}`;
// send email to supplier
mailgun.messages().send(emailData);
// send response with charge data
res.json({ error: false, charge: charge });
}
})
how can i go about this , the payment is always successful but the email dont go through
You should install nodemailer and nodemailer-mailgun-transport and work with those.
And using those it will work a little something like this:
import * as nodemailer from 'nodemailer';
import * as mailGun from 'nodemailer-mailgun-transport';
const auth = {
api_key: <YOUR_API_KEY>
domain: <YOUR_DOMAIN>,
}
const transporter = nodemailer.createTransport(mailGun(auth));
const mailOptions = {
sender: "John Doe",
from: email,
to: '<WHATEVER_EMEIL>',
subject: '<YOUR_SUBJECT>',
text: '<YOUR_TEXT>',
};
transporter.sendMail(mailOptions);
Just edit those to suit your need and variables, but that's generally the approach.

Mailgun console.log(body) returning undefined

I am using Mailgun to send email when user click on button to book.
The following is my code:
import mailgun from 'mailgun-js';
const book = () => {
const DOMAIN = 'azaleflowerbar.com';
const api_key = '**********5d721598c7d08095-07bc7b05-******'; //hidden for privacy
const mg = mailgun({apiKey: api_key, domain: DOMAIN, host: "api.eu.mailgun.net"});
const data = {
from: 'Excited User <me#samples.mailgun.org>',
to: 'myemail#gmail.com, ',
subject: 'Hello',
text: 'Testing some Mailgun awesomness!'
};
mg.messages().send(data, function (error, body) {
if (error) {
console.log(error)
}
console.log(body);
});
}
What i get though from console.log(body) is "undefined".
I have tried this same code with the sandbox and it works fine (the message is queued).
Also, mailgun DNS for my domain are verified.
I am in touch with mailgun support but they cannot be of any help.
Any help would be much appreciated

Unable to send email using MailGun Node API

When trying to send a simple test message via mailgun using their Node api I don't get any errors, but I also am not receiving emails nor am I seeing any response in the mailgun logs.
Here is the code I am using ...
const mailgun = require('mailgun-js')({
apiKey: 'XXXXXXXXXX',
domain: 'https://api.mailgun.net/v3/XXXXXXXXX'
})
async function sendInvite() {
var email = process.argv[process.argv.length - 1]
const data = {
from: 'support#acme.com',
to: email,
subject: 'Welcome!',
html: '<p>Welcome!</p><p>You are very special!</p>'
}
return new Promise((resolve, reject) => {
mailgun.messages().send(data, (error, body) => {
if (error) {
console.error(error)
reject(error)
return
}
console.log(`Invite sent to ${email}`)
console.log(data)
console.log(body)
resolve();
})
})
}
sendInvite().then(() => console.log('Done')).catch((err) => console.error(err))
I discovered that the problem I had was in the format of the domain I was passing into mailgun.
Before I had the following :
const mailgun = require('mailgun-js')({
apiKey: 'XXXXXXXXXX',
domain: 'https://api.mailgun.net/v3/XXXXXXXXX'
})
The problem is that the value for domain should not include the https://api.mailgun.net/v3/ portion of the URL. Instead it should ONLY have your domain, e.g. mail.mydomain.com
Did you attach your credit card to mailGun account? Or if you just need to test your logic, in your account settings you should confirm any email address, which will get emails from mailgun
https://wordpress.org/support/topic/mailgun-http-api-test-failure-status-free-accounts-are-for-test-purposes-only/

Sending emails to a mailing list with Mailgun

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.

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