This commit is contained in:
2025-05-26 14:48:41 -06:00
parent f87c888a96
commit 8d75a36a64
5 changed files with 809 additions and 817 deletions

View File

@@ -1,216 +1,64 @@
import type { APIRoute } from "astro";
import nodemailer from "nodemailer";
export const prerender = false;
const sendEmailViaJMAP = async ({
const sendEmailViaSMTP = async ({
subject,
message,
}: {
subject: string;
message: string;
}) => {
const accessToken = process.env.JMAP_ACCESS_TOKEN
? process.env.JMAP_ACCESS_TOKEN
: import.meta.env.JMAP_ACCESS_TOKEN;
const accountId = process.env.JMAP_ACCOUNT_ID
? process.env.JMAP_ACCOUNT_ID
: import.meta.env.JMAP_ACCOUNT_ID;
// Get environment variables
const smtpHost = process.env.SMTP_HOST
? process.env.SMTP_HOST
: import.meta.env.SMTP_HOST;
const smtpPort = process.env.SMTP_PORT
? parseInt(process.env.SMTP_PORT)
: parseInt(import.meta.env.SMTP_PORT || "587");
const smtpUser = process.env.SMTP_USER
? process.env.SMTP_USER
: import.meta.env.SMTP_USER;
const smtpPassword = process.env.SMTP_PASSWORD
? process.env.SMTP_PASSWORD
: import.meta.env.SMTP_PASSWORD;
const fromEmail = process.env.FROM_EMAIL
? process.env.FROM_EMAIL
: import.meta.env.FROM_EMAIL;
const toEmail = process.env.TO_EMAIL
? process.env.TO_EMAIL
: import.meta.env.TO_EMAIL;
const apiUrl = "https://api.fastmail.com/jmap/api/";
if (!accessToken || !accountId || !fromEmail || !toEmail) {
throw new Error("Missing environment variables configuration");
if (!smtpHost || !smtpUser || !smtpPassword || !fromEmail || !toEmail) {
throw new Error("Missing SMTP configuration environment variables");
}
const headers = new Headers({
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
Accept: "application/json",
const transporter = nodemailer.createTransport({
host: smtpHost,
port: smtpPort,
secure: smtpPort === 465,
auth: {
user: smtpUser,
pass: smtpPassword,
},
});
try {
// Get email identities
const identityRequest = {
using: ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:submission"],
methodCalls: [
[
"Identity/get",
{
accountId,
properties: ["id", "email", "name"],
},
"0",
],
],
};
await transporter.verify();
const identityResponse = await fetch(apiUrl, {
method: "POST",
headers,
body: JSON.stringify(identityRequest),
const info = await transporter.sendMail({
from: fromEmail,
to: toEmail,
subject: subject,
text: message,
html: `<pre>${message}</pre>`,
});
const identityData = await identityResponse.json();
const identity = identityData.methodResponses[0][1].list.find(
(id: any) => id.email === fromEmail,
);
if (!identity) {
throw new Error(`No identity found for email: ${fromEmail}`);
}
// Get drafts mailbox
const mailboxRequest = {
using: ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"],
methodCalls: [
[
"Mailbox/get",
{
accountId,
properties: ["id", "role"],
},
"0",
],
],
};
const mailboxResponse = await fetch(apiUrl, {
method: "POST",
headers,
body: JSON.stringify(mailboxRequest),
});
const mailboxData = await mailboxResponse.json();
const drafts = mailboxData.methodResponses[0][1].list.find(
(box: any) => box.role === "drafts",
);
if (!drafts) {
throw new Error("Could not find Drafts folder");
}
// Create email draft
const emailRequest = {
using: [
"urn:ietf:params:jmap:core",
"urn:ietf:params:jmap:mail",
"urn:ietf:params:jmap:submission",
],
methodCalls: [
[
"Email/set",
{
accountId,
create: {
"draft-1": {
mailboxIds: { [drafts.id]: true },
from: [{ email: fromEmail, name: identity.name }],
to: [{ email: toEmail }],
subject,
bodyValues: {
body1: {
value: message,
charset: "utf-8",
},
},
textBody: [
{
partId: "body1",
type: "text/plain",
},
],
},
},
},
"0",
],
],
};
const emailResponse = await fetch(apiUrl, {
method: "POST",
headers,
body: JSON.stringify(emailRequest),
});
const emailResult = await emailResponse.json();
const createdId = emailResult.methodResponses[0][1].created["draft-1"].id;
// Submit email with identity
const submitRequest = {
using: [
"urn:ietf:params:jmap:core",
"urn:ietf:params:jmap:mail",
"urn:ietf:params:jmap:submission",
],
methodCalls: [
[
"EmailSubmission/set",
{
accountId,
create: {
"submit-1": {
emailId: createdId,
identityId: identity.id,
envelope: {
mailFrom: {
email: fromEmail,
},
rcptTo: [{ email: toEmail }],
},
},
},
},
"0",
],
],
};
const submitResponse = await fetch(apiUrl, {
method: "POST",
headers,
body: JSON.stringify(submitRequest),
});
const submitResult = await submitResponse.json();
if (!submitResult.methodResponses[0][1].created?.["submit-1"]) {
throw new Error(`Submission failed: ${JSON.stringify(submitResult)}`);
}
const deleteRequest = {
using: ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"],
methodCalls: [
[
"Email/set",
{
accountId,
destroy: [createdId],
},
"0",
],
],
};
const deleteResponse = await fetch(apiUrl, {
method: "POST",
headers,
body: JSON.stringify(deleteRequest),
});
const deleteResult = await deleteResponse.json();
if (!deleteResult.methodResponses[0][1].destroyed?.includes(createdId)) {
console.warn("Failed to delete draft email", deleteResult);
}
return { success: true };
console.log("Message sent: %s", info.messageId);
return { success: true, messageId: info.messageId };
} catch (error) {
console.error("JMAP Error:", error);
console.error("SMTP Error:", error);
throw error;
}
};
@@ -230,7 +78,7 @@ export const POST: APIRoute = async ({ request }) => {
);
}
await sendEmailViaJMAP({ subject, message });
await sendEmailViaSMTP({ subject, message });
return new Response(
JSON.stringify({ success: true, message: "Email sent successfully" }),