zhemima/msmail
0
1import { authApiToken, authMiddleware } from "../../utils/auth.js";2import { addCorsHeaders } from "../../utils/cors.js";3import { get_access_token, sendEmail } from "../../utils/mail.js";4 5export const onRequest = async (context: RouteContext): Promise<Response> => {6 const request = context.request;7 const env: Env = context.env;8 9 // 验证权限10 const authResponse = await authMiddleware(request, env);11 const apiResponse = await authApiToken(request, env);12 if (authResponse && apiResponse) {13 return addCorsHeaders(authResponse);14 }15 16 const method = request.method;17 if (method !== 'POST') {18 return new Response(19 JSON.stringify({ error: 'Method not allowed' }),20 { status: 405 }21 );22 }23 24 try {25 const { email, to, subject, body, isHtml = false } = await request.json() as any;26 27 // 检查必要参数28 if (!email || !to || !subject || !body) {29 return new Response(30 JSON.stringify({31 error: 'Missing required parameters: email, to, subject, body'32 }),33 { status: 400 }34 );35 }36 37 // 从KV获取刷新令牌38 const tokenInfoStr = await env.KV.get(`refresh_token_${email}`);39 if (!tokenInfoStr) {40 throw new Error("No refresh token found for this email");41 }42 const tokenInfo = JSON.parse(tokenInfoStr);43 const access_token = await get_access_token(tokenInfo, env.ENTRA_CLIENT_ID, env.ENTRA_CLIENT_SECRET);44 45 // 发送邮件46 await sendEmail(access_token, Array.isArray(to) ? to : [to], subject, body, isHtml);47 48 return new Response(49 JSON.stringify({ message: 'Email sent successfully' }),50 {51 status: 200,52 headers: {53 'Content-Type': 'application/json',54 'Access-Control-Allow-Origin': '*'55 }56 }57 );58 } catch (error: any) {59 return new Response(60 JSON.stringify({ error: error.message }),61 {62 status: 500, headers: {63 'Content-Type': 'application/json',64 'Access-Control-Allow-Origin': '*'65 }66 }67 );68 }69};70 71 