Reputation: 11
I'm developing a NextJS application with typescript, trying to set up mailgun.
I have this mailgun.ts
setup file:
import config from "@/config";
import Mailgun, { MessagesSendResult } from "mailgun.js";
import formData from "form-data";
const mailgun = new Mailgun(formData);
const mg = mailgun.client({
username: "api",
key: process.env.MAILGUN_API_KEY || "dummy",
url: "https://api.eu.mailgun.net/",
});
if (!process.env.MAILGUN_API_KEY && process.env.NODE_ENV === "development") {
console.group("⚠️ MAILGUN_API_KEY missing from .env");
console.error("It's not mandatory but it's required to send emails.");
console.error("If you don't need it, remove the code from /libs/mailgun.js");
console.groupEnd();
}
/**
* Sends an email using the provided parameters.
*
* @async
* @param {Object} params - The email parameters.
* @param {string} params.to - The recipient's email address.
* @param {string} params.subject - The subject of the email.
* @param {string} [params.text] - The plain text content of the email.
* @param {string} [params.html] - The HTML content of the email.
* @param {string} [params.replyTo] - The email address to set as the "Reply-To" address.
* @returns {Promise<MessagesSendResult>} A Promise that resolves when the email is sent.
*/
export const sendEmail = async ({
to,
subject,
text,
html,
replyTo,
}: {
to: string;
subject: string;
text?: string;
html?: string;
replyTo?: string;
}): Promise<MessagesSendResult> => {
const data = {
from: config.mailgun.fromAdmin,
to: [to],
subject,
text,
html,
...(replyTo && { "h:Reply-To": replyTo }),
};
return mg.messages.create(
(config.mailgun.subdomain ? `${config.mailgun.subdomain}.` : "") +
config.domainName,
data
);
};
Then in my .local.env
I have my MAILGUN_API_KEY
set up. It's the right one, I double checked, recreated it... everything. However, when I try to send an email from a component with sendEmail()
where email is inserted by the user:
// Send a welcome email to the user
await sendEmail({
to: email,
subject: "Welcome to TheName",
text: "Welcome to TheName! We're excited to have you on board. We'll let you know as soon as we launch.",
});
I always get a 401 (authentication) error:
mailgun.ts:54
POST https://api.eu.mailgun.net/v3/mail.thename.baby.thename.baby/messages 401 (Unauthorized)
sendEmail @ mailgun.ts:54
handleSubmit @ ButtonLead.tsx:26
I know many people get this error due to not having configured the url properly for EU (see this). However this is not my case, I have the "eu" zone setup correctly. I checked with a simple logging, and the problem isn't that the API key is wrong, the problem seems to be that the code isn't able to read the env variable for some reason (I get undefined). Any ideas?
Tried:
Upvotes: 1
Views: 19