-
Notifications
You must be signed in to change notification settings - Fork 8
Feature/mailgun integration templates final #43
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
Merged
MrImmortal09
merged 5 commits into
iiitl:main
from
DistantMyth:feature/mailgun-integration-templates-final
Apr 11, 2026
Merged
Changes from 3 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
f444bf1
feat: implement Mailgun email service with database logging for sent …
DistantMyth d0f1b08
chore: add tsx dependency and implement MONGODB_URI validation in dat…
DistantMyth ec5cd85
docs: add comprehensive JSDoc comments to database models, connection…
DistantMyth 220b445
Applied the recommended changes
DistantMyth c35eeec
Applied more recommended changes
DistantMyth 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
Submodule .student-hub-ref
added at
3efe55
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
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,128 @@ | ||
| import FormData from 'form-data'; | ||
| import Mailgun from 'mailgun.js'; | ||
| import EmailLog from '../../models/EmailLog'; | ||
| import { connectDB } from '../db'; | ||
|
|
||
| /** | ||
| * Options required to send an email via Mailgun. | ||
| */ | ||
| interface EmailOptions { | ||
| /** The recipient's email address. */ | ||
| to: string; | ||
| /** The subject line of the email. */ | ||
| subject: string; | ||
| /** The plain text body of the email. */ | ||
| text: string; | ||
| /** The HTML encoded body of the email (optional, defaults to plain text if not provided). */ | ||
| html?: string; | ||
| } | ||
|
|
||
| /** | ||
| * Validates the presence of required Mailgun environment variables. | ||
| * | ||
| * @returns {boolean} True if all required environment variables are present, otherwise false. | ||
| */ | ||
| function validateMailgunEnvVars(): boolean { | ||
| const requiredVars = ['MAILGUN_API_KEY', 'MAILGUN_DOMAIN']; | ||
| const missingVars = requiredVars.filter((varName) => !process.env[varName]); | ||
|
|
||
| if (missingVars.length > 0) { | ||
| console.warn(`Missing Mailgun environment variables: ${missingVars.join(', ')}`); | ||
| return false; | ||
| } | ||
| return true; | ||
| } | ||
|
|
||
| let mailgunClient: ReturnType<Mailgun['client']> | null = null; | ||
|
|
||
| /** | ||
| * Initializes and returns a singleton instance of the Mailgun client. | ||
| * | ||
| * The client is configured using the `MAILGUN_API_KEY` and `MAILGUN_URL` | ||
| * environment variables. It caches the instance to avoid re-initialization on subsequent calls. | ||
| * | ||
| * @returns {ReturnType<Mailgun['client']> | null} The authenticated Mailgun client instance, or null if initialization fails. | ||
| */ | ||
| function getMailgunClient() { | ||
| if (!mailgunClient && validateMailgunEnvVars()) { | ||
| const mailgun = new Mailgun(FormData); | ||
| mailgunClient = mailgun.client({ | ||
| username: 'api', | ||
| key: process.env.MAILGUN_API_KEY || '', | ||
| url: process.env.MAILGUN_URL || 'https://api.mailgun.net', // allows EU domains | ||
| }); | ||
| } | ||
| return mailgunClient; | ||
| } | ||
|
|
||
| /** | ||
| * Sends an email using the Mailgun API and logs the attempt to the database. | ||
| * | ||
| * This function ensures the Mailgun client is properly configured and constructs | ||
| * the 'From' address using environment variables. It logs both successful sends | ||
| * and failed attempts to the `EmailLog` database collection. | ||
| * | ||
| * @param {EmailOptions} options - The configuration object for the email to be sent. | ||
| * @returns {Promise<boolean>} A promise that resolves to `true` if the email was successfully sent, or `false` if it failed. | ||
| */ | ||
| export async function sendEmail({ to, subject, text, html }: EmailOptions): Promise<boolean> { | ||
| const mg = getMailgunClient(); | ||
|
|
||
| if (!mg || !process.env.MAILGUN_DOMAIN) { | ||
| console.error('Mailgun client not initialized or domain missing'); | ||
| return false; | ||
| } | ||
|
|
||
| // Ensure from address is in proper format | ||
| const fromAddress = process.env.EMAIL_FROM || `no-reply@${process.env.MAILGUN_DOMAIN}`; | ||
|
|
||
| try { | ||
| const data = await mg.messages.create(process.env.MAILGUN_DOMAIN, { | ||
| from: fromAddress, | ||
| to: [to], | ||
| subject, | ||
| text, | ||
| html: html || text, | ||
| }); | ||
|
|
||
| console.log('Email sent successfully via Mailgun:', data.id); | ||
| await logEmail(to, subject, 'sent', data.id); | ||
| return true; | ||
| } catch (error: unknown) { | ||
| const err = error as { message?: string }; | ||
| console.error('Mailgun error details:', err?.message); | ||
| await logEmail(to, subject, 'failed', undefined, err?.message); | ||
| return false; | ||
|
coderabbitai[bot] marked this conversation as resolved.
coderabbitai[bot] marked this conversation as resolved.
Outdated
|
||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Logs an email delivery attempt to the MongoDB database. | ||
| * | ||
| * @param {string} to - The recipient's email address. | ||
| * @param {string} subject - The subject line of the email. | ||
| * @param {'sent' | 'failed'} status - The delivery outcome status. | ||
| * @param {string} [messageId] - The Mailgun message ID (applicable if successful). | ||
| * @param {string} [errorDetails] - The error message details (applicable if failed). | ||
| * @returns {Promise<void>} | ||
| */ | ||
| async function logEmail( | ||
| to: string, | ||
| subject: string, | ||
| status: 'sent' | 'failed', | ||
| messageId?: string, | ||
| errorDetails?: string | ||
| ) { | ||
| try { | ||
| await connectDB(); | ||
| await EmailLog.create({ | ||
| to, | ||
| subject, | ||
| status, | ||
| messageId, | ||
| errorDetails, | ||
| }); | ||
| } catch (dbError) { | ||
| console.error('Failed to log email to database:', dbError); | ||
| } | ||
| } | ||
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,51 @@ | ||
| import mongoose, { Schema, Document, Model } from 'mongoose'; | ||
|
|
||
| /** | ||
| * Represents a logged email delivery attempt in the database. | ||
| */ | ||
| export interface IEmailLog extends Document { | ||
| /** The recipient's email address. */ | ||
| to: string; | ||
| /** The subject line of the email. */ | ||
| subject: string; | ||
| /** The delivery status of the email. */ | ||
| status: 'sent' | 'failed'; | ||
| /** The unique message ID returned by Mailgun upon successful send (optional). */ | ||
| messageId?: string; | ||
| /** Detailed error message if the email attempt failed (optional). */ | ||
| errorDetails?: string; | ||
| /** Automatically generated timestamp of when the log was created. */ | ||
| createdAt: Date; | ||
| /** Automatically generated timestamp of when the log was last updated. */ | ||
| updatedAt: Date; | ||
| } | ||
|
|
||
| const EmailLogSchema: Schema<IEmailLog> = new Schema<IEmailLog>( | ||
| { | ||
| to: { | ||
| type: String, | ||
| required: [true, 'Recipient email is required'], | ||
| }, | ||
| subject: { | ||
| type: String, | ||
| required: [true, 'Email subject is required'], | ||
| }, | ||
| status: { | ||
| type: String, | ||
| enum: ['sent', 'failed'], | ||
| required: [true, 'Email status is required'], | ||
| }, | ||
| messageId: { | ||
| type: String, | ||
| }, | ||
| errorDetails: { | ||
| type: String, | ||
| }, | ||
| }, | ||
| { timestamps: true } | ||
| ); | ||
|
DistantMyth marked this conversation as resolved.
|
||
|
|
||
| const EmailLog: Model<IEmailLog> = | ||
| mongoose.models.EmailLog || mongoose.model<IEmailLog>('EmailLog', EmailLogSchema); | ||
|
|
||
| export default EmailLog; | ||
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
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.