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

R B*_*nes 2 sendgrid svelte sveltekit

我正在使用 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>
Run Code Online (Sandbox Code Playgroud)

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

我缺少什么建议吗?

ale*_*alk 5

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

一个解决方案可能是查看 SvelteKit,它具有始终在服务器端运行的“端点”概念。或者您可以创建一个快速服务器来处理向 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,
  };
}
Run Code Online (Sandbox Code Playgroud)

文件/src/routes/index.svelte

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

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

Run Code Online (Sandbox Code Playgroud)