I'm doing a course that does not allow mw to use libraries and npm so this is the https request I have crafted
helpers.mailgunSendEmail = (toEmail, toName, subject, message, callback) => {
// validate parameters
const emailRegex = /\S+@\S+\.\S+/;
toEmail = typeof(toEmail) === 'string' && emailRegex.test(toEmail) ? toEmail.trim() : false;
toName = typeof(toName) === 'string' && toName.trim().length > 2 ? toName.trim() : false;
subject = typeof(subject) === 'string' && subject.trim().length > 2 ? subject.trim() : false;
message = typeof(message) === 'string' && message.trim().length > 2 ? message.trim() : false;
if (toEmail && toName && message) {
// Configure the request payload
const payload = {
'from' : 'Pizza App <weixinpua0227@gmail.com>',
'to' : "weixinpua0227@gmail.com",
'subject' : subject,
'text' : message
};
// Stringify the payload
const stringPayload = querystring.stringify(payload);
// Configure the request details
const requestDetails = {
'protocol' : 'https:',
'hostname' : 'api.mailgun.net',
'method' : 'POST',
'auth' : config.mailgun.mailgunCredential,
'path' : '/v3/' +config.mailgun.sandbox+ '/messages',
'headers' : {
'Content-type' : 'application/x-www-form-urlencoded',
'Content-length' : Buffer.byteLength(stringPayload)
}
};
// Instantiate the request object
let req = https.request(requestDetails, res => {
// Grab the status of the sent request
let status = res.statusCode;
// Callback successfully if the request went through
if (status == 200 || status == 201) {
callback(false);
} else {
callback(status);
}
});
this is how I call it
helpers.mailgunSendEmail("wxpua27@hotmail.com",'weixin','no subject','msg',(status)=>{
console.log(status)
});
this is where the sandbox domain is stored
mailgun:{
sandbox:"sandboxa3a26706f4b74f75b015e91df2f31ebb.mailgun.org",
mailgunCredential:"key-ba7409a41e533fcaecc0454cdf93475b"
}
I hardcoded my email(weixinpua0227@gmail.com)
into the code due to mailgun's sandbox only allowing mail to be sent to authorised user
my sandbox is also in US area so the hostname (api.mailgun.net) should be fine