'Error sending mail with Mailgun API within a docker
I'm using Mailgun API to send emails.
It's working in the local environment but when I create an image and run it with Docker I receive an error regarding the fetch.
I've checked and the env variables are correct.
The back-end code in node.js for sending the email:
const API_KEY = process.env.MAILGUN_API_KEY;
const DOMAIN = process.env.MAILGUN_DOMAIN_NAME;
const formData = require('form-data');
const Mailgun = require('mailgun.js');
const mailgun = new Mailgun(formData);
const client = mailgun.client({ username: 'api', key: API_KEY });
const sendEmail = async (to, subject, text) => {
try {
const messageData = {
from: `Noreply <noreply@${DOMAIN}>`,
to: to,
subject: subject,
text: text
};
const res = await client.messages.create(DOMAIN, messageData)
} catch (error) {
console.error(error);
return error;
}
}
sendEmail("[email protected]", "aa", "aa");
The error received in the docker container:
docker-firebase-1 | (node:1) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time
docker-firebase-1 | (Use `node --trace-warnings ...` to show where the warning was created)
TypeError: fetch failed
docker-firebase-1 | at Object.processResponse (node:internal/deps/undici/undici:5570:34)
docker-firebase-1 | at node:internal/deps/undici/undici:5896:42
docker-firebase-1 | at node:internal/process/task_queues:140:7
docker-firebase-1 | at AsyncResource.runInAsyncScope (node:async_hooks:202:9)
docker-firebase-1 | at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8) {
docker-firebase-1 | cause: TypeError: object2 is not iterable
docker-firebase-1 | at action (node:internal/deps/undici/undici:1651:39)
docker-firebase-1 | at action.next (<anonymous>)
docker-firebase-1 | at Object.pull (node:internal/deps/undici/undici:1699:52)
docker-firebase-1 | at ensureIsPromise (node:internal/webstreams/util:172:19)
docker-firebase-1 | at readableStreamDefaultControllerCallPullIfNeeded (node:internal/webstreams/readablestream:1884:5)
docker-firebase-1 | at node:internal/webstreams/readablestream:1974:7
docker-firebase-1 | }
Solution 1:[1]
After some testing, I found the source of the problem was in the image's version of node I've been using in the Dockerfile.
I've been using the image node: alpine which does not support the fetch API the mailgun.js is using (because it is a slimmer version of node).
I've switched up to node:16.14.2-buster and it's now working.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alon Ben Yaakov |
