question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unable to send from localhost (works on Vercel-hosted site)

See original GitHub issue

I’m trying to use MailGun with a NextJS website and API routes. In the hosted site, the code works as expected and returns the “Queued. Thank you.” message.

On my local computer, when running using next dev, I’m unable to get the messages.create(...) function to work - it instead returns only [Error] { status: undefined, message: undefined, details: undefined }.

The code I’m using is given below (all of the environment variables can be logged and have values - the MG_API_KEY is taken from https://app.mailgun.com/app/account/security/api_keys (private API key) but I also tried generating and using a “Sending API Key” under https://app.mailgun.com/app/sending/domains/mydomainhere/sending-keys):

import Mailgun from 'mailgun.js'
import FormDataPackage from 'form-data'

const MG_API_KEY = process.env.MG_API_KEY as string

const mailgun = new Mailgun(FormDataPackage)
const mg = mailgun.client({ username: 'api', key: MG_API_KEY, url: 'https://api.mailgun.net' })

export type EmailContent = {
  to: string | string[]
  subject: string
  bodyPlain: string
  body?: string
  from?: string
}

export const sendMailApi = async (emailContent: EmailContent) => {
  const { to, subject, body, bodyPlain } = emailContent
  const from = emailContent.from ?? process.env.EMAIL_FROM_MG
  
  return mg.messages
    .create('mydomainhere', {to, subject, text: bodyPlain, html: body, from})
    .then((msg) => {
      return msg
    })
    .catch((err) => {
      return err
    })
}

where ‘mydomainhere’ is the string taken from https://app.mailgun.com/app/sending/domains under “name”.

Is this expected behaviour, or should this work? Do I need to change some configuration detail when sending on localhost?

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
olexandr-mazepacommented, Nov 16, 2022

It seems like this issue is more related to the local environment than to the SDK itself. Error handling was updated some time ago in version 7.0.1 So I am closing this issue. Feel free to open a new issue if you see places for improvement in this area. @chrisb2244, thank you for your input.

1reaction
chrisb2244commented, Jun 8, 2022

Sure - I’m using Windows Subsystem for Linux 2 with Docker containers to host a local development environment for my NextJS site, using a Docker engine directly inside WSL2 (not one installed in Windows, using e.g. Docker Desktop for Windows).

I suspect (although I haven’t tested) that if I used a Docker engine in the Windows OS, this might not happen, so it might be a corner case.

In any case, I installed Docker in WSL2 using something like apt-get install docker-ce-cli docker-ce, and then run the site using docker compose, shown below:

services:
    react:
        build:
            dockerfile: Dockerfile
            context: frontend
        image: my-react-frontend
        container_name: my-react
        ports:
            - "3000:3000"
        volumes:
            - ./frontend/src:/usr/app/src
            - ./frontend/public:/usr/app/public
        networks:
            - my-react-network
networks:
    my-react-network:
        driver: bridge

I’m unsure if the bridge network might also be a contributing factor here. Previously I placed a database (using a mysql image) in the same compose file, but I’ve since replaced that. I’ll test after posting if removing the bridge network leaves me with a better/worse/unchanged situation. Removing the bridge network (and falling back on the default, which for Linux Docker is I believe just a different bridge) makes no difference.

The Dockerfile probably doesn’t have anything unusual, it’s running from node:16.13.0, as USER node and the command is CMD ["npm", "run", "dev"].

The triggering code I gave above is used in an API Route, at (in this case) pages/api/sendMailTest.ts.

pages/api/sendMailTest.ts

import { sendMailApi } from "@/lib/sendMail";
import type { NextApiHandler } from "next";

const sendMailTest: NextApiHandler = async (req, res) => {
  const now = Date.now().toString()
  return sendMailApi({
    to: 'myemailaddress@gmail.com',
    subject: 'test email',
    body: now,
    bodyPlain: now
  }).then((msg) => {
    res.status(200).send('success')
  }).catch((err) => {
    console.log(err)
    res.status(500).json(err)
  })

}

export default sendMailTest

This allows me to trigger the function by navigating to http://localhost:3000/api/sendMailTest, which is convenient for testing.

My updated sendMailApi function is copied below (but basically a variation on the one in a previous comment).

lib/sendMail.ts

import Mailgun from 'mailgun.js'
import FormDataPackage from 'form-data'

const MG_API_KEY = process.env.MG_API_KEY as string

const mailgun = new Mailgun(FormDataPackage)
const mg = mailgun.client({ username: 'api', key: MG_API_KEY, url: 'https://api.mailgun.net' })

export type EmailContent = {
  to: string | string[]
  subject: string
  bodyPlain: string
  body?: string
  from?: string
}

export const sendMailApi = async (emailContent: EmailContent) => {
  const { to, subject, body, bodyPlain } = emailContent
  const from = emailContent.from ?? process.env.EMAIL_FROM_MG

  return mg.messages
    .create('mg.mydomain.org', {to, subject, text: bodyPlain, html: body, from})
    .then((msg) => {
      return msg
    })
    .catch((err) => {
      return err
    })
}

The problem can be resolved by adjusting the DNS nameservers produced by WSL on startup - more specifically, by default there is no file at /etc/wsl.conf, and /etc/resolv.conf contains something like the following:

# This file was automatically generated by WSL. To stop automatic generation of this file, add the following entry to /etc/wsl.conf:
# [network]
# generateResolvConf = false
nameserver ipaddress.of.host.adaptor

Modifying it by following the instructions (add the wsl.conf file) and writing something like

# /etc/resolv.conf 
nameserver 8.8.8.8

allows emails to be sent (but can cause other issues with WSL, so it’s a bit fiddly - setting it like this prevents me from connecting to other systems via SSH or remote desktop within my workplace network). I think adding both lines might fix both issues, but I haven’t gotten around to finding a suitable way to generate and adapt the resolv.conf file on startup for that.

Read more comments on GitHub >

github_iconTop Results From Across the Web

localhost didn't send any data. · Issue #10319 · vercel/next.js
It worked. I belive this error because you start vs code run as admin, then you install a packge and next time you...
Read more >
Dynamic table of contents won't deploy on Vercel (... but works ...
The code is running perfectly on my localhost, but as soon as I'm deploying it to vercel I got this error: TypeError: Cannot...
Read more >
Errors – Vercel Docs
A list of errors provided by Vercel CLI or the REST API, with details on how they occur and how to resolve them....
Read more >
Serverless deployments via Vercel using Node.js
Running serverless functions through Vercel CLI eliminates backend work ... With it, you can host websites and web applications that deploy ...
Read more >
Use Next.js and Vercel to build a link-sharing app using ...
Ensure that your server is running and then open two or more tabs at https://localhost:3000. Find an article online, and submit its URL....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found