Send an email through Mailgun API without using their SDK.

Not in a situation to import libraries? here's a tiny trick you can use.

·

2 min read

If you were stuck in a situation where importing libraries is not an option and have to use vanilla JS to automate sending an email through Mailgun, then I must say you are good at googling cause you found this article.

I was in a similar situation where airtable's scripting feature wasn't allowing me to import libraries on their online IDE. So to make a way around it I was going through the docs of mailgun and realized that they support curl (which is a command line tool using which one can send emails from their CLI). Henceforth there must be a way to send emails without using their SDK. So after a good session of research this is the essential code part that I could come up with which lets you send emails through mailgun.

Important detail here: You will have to base64 encode your API key in this format, api:YOUR_API_KEY

let formData = new FormData();

formData.append('from','sender@mailaddress.com');
formData.append('to', 'reciever@mailaddress.com');
formData.append('cc', 'anyone@else.com');
formData.append('subject', 'This mail was sent through mailgun!');
formData.append('text', 'lorem ipsum dollar amit');

let domainName = 'mg.your-domain-name-here.com';

async function sendMailgunEmail() {

//the link below has a domainName specific to your account
    await fetch(`https://api.mailgun.net/v3/${domainName}/messages`, {
        method: 'POST',
        body: formData,
        headers: {
            'Authorization': 'Basic put_your_base64_encoded_string_here'
        },
    })
    .then(response => {
        if(response.status == '200'){
            console.log('email sent successfully!');
        } else {
            console.log('email NOT sent, please try again later or contact your developer')
        }
    })
    .catch((error) => {
        console.error('Error:', error);
    });

}

await sendMailgunEmail();

But why encode? here's what the docs say

image.png

Also, please do give this document a thorough read to have a deeper understanding (this was linked in the docs as well) of how this works.

Let me know how it went, if you find a better way around this then please do feel free to comment it down below. May your automation automate!