Reputation: 11
I'm trying to create a contact form where the user enters their details and then attaches a file. For this I'm using Resend and followed one of their examples found here but I keep getting a POST http://localhost:3000/api/send 500 (Internal Server Error) when I try to send the email.
Here is my send.ts file code:
import type { NextApiRequest, NextApiResponse } from 'next';
import { Resend } from 'resend';
const resend = new Resend(process.env.RESEND_API_KEY);
const send = async (req: NextApiRequest, res: NextApiResponse) => {
const { method } = req;
const { content, filename } = req.body;
switch (method) {
case 'POST': {
const { data } = await resend.emails.send({
from: '[email protected]',
to: ['[email protected]'],
subject: 'Email with attachment',
html: '<p>See attachment</p>',
attachments: [
{
content,
filename,
},
],
});
return res.status(200).send({ data: data?.id });
}
default:
res.setHeader('Allow', ['POST']);
res.status(405).end(`Method ${method} Not Allowed`);
}
};
export default send;
And here is my ContactForm component code:
import * as React from 'react';
export const Index: React.FC = () => {
const [content, setContent] = React.useState<string | null>(null);
const [filename, setFilename] = React.useState('');
const onSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (content === null) {
alert('Please select a file to upload');
return;
}
const base64Content = content.split(',')[1];
try {
await fetch('/api/send', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
content: base64Content,
filename,
}),
});
alert('Request sent');
} catch (e) {
alert('Something went wrong');
}
};
const onAddFileAction = (e: React.ChangeEvent<HTMLInputElement>) => {
const reader = new FileReader();
const files = e.target.files;
if (files && files.length > 0) {
reader.onload = (r) => {
if (r.target?.result) {
setContent(r.target.result.toString());
setFilename(files[0].name);
}
};
reader.readAsDataURL(files[0]);
}
};
return (
<form
onSubmit={onSubmit}
style={{
display: 'flex',
flexDirection: 'column',
gap: '20px',
width: 200,
}}
>
<input
type="file"
name="file"
onChange={onAddFileAction}
accept="image/*"
/>
<input type="submit" value="Send Email" />
</form>
);
};
export default Index;
I'm wondering if this is a standard coding error or file organising.
Any help would be highly appreciated. Thanks in advance.
I've tried moving the files around to see if the error was with the api fetching, but it seems to fetch alright.
Upvotes: 1
Views: 325
Reputation: 116
I think it’s because you are using the email in the example “[email protected]” and you probably don’t own this domain. AFAIK you can only send emails from domains you own?
Try changing the “from” part to a domain you own and verified via the domains settings here: https://resend.com/domains
Upvotes: 0