Skip to content

Commit 038d353

Browse files
committed
Adding HTML support to Resend for rich email content
1 parent ebd7266 commit 038d353

File tree

2 files changed

+21
-9
lines changed

2 files changed

+21
-9
lines changed

app/api/send-email/route.ts

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ type EmailRequestBody = {
66
cc?: string;
77
subject?: string;
88
message?: string;
9+
html?: string;
910
};
1011

1112
export async function POST(request: Request) {
@@ -20,7 +21,7 @@ export async function POST(request: Request) {
2021
);
2122
}
2223

23-
const { to, cc, subject, message } = payload;
24+
const { to, cc, subject, message, html } = payload;
2425

2526
if (!to) {
2627
return NextResponse.json(
@@ -29,7 +30,10 @@ export async function POST(request: Request) {
2930
);
3031
}
3132

32-
if (!message) {
33+
const trimmedMessage = (message ?? "").trim();
34+
const trimmedHtml = (html ?? "").trim();
35+
36+
if (!trimmedMessage && !trimmedHtml) {
3337
return NextResponse.json(
3438
{ error: "Message body cannot be empty." },
3539
{ status: 400 }
@@ -41,7 +45,10 @@ export async function POST(request: Request) {
4145
to,
4246
cc,
4347
subject: subject ?? "(no subject)",
44-
message,
48+
message:
49+
trimmedMessage ||
50+
trimmedHtml.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim(),
51+
html: trimmedHtml || undefined,
4552
});
4653

4754
if (result.error) {

app/emails.tsx

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ type SendEmailArgs = {
1616
message: string;
1717
cc?: string;
1818
from?: string;
19+
html?: string;
1920
};
2021

2122
const normalizeList = (value?: string) =>
@@ -30,6 +31,7 @@ export async function sendEmail({
3031
message,
3132
cc,
3233
from,
34+
html,
3335
}: SendEmailArgs) {
3436
const toList = normalizeList(to);
3537
if (!toList?.length) {
@@ -38,18 +40,21 @@ export async function sendEmail({
3840

3941
const ccList = normalizeList(cc);
4042

41-
const html = message
42-
.split("\n")
43-
.map((line) => line.trim())
44-
.map((line) => (line.length ? `<p>${line}</p>` : "<br/>"))
45-
.join("");
43+
const normalizedHtml =
44+
html && html.trim().length
45+
? html
46+
: message
47+
.split("\n")
48+
.map((line) => line.trim())
49+
.map((line) => (line.length ? `<p>${line}</p>` : "<br/>"))
50+
.join("");
4651

4752
return resend.emails.send({
4853
from: from ?? resendFromAddress,
4954
to: toList,
5055
cc: ccList,
5156
subject,
5257
text: message,
53-
html,
58+
html: normalizedHtml,
5459
});
5560
}

0 commit comments

Comments
 (0)