import Mailgun from "mailgun.js" import FormData from "form-data" import { singleton } from "./singleton.server" import { ENCRYPT_SECRET, MAILGUN_APIKEY, MAILGUN_DOMAIN, } from "~/lib/env.server" import type { MailgunMessageData } from "mailgun.js/interfaces/Messages" import { IS_PROD } from "./constants" import { APP_NAME, OUR_DOMAIN, SITE_URL } from "./env" import { SubscribeFormData } from "./types" import { getSite } from "~/models/site.model" import { type Site } from "~/lib/db.server" import Iron from "@hapi/iron" import mjml from "mjml" import { getSiteLink } from "./helpers" const enableMailgun = Boolean(MAILGUN_APIKEY && MAILGUN_DOMAIN) const getClient = () => singleton("mailgun", () => { const mg = new Mailgun(FormData) const client = mg.client({ username: "api", key: MAILGUN_APIKEY, timeout: 60000, }) return client }) const sendEmail = async (message: MailgunMessageData) => { console.log(message) if (!enableMailgun) { console.error( "not sending email because no mailgun apikey or domain configured" ) return } const client = getClient() await client.messages.create(MAILGUN_DOMAIN, message).then(console.log) } export const sendLoginEmail = async (payload: { token: string email: string url: string subscribeForm?: SubscribeFormData }) => { const { protocol, host, pathname } = new URL(payload.url) const query = new URLSearchParams([ ["token", payload.token], ["next", `${protocol}//${host}${pathname}`], ]) if (payload.subscribeForm) { query.append("subscribe", JSON.stringify(payload.subscribeForm)) } const loginLink = `${ IS_PROD ? "https" : "http" }://${OUR_DOMAIN}/api/login?${query.toString()}` let subject = `Sign in to ${APP_NAME}` let html = `
Hello,
We received a request to sign in to ${APP_NAME} using this email address, please click the link below to sign in:
Sign in to ${APP_NAME}This link will expire in 10 minutes. If you did not request this link, you can safely ignore this email.
Thanks,
Your Proselog Team
` if (payload.subscribeForm) { const site = await getSite(payload.subscribeForm.siteId) subject = `Confirm your subscription to ${site.name}` html = `Please confirm your subscription to ${site.name} by clicking the link below:
confirmThis link will expire in 10 minutes.
` } const message: MailgunMessageData = { from: `${APP_NAME}