I'm using a simple contact <form>
to send emails to a given address, it works fine, now i need to add file attachments, i have an input
of type="file"
, and it can take in multiple files
How do i go from that to a string
/buffer
format like it says in the docs ?
https://resend.com/docs/api-reference/emails/send-email
Example :
await resend.emails.send({
from: 'Acme <[email protected]>',
to: ['[email protected]'],
subject: 'hello world',
text: 'it works!',
attachments: [
{
filename: 'invoice.pdf',
content: invoiceBuffer,
},
]
});
The format i use, either a string or a buffer, must be includable in the POST request's body, since what i do now is a JSON.stringify(data)
of my <form>
data and send it to the backend so it does the email sending.
I tried finding a solution with chat GPT, it suggests using FormData
, which is fine, but it never gets the format right, either it's broken when sent ( an empty array, instead of a file as string ), or it goes through but then i get the content must be in string or buffer format" error.
I'm really stuck, any help is appreciated 🙏🏼.
Found answer here : https://github.com/resend/resend-examples/blob/main/with-attachments-content/src/pages/index.tsx
the trick is to use this to read the file as a string :
const onAddFileAction = (e) => {
const reader = new FileReader();
const files = e.target.files;
reader.onload = (r) => {
setContent(r.target.result.toString());
setFilename(files[0].name);
};
reader.readAsDataURL(files[0]);
};
And then make the handler for your <input type="file" onChange={onAddFileAction}/>
And then use fetch to call the API :
await fetch('/api/send', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
content: base64Content,
filename,
}),
});