发邮件
使用 Resend API 从 Edge Functions 发送电子邮件。
🌐 Sending emails from Edge Functions using the Resend API.
先决条件 #
🌐 Prerequisites
要充分利用本指南,你需要:
🌐 To get the most out of this guide, you’ll need to:
确保你已经安装了最新版本的 Supabase CLI。
🌐 Make sure you have the latest version of the Supabase CLI installed.
1. 创建 Supabase 函数 #
🌐 1. Create Supabase function
在本地创建一个新函数:
🌐 Create a new function locally:
supabase functions new resend将 RESEND_API_KEY 存储到你的 .env 文件中。
🌐 Store the RESEND_API_KEY in your .env file.
2. 编辑处理函数 #
🌐 2. Edit the handler function
把以下代码粘贴到 index.ts 文件里:
🌐 Paste the following code into the index.ts file:
import { withSupabase } from 'npm:@supabase/server@^1'const RESEND_API_KEY = Deno.env.get('RESEND_API_KEY')const handler = async (_request: Request): Promise<Response> => { const res = await fetch('https://api.resend.com/emails', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${RESEND_API_KEY}`, }, body: JSON.stringify({ from: 'onboarding@resend.dev', to: 'delivered@resend.dev', subject: 'hello world', html: '<strong>it works!</strong>', }), }) const data = await res.json() return Response.json(data)}export default { fetch: withSupabase({ auth: ['user', 'secret'] }, handler) }3. 部署并发送邮件 #
🌐 3. Deploy and send email
在本地运行函数:
🌐 Run function locally:
supabase startsupabase functions serve --no-verify-jwt --env-file .env该函数接受已登录用户的 JWT 或一个密钥,因此可以通过你的应用(通过 supabase.functions.invoke)或从数据库函数触发。在本地使用密钥进行测试:
🌐 The function accepts a signed-in user's JWT or a secret key, so it can be triggered from your app (via supabase.functions.invoke) or from a database function. Test it locally with a secret key:
curl -i --request POST 'http://localhost:54321/functions/v1/resend' \ --header 'apikey: <SUPABASE_SECRET_KEY>'将函数部署到 Supabase:
🌐 Deploy function to Supabase:
supabase functions deploy resend --no-verify-jwt当你部署到 Supabase 时,确保你的 RESEND_API_KEY 已在 Edge Function Secrets Management 中设置
🌐 When you deploy to Supabase, make sure that your RESEND_API_KEY is set in Edge Function Secrets Management
4. 你自己试试 #
🌐 4. Try it yourself
在 GitHub 上查看完整示例。
🌐 Find the complete example on GitHub.