我使用SendGrid,并且我知道我的SendGrid密钥是通过从终端进行检查来工作的。我用SendGrid发件人身份验证了我的电子邮件。
curl -i --request POST \
--url https://api.sendgrid.com/v3/mail/send \
--header 'Authorization: Bearer MY-API-KYE_HERE' \
--header 'Content-Type: application/json' \
--data '{"personalizations": [{"to": [{"email": "myname@gmail.com"}]}],"from": {"email": "connect@mywebsite.com"},"subject": "SendGrid Test!","content": [{"type": "text/plain", "value": "Howdy!"}]}'
HTTP/1.1 202 Accepted
Server: nginx
Date: Mon, 20 Dec 2021 04:42:08 GMT
Content-Length: 0
Connection: keep-alive
X-Message-Id: 9G5w8P8_SJWPwj1acrNRPQ
Access-Control-Allow-Origin: https://sendgrid.api-docs.io
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl
Access-Control-Max-Age: 600
X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html
Strict-Transport-Security: max-age=600; includeSubDomains
我收到一封电子邮件。
它也适用于本地主机。
但是当我用下面的代码部署到Vercel时,它不会发送任何电子邮件。
import sgMail from '@sendgrid/mail'
import dotenv from 'dotenv'
dotenv.config()
const host = process.env['HOST_URL']
const email_from = process.env['EMAIL_FROM']
const SENDGRID_API_KEY = process.env['SENDGRID_API']
export const sendGridConfirmationEmail = async (name, email, confirmationCode) => {
await sgMail.setApiKey(SENDGRID_API_KEY)
const msg = {
to: email,
from: `${email_from}`,
subject: "Please confirm your account",
text: `Email Confirmation: Hello ${name}.
Please confirm your email by clicking on the following link.
Click here, ${host}/auth/confirm/${confirmationCode}`,
html:`<h1>Email Confirmation</h1>
<h2>Hello ${name}</h2>
<p>Please confirm your email by clicking on the following link.</p>
<a href=${host}/auth/confirm/${confirmationCode}> Click here</a>
</div>`,
}
await sgMail
.send(msg)
.then(() => {
console.log('Email sent')
})
.catch((error) => {
console.error(error)
})
}
我也试过以下几种方法,但也不起作用。
export const sendGridConfirmationEmail = async (name, email, confirmationCode) => {
await fetch(SENDGRID_API, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${SENDGRID_API_KEY}`
},
body: JSON.stringify({
personalizations: [
{
to: [
{
email
}
],
subject: 'Demo success :)'
}
],
from: {
email: email_from,
name: 'Test SendGrid'
},
content: [
{
type: 'text/html',
value: `Congratulations <b>${name}</b>, you just sent an email with sendGrid. ${confirmationCode}`
}
]
})
});
}
如何使用SendGrid从Vercel发送电子邮件?
发布于 2021-12-21 04:36:22
我解决了问题。
当我调用sendGridConfirmationEmail
时,我需要使用await
。
export const post = async ({ body }) => {
...
if (mail_method === "sendgrid") {
await sendGridConfirmationEmail(
body.name,
body.email,
token
);
console.log('SendGrid registration is emailed.')
}
...
https://stackoverflow.com/questions/70417562
复制相似问题