Search code examples
javascriptjquerymandrillmailgunsparkpost

Send an email from Chrome extension with Mailgun


I have a small Chrome extension that I use just for myself. Currently it uses Mandrill, but Mandrill is going to stop being free in about a month and I am looking for other ways to send emails from the extension.

What I need is something really simple, and pure Javascript-jQuery. I don't mind exposing an API key in the code since the extension is just for my own use. I've been looking at documentation in sites like Mailgun or SparkPost, but I can't find a simple and pure JavaScript example. For instance, this is the code I tried for Mailgun; it's raising a 404 even though I'm using my sandbox URL and it is active:

$.ajax({
    type: "POST",
    url: "MY SANDBOX URL",
    data: {
      'user':'api',
      'key': 'MY KEY',
      'from': 'SENDER EMAIL ADDRESS',
      'to': 'RECIPIENT EMAIL ADDRESS',
      'subject': 'Subject',
      'text': 'Body'
      }
    }).done(function(response) {
        console.log("Email sent");
 });

Please, could you help me? Thanks!


Solution

  • Sorry for the delay, I was really busy and thought this would take many hours of struggling so I did not try it until I had some time. In fact all the process took less than 30 minutes because SendGrid has a nice documentation and is very easy to use, at least for what I need. Thanks Adnan Umer for pointing me to this tool.

    Here is what I did:

    1) Create a free account. Allows up to 12k emails per month, more than enough for me.

    2) Wait until the account is provisioned. In my case this was instant, but there could be a delay sometimes, allegedly up to several hours.

    3) Generate a general API key here: https://app.sendgrid.com/settings/api_keys with full access to "Mail Send".

    4) Send an email adding an "Authorization" header, and the key as a "Bearer" token in that header.

    In my case this is working ok:

    $.ajax({
        type: "POST",
        url: "https://api.sendgrid.com/api/mail.send.json",
        headers: {
            'Authorization': 'Bearer ' + SENDGRID_API_KEY
        },
        data: {
            'to': EMAIL_ADDRESS_TO,
            'from': EMAIL_ADDRESS_FROM,
            'subject': 'Email subject',
            'html': 'Email body',
        }
    }).done(function(response) {
        console.log("Email sent");
    });
    

    Thank you all!