mailgunnext-auth

How to configuring Mailgun for NextAuth


I am trying to use Mailgin as Email provider uses email to send "magic links" that can be used to sign in.

import clientPromise from "@/app/lib/connectDb";
import NextAuth from "next-auth";
import EmailProvider from "next-auth/providers/email";

import { MongoDBAdapter } from "@next-auth/mongodb-adapter";

const handler = NextAuth({
    adapter: MongoDBAdapter(clientPromise),
    providers: [
        EmailProvider({
            server: {
                host: process.env.EMAIL_SERVER_HOST,
                port: process.env.EMAIL_SERVER_PORT,
                auth: {
                    user: process.env.EMAIL_SERVER_USER,
                    pass: process.env.EMAIL_SERVER_PASSWORD,
                },
            },
            from: process.env.EMAIL_FROM,
            maxAge: 10 * 60, // Magic links are valid for 10 min only
        }),
    ],

     
});

export { handler as GET, handler as POST };

env variables are:

MAIL_SERVER_HOST="smtp.mailgun.org"
EMAIL_SERVER_PORT="587"
EMAIL_SERVER_USER="postmaster@mydomain"
EMAIL_SERVER_PASSWORD="key-**********"

I get an error
message: 'Invalid login: 535 Authentication failed'


Solution

  • Setting up NextAuth's EmailProvider with Mailgun (via SMTP)

    Given you likely won't reuse all 4 SMTP environment variables outside of this one file (or import them in isolation throughout your app), you can simplify the EmailProvider's server configuration as follows:

    EmailProvider({
      from: process.env.EMAIL_FROM,
      server: process.env.EMAIL_SERVER, 
      maxAge: 10 * 60, // Magic links are valid for 10 min only
    }),
    

    Then consolidate the environment variables:

    # Email Sender Info
    EMAIL_FROM=My App <name@mydomain.com>
    
    # Magic Link Email Server
    EMAIL_SERVER=smtp://postmaster@mydomain.com:smtp_password@smtp.mailgun.org:587
    

    Good to know: If your Mailgun account is hosted in Europe, the host becomes: smtp.eu.mailgun.org