提交表单后通过 SendGrid 发送电子邮件

Sending email via SendGrid after form submission

我正在使用 Svelte 和 SendGrid 制作一个联系表。这是一个基本的 app.svelte:

<script>
    import sgMail from '@sendgrid/mail';
    sgMail.setApiKey(import.meta.env.VITE_SENDGRID);

    function submitForm() {
        const msg = {
            to: 'test@example.com',
            from: 'test@example.com',
            subject: 'Sending with SendGrid is Fun',
            text: 'and easy to do anywhere, even with Node.js',
            html: '<strong>and easy to do anywhere, even with Node.js</strong>'
        };
        console.log('Form submitted');
        sgMail.send(msg);
    }
</script>

<form on:submit|preventDefault={submitForm}>
    <button type="submit">Submit</button>
</form>

上面的代码在用户在表单上选择 submit 后不会发送电子邮件,尽管调用了该函数(它在控制台中记录 Form submitted)。当我将 submitForm() 中的所有代码移到函数外部时,代码会在页面加载时执行,所以我知道这不是我的 API 键的问题。

有什么我遗漏的建议吗?

Svelte 只是一个前端环境。 Sendgrid 包是为服务器端/node.js 环境设计的。在您的示例中,您的 Sendgrid API 密钥将被公开,因为您正试图在前端/客户端使用它。

一个解决方案可能是查看 SvelteKit,它具有 'endpoints' 的概念,在服务器端始终 运行。或者您可以创建一个快速服务器来处理向 Sendgrid 发送电子邮件。

编辑:解决方案是使用 Sveltekit 端点。服务器上的终结点始终 运行。您的最终解决方案可能如下所示:

文件:/src/routes/api/sendmail.ts 或 /src/api/sendmail.js

import sgMail from "@sendgrid/mail";
sgMail.setApiKey(import.meta.env.VITE_SENDGRID);

export async function get(page) {
      const msg = {
        to: "test@example.com",
        from: "test@example.com",
        subject: "Sending with SendGrid is Fun",
        text: "and easy to do anywhere, even with Node.js",
        html: "<strong>and easy to do anywhere, even with Node.js</strong>",
      };
      console.log("Form submitted");
      const output = await sgMail.send(msg);
  return {
    body: output,
  };
}

文件/src/routes/index.svelte

<script>
  function submitForm() {
    fetch("/api/sendmail");
  }
</script>

<form on:submit|preventDefault={submitForm}>
  <button type="submit">Submit</button>
</form>