-
Notifications
You must be signed in to change notification settings - Fork 0
Feature/email service #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
plumburite
wants to merge
2
commits into
main
Choose a base branch
from
feature/email-service
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| export async function sendAuthCode(payload: { | ||
| email?: string; | ||
| phoneNumber?: string; | ||
| firstName?: string; | ||
| lastName?: string; | ||
| }) { | ||
| const res = await fetch("/api/auth/send-code", { | ||
| method: "POST", | ||
| headers: { "Content-Type": "application/json" }, | ||
| body: JSON.stringify(payload), | ||
| }); | ||
| if (!res.ok) { | ||
| const err = await res.json().catch(() => ({ message: "Failed to send code" })); | ||
| throw new Error(err.message || "Failed to send code"); | ||
| } | ||
| return res.json(); | ||
| } | ||
|
|
||
| export async function verifyAuthCode(payload: { | ||
| email?: string; | ||
| phoneNumber?: string; | ||
| code: string; | ||
| }) { | ||
| const res = await fetch("/api/auth/verify-code", { | ||
| method: "POST", | ||
| headers: { "Content-Type": "application/json" }, | ||
| body: JSON.stringify(payload), | ||
| }); | ||
| if (!res.ok) { | ||
| const err = await res.json().catch(() => ({ message: "Failed to verify code" })); | ||
| throw new Error(err.message || "Failed to verify code"); | ||
| } | ||
| return res.json(); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,120 +1,127 @@ | ||
| // SendGrid email service integration | ||
| import sgMail from '@sendgrid/mail'; | ||
| import nodemailer from "nodemailer"; | ||
|
|
||
| class EmailService { | ||
| private initialized = false; | ||
| type SendResult = { success: boolean; info?: any }; | ||
|
|
||
| constructor() { | ||
| this.initialize(); | ||
| } | ||
| const SMTP_HOST = process.env.SMTP_HOST; | ||
| const SMTP_PORT = process.env.SMTP_PORT ? parseInt(process.env.SMTP_PORT, 10) : undefined; | ||
| const SMTP_USER = process.env.SMTP_USER; | ||
| const SMTP_PASS = process.env.SMTP_PASS; | ||
| const SMTP_SECURE = process.env.SMTP_SECURE === "true"; | ||
|
|
||
| private initialize() { | ||
| try { | ||
| const apiKey = process.env.SENDGRID_API_KEY; | ||
|
|
||
| if (!apiKey) { | ||
| console.log('SendGrid API key not found - email verification disabled'); | ||
| console.log('Set SENDGRID_API_KEY environment variable to enable email verification'); | ||
| return; | ||
| } | ||
| let transporter: nodemailer.Transporter | null = null; | ||
|
|
||
| if (!apiKey.startsWith('SG.')) { | ||
| console.warn('Warning: SendGrid API key format appears invalid (should start with "SG.")'); | ||
| } | ||
| if (SMTP_HOST && SMTP_PORT && SMTP_USER && SMTP_PASS) { | ||
| transporter = nodemailer.createTransport({ | ||
| host: SMTP_HOST, | ||
| port: SMTP_PORT, | ||
| secure: SMTP_SECURE || SMTP_PORT === 465, | ||
| auth: { | ||
| user: SMTP_USER, | ||
| pass: SMTP_PASS, | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| sgMail.setApiKey(apiKey); | ||
| this.initialized = true; | ||
| console.log('✓ SendGrid email service initialized successfully'); | ||
| } catch (error) { | ||
| console.error('Failed to initialize SendGrid:', error); | ||
| } | ||
| } | ||
| function verificationEmailHtml(code: string, firstName?: string) { | ||
| const name = firstName ? `Hi ${firstName},` : "Hello,"; | ||
| return ` | ||
| <div style="font-family: Arial, sans-serif; color: #111;"> | ||
| <p>${name}</p> | ||
| <p>Your verification code for Instant Plumber Connect is:</p> | ||
| <h2 style="letter-spacing: 4px;">${code}</h2> | ||
| <p>This code expires in 10 minutes. If you did not request this, please ignore this email.</p> | ||
| <hr /> | ||
| <p style="font-size: 12px; color: #666;">If you have trouble signing in, contact support.</p> | ||
| </div> | ||
| `; | ||
| } | ||
|
|
||
| isReady(): boolean { | ||
| return this.initialized; | ||
| } | ||
| function welcomeEmailHtml(firstName?: string) { | ||
| const name = firstName ? `Hi ${firstName},` : "Welcome,"; | ||
| return ` | ||
| <div style="font-family: Arial, sans-serif; color: #111;"> | ||
| <p>${name}</p> | ||
| <p>Welcome to Instant Plumber Connect — glad to have you on board.</p> | ||
| <p>Start by updating your profile and verifying your contact details.</p> | ||
| <hr /> | ||
| <p style="font-size: 12px; color: #666;">Thank you,<br/>The Instant Plumber Connect Team</p> | ||
| </div> | ||
| `; | ||
| } | ||
|
|
||
| async sendVerificationEmail(email: string, code: string, firstName?: string): Promise<boolean> { | ||
| if (!this.initialized) { | ||
| console.log('Email service not initialized - cannot send verification email'); | ||
| return false; | ||
| } | ||
| export const emailService = { | ||
| isReady() { | ||
| return transporter !== null || process.env.NODE_ENV === "development"; | ||
| }, | ||
|
|
||
| async sendVerificationEmail(to: string, code: string, firstName?: string): Promise<boolean> { | ||
| try { | ||
| const msg = { | ||
| to: email, | ||
| from: 'noreply@instantplumberconnect.com', // Replace with your verified sender | ||
| subject: 'Your Instant Plumber Connect Verification Code', | ||
| text: `Your verification code is: ${code}`, | ||
| html: ` | ||
| <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;"> | ||
| <h2 style="color: #2563eb;">Instant Plumber Connect</h2> | ||
| <p>Hello ${firstName || 'there'},</p> | ||
| <p>Your verification code is:</p> | ||
| <div style="background-color: #f3f4f6; padding: 20px; text-align: center; margin: 20px 0;"> | ||
| <h1 style="color: #1f2937; font-size: 32px; margin: 0; letter-spacing: 4px;">${code}</h1> | ||
| </div> | ||
| <p>This code will expire in 10 minutes.</p> | ||
| <p>If you didn't request this verification, please ignore this email.</p> | ||
| <hr style="margin: 30px 0; border: none; border-top: 1px solid #e5e7eb;"> | ||
| <p style="color: #6b7280; font-size: 14px;"> | ||
| Instant Plumber Connect - Professional plumbing services made simple | ||
| </p> | ||
| </div> | ||
| `, | ||
| }; | ||
|
|
||
| await sgMail.send(msg); | ||
| console.log(`Verification email sent successfully to ${email}`); | ||
| return true; | ||
| } catch (error: any) { | ||
| console.error('SendGrid email error:', error); | ||
|
|
||
| // Handle specific SendGrid errors | ||
| if (error.response) { | ||
| console.error('SendGrid response error:', { | ||
| status: error.response.status, | ||
| body: error.response.body | ||
| const subject = "Your Instant Plumber Connect verification code"; | ||
| const html = verificationEmailHtml(code, firstName); | ||
| if (transporter) { | ||
| const info = await transporter.sendMail({ | ||
| from: process.env.EMAIL_FROM || `"Instant Plumber Connect" <no-reply@plumberconnect.local>`, | ||
| to, | ||
| subject, | ||
| html, | ||
| text: `Your verification code is ${code}`, | ||
| }); | ||
| console.log("Verification email sent:", info.messageId); | ||
| return true; | ||
| } else { | ||
| // Development fallback: log code so you can test without SMTP configured | ||
| console.log(`[DEV EMAIL] To: ${to} Subject: ${subject} Code: ${code}`); | ||
| return true; | ||
| } | ||
|
|
||
| } catch (err) { | ||
| console.error("Error sending verification email:", err); | ||
| return false; | ||
| } | ||
| } | ||
| }, | ||
|
|
||
| async sendWelcomeEmail(email: string, firstName: string): Promise<boolean> { | ||
| if (!this.initialized) { | ||
| async sendWelcomeEmail(to: string, firstName?: string): Promise<boolean> { | ||
| try { | ||
| const subject = "Welcome to Instant Plumber Connect"; | ||
| const html = welcomeEmailHtml(firstName); | ||
| if (transporter) { | ||
| const info = await transporter.sendMail({ | ||
| from: process.env.EMAIL_FROM || `"Instant Plumber Connect" <no-reply@plumberconnect.local>`, | ||
| to, | ||
| subject, | ||
| html, | ||
| text: `Welcome to Instant Plumber Connect.`, | ||
| }); | ||
| console.log("Welcome email sent:", info.messageId); | ||
| return true; | ||
| } else { | ||
| console.log(`[DEV EMAIL] To: ${to} Subject: ${subject}`); | ||
| return true; | ||
| } | ||
| } catch (err) { | ||
| console.error("Error sending welcome email:", err); | ||
| return false; | ||
| } | ||
| }, | ||
|
|
||
| async sendGenericEmail(to: string, subject: string, html: string): Promise<SendResult> { | ||
| try { | ||
| const msg = { | ||
| to: email, | ||
| from: 'noreply@instantplumberconnect.com', | ||
| subject: 'Welcome to Instant Plumber Connect!', | ||
| html: ` | ||
| <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;"> | ||
| <h2 style="color: #2563eb;">Welcome to Instant Plumber Connect!</h2> | ||
| <p>Hello ${firstName},</p> | ||
| <p>Your plumber account has been successfully created. You can now:</p> | ||
| <ul> | ||
| <li>Receive instant video call requests from customers</li> | ||
| <li>Manage your availability status</li> | ||
| <li>Track your earnings and call history</li> | ||
| </ul> | ||
| <p>Start receiving calls by setting yourself as available in your dashboard!</p> | ||
| </div> | ||
| `, | ||
| }; | ||
|
|
||
| await sgMail.send(msg); | ||
| console.log(`Welcome email sent to ${email}`); | ||
| return true; | ||
| } catch (error) { | ||
| console.error('Error sending welcome email:', error); | ||
| return false; | ||
| if (transporter) { | ||
| const info = await transporter.sendMail({ | ||
| from: process.env.EMAIL_FROM || `"Instant Plumber Connect" <no-reply@plumberconnect.local>`, | ||
| to, | ||
| subject, | ||
| html, | ||
| }); | ||
| return { success: true, info }; | ||
| } else { | ||
| console.log(`[DEV EMAIL] To: ${to} Subject: ${subject} HTML: ${html}`); | ||
| return { success: true, info: "dev-fallback" }; | ||
| } | ||
| } catch (err) { | ||
| console.error("Error sending email:", err); | ||
| return { success: false, info: err }; | ||
| } | ||
| } | ||
| } | ||
| }, | ||
| }; | ||
|
|
||
| export const emailService = new EmailService(); | ||
| export default emailService; | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The new email service now imports
nodemailerbutpackage.jsonstill only declares the SendGrid SDK. After this commit a clean install will not includenodemailer, so starting the server will throwCannot find module 'nodemailer'as soon asemail-service.tsis loaded. The dependency needs to be added to the project’s package.json (and the unused SendGrid dependency removed) so the runtime can resolve the module.Useful? React with 👍 / 👎.