使用重新发送以联系表单形式发送带有附件的电子邮件

问题描述 投票:0回答:1

我正在尝试创建一个联系表单,用户在其中输入详细信息,然后附加文件。为此,我使用 Resend 并遵循他们在here找到的示例之一,但当我尝试发送电子邮件时,我不断收到 POST http://localhost:3000/api/send 500(内部服务器错误)

这是我的 send.ts 文件代码:

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; 

这是我的 ContactForm 组件代码:

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;

我想知道这是否是标准编码错误或文件组织错误。

任何帮助将不胜感激。 预先感谢。

我尝试移动文件以查看错误是否与 api 获取有关,但似乎可以正常获取。

reactjs typescript next.js email-attachments resend.com
1个回答
0
投票

我认为这是因为您正在使用示例“[email protected]”中的电子邮件,并且您可能不拥有该域。据我所知,您只能从您拥有的域发送电子邮件?

尝试将“来自”部分更改为您拥有并通过此处的域设置进行验证的域:https://resend.com/domains

© www.soinside.com 2019 - 2024. All rights reserved.