Skip to content

⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.

1.4 KB
Raw Blame
import { readFileSync } from "fs";
import path from "path";
import Handlebars from "handlebars";
import transporter from "@linkwarden/lib/transporter";

type Params = {
  identifier: string;
  url: string;
  from: string;
  token: string;
};

export default async function sendVerificationRequest({
  identifier,
  url,
  from,
  token,
}: Params) {
  const emailsDir = path.resolve(process.cwd(), "templates");

  const templateFile = readFileSync(
    path.join(emailsDir, "verifyEmail.html"),
    "utf8"
  );

  const emailTemplate = Handlebars.compile(templateFile);

  const { host } = new URL(url);
  const verifyUrl = `${
    process.env.BASE_URL
  }/auth/verify?token=${token}&email=${encodeURIComponent(identifier)}`;
  const result = await transporter.sendMail({
    to: identifier,
    from: {
      name: "Linkwarden",
      address: from as string,
    },
    subject: `Please verify your email address`,
    text: text({ url: verifyUrl, host }),
    html: emailTemplate({
      url: verifyUrl,
    }),
  });
  const failed = result.rejected.concat(result.pending).filter(Boolean);
  if (failed.length) {
    throw new Error(`Email (${failed.join(", ")}) could not be sent`);
  }
}

/** Email Text body (fallback for email clients that don't render HTML, e.g. feature phones) */
function text({ url, host }: { url: string; host: string }) {
  return `Sign in to ${host}\n${url}\n\n`;
}