Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unauthorized Error when calling mg.messages.create() #411

Open
srestraj opened this issue Apr 16, 2024 · 5 comments
Open

Unauthorized Error when calling mg.messages.create() #411

srestraj opened this issue Apr 16, 2024 · 5 comments

Comments

@srestraj
Copy link

srestraj commented Apr 16, 2024

I have a Next.js 14 project deployed on Vercel, where I've integrated the Mailgun API to send emails using this package. The integration works fine locally. However, after deploying to production on Vercel, I'm consistently encountering an "Unauthorized" error when attempting to send emails via the Mailgun API.

I've already added Vercel's IP, i.e. 76.76.21.21 to our domain's whitelist on Mailgun, but still no luck.

I've thoroughly checked and verified the API keys, environment variables and permissions and they're all fine. I've also included my code below for reference.

import { NextRequest, NextResponse } from "next/server";
import FormData from "form-data";
import Mailgun from "mailgun.js";

const { MAILGUN_EMAIL, MAILGUN_TO_EMAIL, MAILGUN_API, MAILGUN_DOMAIN } =
  process.env;

export async function POST(request: NextRequest, res: NextResponse) {
  const { name, email, ticketCount, attendingAs, exhibitorDetails } =
    await request.json();

  const mailgun = new Mailgun(FormData);

  try {
    const mg = mailgun.client({
      username: "api",
      key: MAILGUN_API as string,
    });

    const mailData = {
      from: MAILGUN_EMAIL,
      to: MAILGUN_TO_EMAIL,
      subject: `${name} just signed up for the expo`,
      text: `${name} just signed up for ${ticketCount} tickets as ${attendingAs} for the expo with email: ${email}.`,
      html: `
      <body>
        <div style="background: #f7f7f7; padding: 20px 0; margin:0">
           body content here
        </div>
      </body>`,
    };

    await new Promise((resolve, reject) => {
      mg.messages
        .create(MAILGUN_DOMAIN as string, mailData)
        .then((message) => {
          resolve(message);
        })
        .catch((error) => {
          reject(error);
          return NextResponse.json({ error: error }, { status: error.status });
        });
    });
    return NextResponse.json(
      {
        message:
          "Thank you for your interest in attending the expo. We hope to see you there.",
      },
      { status: 200 }
    );
  } catch (error: any) {
    return NextResponse.json({ error: error }, { status: error.status });
  }
}

I've also attached a screenshot below for reference.
image

@dalaverd
Copy link

I am getting the same issue

@kodobrody
Copy link

same

@srestraj
Copy link
Author

So I came across one Vercel article, which suggests that on the free plan, we don't have the option to create custom IP for our domains as Vercel deployments use a range of IP addresses that can't be easily specified for Mialgun's IP Allowlist. So, we have two options:

  • Allow all internet traffic (not recommended): This is the simplest solution but poses security risks. If you must go this route, you can add "0.0.0.0/0" to your Allowlist.
  • Use Vercel Secure Compute (for Enterprise plans): This creates a private network with dedicated IP addresses for your deployment. You can then add these IPs to your Mailgun Allowlist for enhanced security.

@tayyabmughal676
Copy link

I resolved the 401 Unauthorized error by adding 0.0.0.0/0 to my IP Access Management in Mailgun. This might not be the ideal solution, but it worked for me. If you're facing the same issue, you can try this approach.

@suarez9093
Copy link

suarez9093 commented Sep 11, 2024

Running into the same issue testing locally. When running the curl example the email goes through. When trying the node example getting the same 401 error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants