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



我正在使用Svelte和SendGrid创建一个联系人表单。这是一个基本的应用程序。速度:

<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>

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

有什么建议我缺少的吗?

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

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

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

文件:/src/routes/api/sendmail.ts或/src/api/ssendmail.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>

相关内容

最新更新