|
| 1 | +import { Resend } from 'resend'; |
| 2 | +import { RESEND_API_KEY, RESEND_FROM_EMAIL } from '$env/static/private'; |
| 3 | + |
| 4 | +const resend = new Resend(RESEND_API_KEY); |
| 5 | + |
| 6 | +interface SendMagicLinkResult { |
| 7 | + success: boolean; |
| 8 | + error?: string; |
| 9 | +} |
| 10 | + |
| 11 | +export async function sendMagicLinkEmail( |
| 12 | + to: string, |
| 13 | + magicLinkUrl: string, |
| 14 | + type: 'staff' | 'student', |
| 15 | +): Promise<SendMagicLinkResult> { |
| 16 | + const subject = type === 'staff' |
| 17 | + ? 'Staff Login - Apprentice Pulse' |
| 18 | + : 'Student Login - Apprentice Pulse'; |
| 19 | + |
| 20 | + const html = ` |
| 21 | + <div style="font-family: sans-serif; max-width: 600px; margin: 0 auto;"> |
| 22 | + <h1 style="color: #333;">Apprentice Pulse</h1> |
| 23 | + <p>Click the button below to log in:</p> |
| 24 | + <a href="${magicLinkUrl}" style="display: inline-block; background: #0066cc; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; margin: 16px 0;"> |
| 25 | + Log in |
| 26 | + </a> |
| 27 | + <p style="color: #666; font-size: 14px;"> |
| 28 | + This link expires in 15 minutes.<br> |
| 29 | + If you didn't request this, you can safely ignore this email. |
| 30 | + </p> |
| 31 | + <p style="color: #999; font-size: 12px;"> |
| 32 | + Or copy this link: ${magicLinkUrl} |
| 33 | + </p> |
| 34 | + </div> |
| 35 | + `; |
| 36 | + |
| 37 | + const text = ` |
| 38 | +Apprentice Pulse |
| 39 | +
|
| 40 | +Click this link to log in: |
| 41 | +${magicLinkUrl} |
| 42 | +
|
| 43 | +This link expires in 15 minutes. |
| 44 | +If you didn't request this, you can safely ignore this email. |
| 45 | + `.trim(); |
| 46 | + |
| 47 | + try { |
| 48 | + const { error } = await resend.emails.send({ |
| 49 | + from: RESEND_FROM_EMAIL, |
| 50 | + to, |
| 51 | + subject, |
| 52 | + html, |
| 53 | + text, |
| 54 | + }); |
| 55 | + |
| 56 | + if (error) { |
| 57 | + console.error('Resend error:', error); |
| 58 | + return { success: false, error: error.message }; |
| 59 | + } |
| 60 | + |
| 61 | + return { success: true }; |
| 62 | + } |
| 63 | + catch (err) { |
| 64 | + console.error('Email send error:', err); |
| 65 | + return { success: false, error: 'Failed to send email' }; |
| 66 | + } |
| 67 | +} |
0 commit comments