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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.