gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:11:40 25 4
gpt4 key购买 nike

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

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

function submitForm() {
const msg = {
to: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3044554344705548515d405c551e535f5d" rel="noreferrer noopener nofollow">[email protected]</a>',
from: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bbcfdec8cffbdec3dad6cbd7de95d8d4d6" rel="noreferrer noopener nofollow">[email protected]</a>',
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 key 的问题。

我缺少什么建议吗?

最佳答案

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

解决方案可能是查看 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: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2155445255614459404c514d440f424e4c" rel="noreferrer noopener nofollow">[email protected]</a>",
from: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed99889e99ad88958c809d8188c38e8280" rel="noreferrer noopener nofollow">[email protected]</a>",
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>

关于sendgrid - 提交表单后通过 SendGrid 发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70647174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com