Website : rimsha.abasa.com
backdoor
Home
Console
Upload
information
Create File
Create Folder
About
Tools
:
/
exp-backend
/
src
/
services
/
Filename :
emailService.ts
back
Copy
import { SESClient, SendEmailCommand, SendEmailCommandInput } from "@aws-sdk/client-ses"; import { generateEmailTemplate, generateTextEmail } from "../utils/Templates/emailTemplate"; import dotenv from "dotenv"; dotenv.config(); // Updated interfaces to match your Prisma model interface EmailParams { to: string; // receiverEmail in your model subject: string; // subject in your model body: string; // body in your model from?: string; // sender's email name?: string; // Optional recipient name for personalization leadId?: string; // Optional lead ID for tracking } interface BulkEmailParams { recipients: { email: string; name?: string; subject: string; // personalized body: string; // personalized }[]; from?: string; } // AWS SES Client Setup const sesClient = new SESClient({ region: process.env.AWS_REGION as string, credentials: { accessKeyId: process.env.AWS_ACCESS_KEY_ID as string, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY as string, }, }); /** * Send a single email using the template * @param {EmailParams} params - Email parameters * @returns {Promise<{success: boolean, messageId?: string, error?: string}>} Result object */ export const sendEmail = async ({ to, subject, body, name = 'Customer', // Default name if not provided from = process.env.AWS_SES_EMAIL }: EmailParams) => { try { // Generate email content using the template const htmlBody = generateEmailTemplate(name, subject, body); const textBody = generateTextEmail(name, subject, body); const params: SendEmailCommandInput = { Destination: { ToAddresses: [to], }, Message: { Body: { Html: { Data: htmlBody }, Text: { Data: textBody }, }, Subject: { Data: subject }, }, Source: from, }; const command = new SendEmailCommand(params); const response = await sesClient.send(command); console.log("Email Sent Successfully:", response.MessageId); return { success: true, messageId: response.MessageId, emailData: { to, subject, body, from } }; } catch (error) { console.error("Email Send Error:", error); return { success: false, error: (error as Error).message, emailData: { to, subject, body, from } }; } }; /** * Send bulk emails by sending individual emails in parallel * @param {BulkEmailParams} params - Bulk email parameters * @param {number} batchSize - Number of emails to send in parallel (default: 10) * @returns {Promise<{success: boolean, results: any[]}>} Result object */ export const sendBulkEmail = async ({ recipients, subject, body, from = process.env.AWS_SES_EMAIL }: BulkEmailParams, batchSize: number = 10): Promise<{success: boolean, results: any[]}> => { const results = []; const BATCH_DELAY_MS = 1100; // AWS SES rate limit handle karne ke liye // Process recipients in batches to avoid overwhelming the system for (let i = 0; i < recipients.length; i += batchSize) { const batch = recipients.slice(i, i + batchSize); const batchPromises = batch.map(recipient => sendEmail({ to: recipient.email, subject: recipient.subject, // ✅ use personalized body: recipient.body, // ✅ use personalized name: recipient.name || 'User', from }).then(result => ({ ...result, email: recipient.email })) .catch(error => ({ success: false, email: recipient.email, error: (error as Error).message })) ); const batchResults = await Promise.all(batchPromises); results.push(...batchResults); // Add delay only if more batches remain if (i + batchSize < recipients.length) { await new Promise(resolve => setTimeout(resolve, BATCH_DELAY_MS)); } } return { success: !results.some(r => !r.success), // true only if all succeeded results }; }; // import AWS from 'aws-sdk'; // // Configure AWS SDK // AWS.config.update({ // region: 'your-region', // accessKeyId: 'your-access-key-id', // secretAccessKey: 'your-secret-access-key', // }); // const ses = new AWS.SES(); // export const sendPasswordResetEmail = async (email: string, token: string, firstName: string) => { // const params = { // Source: 'your-verified-email@example.com', // Destination: { // ToAddresses: [email], // }, // Message: { // Subject: { // Data: 'Password Reset Request', // Charset: 'UTF-8', // }, // Body: { // Html: { // Data: ` // <p>Hello ${firstName},</p> // <p>We received a request to reset your password. Please click the link below to reset it:</p> // <a href="https://your-domain.com/reset-password?token=${token}">Reset Password</a> // <p>If you didn't request this, please ignore this email.</p> // <p>Thank you!</p> // `, // Charset: 'UTF-8', // }, // }, // }, // }; // try { // await ses.sendEmail(params).promise(); // } catch (error) { // console.error('Error sending email:', error); // throw new Error('Could not send password reset email.'); // } // };