Skip to content
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

feat : Added support for different email service provider. #746

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions apps/ecosystem/src/ecosystem.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { ClientProxy, RpcException } from '@nestjs/microservices';
import { PrismaService } from '@credebl/prisma-service';
import { EcosystemInviteTemplate } from '../templates/EcosystemInviteTemplate';
import { EmailDto } from '@credebl/common/dtos/email.dto';
import { sendEmail } from '@credebl/common/send-grid-helper-file';
import { EmailService } from '@credebl/common/email.service';
import { AcceptRejectEcosystemInvitationDto } from '../dtos/accept-reject-ecosysteminvitation.dto';
import { EcosystemConfigSettings, Invitation, OrgAgentType, schemaRequestType, SchemaType } from '@credebl/enum/enum';
import {
Expand Down Expand Up @@ -83,7 +83,8 @@ export class EcosystemService {
private readonly ecosystemRepository: EcosystemRepository,
private readonly logger: Logger,
private readonly prisma: PrismaService,
@Inject(CACHE_MANAGER) private cacheService: Cache
@Inject(CACHE_MANAGER) private cacheService: Cache,
private readonly emailService : EmailService
) {}

/**
Expand Down Expand Up @@ -738,7 +739,7 @@ export class EcosystemService {
);

//Email is sent to user for the verification through emailData
const isEmailSent = await sendEmail(emailData);
const isEmailSent = await this.emailService.sendEmail(emailData);

return isEmailSent;
}
Expand Down
7 changes: 4 additions & 3 deletions apps/issuance/src/issuance.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import { IIssuedCredential, IJsonldCredential } from '@credebl/common/interfaces
import { OOBIssueCredentialDto } from 'apps/api-gateway/src/issuance/dtos/issuance.dto';
import { agent_invitations, organisation } from '@prisma/client';
import { createOobJsonldIssuancePayload, validateEmail } from '@credebl/common/cast.helper';
import { sendEmail } from '@credebl/common/send-grid-helper-file';
import { EmailService } from '@credebl/common/email.service';


@Injectable()
Expand All @@ -46,7 +46,8 @@ export class IssuanceService {
private readonly emailData: EmailDto,
private readonly awsService: AwsService,
@InjectQueue('bulk-issuance') private bulkIssuanceQueue: Queue,
@Inject(CACHE_MANAGER) private cacheService: Cache
@Inject(CACHE_MANAGER) private cacheService: Cache,
private readonly emailService : EmailService
) { }

async sendCredentialCreateOffer(payload: IIssuance): Promise<PromiseSettledResult<ICreateOfferResponse>[]> {
Expand Down Expand Up @@ -693,7 +694,7 @@ async sendEmailForCredentialOffer(sendEmailCredentialOffer: SendEmailCredentialO
disposition: 'attachment'
}
];
const isEmailSent = await sendEmail(this.emailData);
const isEmailSent = await this.emailService.sendEmail(this.emailData);
this.logger.log(`isEmailSent ::: ${JSON.stringify(isEmailSent)}`);
if (!isEmailSent) {
errors.push(new InternalServerErrorException(ResponseMessages.issuance.error.emailSend));
Expand Down
7 changes: 4 additions & 3 deletions apps/organization/src/organization.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { UserOrgRolesService } from '@credebl/user-org-roles';
import { ResponseMessages } from '@credebl/common/response-messages';
import { OrganizationInviteTemplate } from '../templates/organization-invitation.template';
import { EmailDto } from '@credebl/common/dtos/email.dto';
import { sendEmail } from '@credebl/common/send-grid-helper-file';
import { EmailService } from '@credebl/common/email.service';
import { CreateOrganizationDto } from '../dtos/create-organization.dto';
import { BulkSendInvitationDto } from '../dtos/send-invitation.dto';
import { UpdateInvitationDto } from '../dtos/update-invitation.dt';
Expand Down Expand Up @@ -58,7 +58,8 @@ export class OrganizationService {
private readonly userActivityService: UserActivityService,
private readonly logger: Logger,
@Inject(CACHE_MANAGER) private cacheService: Cache,
private readonly clientRegistrationService: ClientRegistrationService
private readonly clientRegistrationService: ClientRegistrationService,
private readonly emailService : EmailService
) {}

/**
Expand Down Expand Up @@ -915,7 +916,7 @@ export class OrganizationService {
);

//Email is sent to user for the verification through emailData
const isEmailSent = await sendEmail(emailData);
const isEmailSent = await this.emailService.sendEmail(emailData);

return isEmailSent;
}
Expand Down
9 changes: 5 additions & 4 deletions apps/user/src/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { URLUserEmailTemplate } from '../templates/user-email-template';
import { UserOrgRolesService } from '@credebl/user-org-roles';
import { UserRepository } from '../repositories/user.repository';
import { VerifyEmailTokenDto } from '../dtos/verify-email.dto';
import { sendEmail } from '@credebl/common/send-grid-helper-file';
import { EmailService } from '@credebl/common/email.service';
import { user } from '@prisma/client';
import {
Attribute,
Expand Down Expand Up @@ -75,7 +75,8 @@ export class UserService {
private readonly awsService: AwsService,
private readonly userDevicesRepository: UserDevicesRepository,
private readonly logger: Logger,
@Inject('NATS_CLIENT') private readonly userServiceProxy: ClientProxy
@Inject('NATS_CLIENT') private readonly userServiceProxy: ClientProxy,
private readonly emailService : EmailService
) {}

/**
Expand Down Expand Up @@ -164,7 +165,7 @@ export class UserService {
emailData.emailSubject = `[${process.env.PLATFORM_NAME}] Verify your email to activate your account`;

emailData.emailHtml = await urlEmailTemplate.getUserURLTemplate(email, verificationCode);
const isEmailSent = await sendEmail(emailData);
const isEmailSent = await this.emailService.sendEmail(emailData);
if (isEmailSent) {
return isEmailSent;
} else {
Expand Down Expand Up @@ -461,7 +462,7 @@ export class UserService {
emailData.emailSubject = `[${process.env.PLATFORM_NAME}] Important: Password Reset Request`;

emailData.emailHtml = await urlEmailTemplate.getUserResetPasswordTemplate(email, verificationCode);
const isEmailSent = await sendEmail(emailData);
const isEmailSent = await this.emailService.sendEmail(emailData);
if (isEmailSent) {
return isEmailSent;
} else {
Expand Down
7 changes: 4 additions & 3 deletions apps/verification/src/verification.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { ResponseMessages } from '@credebl/common/response-messages';
import * as QRCode from 'qrcode';
import { OutOfBandVerification } from '../templates/out-of-band-verification.template';
import { EmailDto } from '@credebl/common/dtos/email.dto';
import { sendEmail } from '@credebl/common/send-grid-helper-file';
import { EmailService } from '@credebl/common/email.service';
import { Cache } from 'cache-manager';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { IUserRequest } from '@credebl/user-request/user-request.interface';
Expand All @@ -28,7 +28,8 @@ export class VerificationService {
private readonly verificationRepository: VerificationRepository,
private readonly outOfBandVerification: OutOfBandVerification,
private readonly emailData: EmailDto,
@Inject(CACHE_MANAGER) private cacheService: Cache
@Inject(CACHE_MANAGER) private cacheService: Cache,
private readonly emailService : EmailService

) { }

Expand Down Expand Up @@ -499,7 +500,7 @@ export class VerificationService {
disposition: 'attachment'
}
];
const isEmailSent = await sendEmail(this.emailData);
const isEmailSent = await this.emailService.sendEmail(this.emailData);

if (!isEmailSent) {
throw new Error(ResponseMessages.verification.error.emailSend);
Expand Down
37 changes: 37 additions & 0 deletions libs/common/src/aws-ses-helper-file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import * as dotenv from 'dotenv';
import { EmailDto } from './dtos/email.dto';
import { Logger } from '@nestjs/common';
import * as nodemailer from 'nodemailer';
import * as AWS from 'aws-sdk';

dotenv.config();

export const sendWithSES = async (emailDto: EmailDto): Promise<boolean> => {
const awsSES = new AWS.SES({
apiVersion: '2010-12-01',
ganeshawle25 marked this conversation as resolved.
Show resolved Hide resolved
region: process.env.AWS_SES_REGION,
credentials: {
accessKeyId: process.env.AWS_SES_ACCESS_KEY,
secretAccessKey: process.env.AWS_SES_SECRET_KEY
}
});
const transporter = nodemailer.createTransport({
SES: awsSES
});
try {
return await transporter
.sendMail({
from: emailDto.emailFrom,
to: emailDto.emailTo, //list of receivers
ganeshawle25 marked this conversation as resolved.
Show resolved Hide resolved
subject: emailDto.emailSubject,
text: emailDto.emailText,
html: emailDto.emailHtml,
attachments: emailDto.emailAttachments
})
.then(() => true)
.catch(() => false);
} catch (error) {
Logger.error('Error while sending email with Amazon SES', error);
return false;
}
};
5 changes: 3 additions & 2 deletions libs/common/src/common.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import { HttpModule } from '@nestjs/axios';
import { Module } from '@nestjs/common';

import { CommonService } from './common.service';
import { EmailService } from './email.service';

@Module({
imports: [HttpModule],
providers: [CommonService],
exports: [CommonService]
providers: [CommonService, EmailService],
exports: [CommonService, EmailService]
})
export class CommonModule {}
40 changes: 40 additions & 0 deletions libs/common/src/email.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { Injectable, Logger } from '@nestjs/common';
import { EmailDto } from './dtos/email.dto';
import { sendWithSendGrid } from '@credebl/common/send-grid-helper-file';
import { sendWithSES } from '@credebl/common/aws-ses-helper-file';
import { sendWithSMTP } from '@credebl/common/smtp-helper-file';

@Injectable()
export class EmailService {
private readonly logger = new Logger(EmailService.name);

constructor() {}
async sendEmail(emailDto: EmailDto): Promise<boolean> {
const provider = process.env.EMAIL_PROVIDER;
let result: boolean;
if (!provider) {
throw new Error('Email provider is not set in environment variables. Please provide email service provider property.');
}
try {
this.logger.debug(`Email Provider is ::::::::${provider}`);
ganeshawle25 marked this conversation as resolved.
Show resolved Hide resolved
switch (provider) {
case 'ses':
result = await sendWithSES(emailDto);
break;
case 'sendGrid':
result = await sendWithSendGrid(emailDto);
break;
case 'smtp':
result = await sendWithSMTP(emailDto);
break;
default:
this.logger.warn(`Unknown email provider: ${provider}. Defaulting to SendGrid.`);
result = await sendWithSendGrid(emailDto);
break;
}
} catch (error) {
throw new Error(`Failed to send email using ${provider} provider: ${error.message}`);
}
return result;
}
}
33 changes: 16 additions & 17 deletions libs/common/src/send-grid-helper-file.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,26 @@
import * as sendgrid from '@sendgrid/mail';
import * as dotenv from 'dotenv';
import { EmailDto } from './dtos/email.dto';
import { Logger } from '@nestjs/common';

dotenv.config();

sendgrid.setApiKey(
process.env.SENDGRID_API_KEY
);

export const sendEmail = async (EmailDto: EmailDto): Promise<boolean> => {
export const sendWithSendGrid = async (emailDto: EmailDto): Promise<boolean> => {
try {
const msg = {
to: EmailDto.emailTo,
from: EmailDto.emailFrom,
subject: EmailDto.emailSubject,
text: EmailDto.emailText,
html: EmailDto.emailHtml,
attachments: EmailDto.emailAttachments
};
return await sendgrid.send(msg).then(() => true).catch(() => false);

sendgrid.setApiKey(process.env.SENDGRID_API_KEY);
return await sendgrid
.send({
to: emailDto.emailTo,
from: emailDto.emailFrom,
subject: emailDto.emailSubject,
text: emailDto.emailText,
html: emailDto.emailHtml,
attachments: emailDto.emailAttachments
})
.then(() => true)
.catch(() => false);
} catch (error) {
Logger.error('Error while sending email with SendGrid', error);
return false;
}

};
};
32 changes: 32 additions & 0 deletions libs/common/src/smtp-helper-file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import * as dotenv from 'dotenv';
import { EmailDto } from './dtos/email.dto';
import { Logger } from '@nestjs/common';
import * as nodemailer from 'nodemailer';

dotenv.config();

export const sendWithSMTP = async (emailDto: EmailDto): Promise<boolean> => {
const { SMTP_HOST: host, SMTP_PORT: port, SMTP_USER: user, SMTP_PASS: pass } = process.env;
const transporter = nodemailer.createTransport({
host,
port: parseInt(port, 10),
auth: { user, pass }
});

try {
return await transporter
.sendMail({
from: emailDto.emailFrom,
to: emailDto.emailTo,
subject: emailDto.emailSubject,
text: emailDto.emailText,
html: emailDto.emailHtml,
attachments: emailDto.emailAttachments
})
.then(() => true)
.catch(() => false);
} catch (error) {
Logger.error('Error while sending email with SMTP', error);
return false;
}
};
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@
"nestjs-typeorm-paginate": "^4.0.4",
"node-html-to-image": "^4.0.0",
"node-qpdf2": "^2.0.0",
"nodemailer": "^6.9.13",
"papaparse": "^5.4.1",
"passport": "^0.6.0",
"passport-jwt": "^4.0.1",
Expand Down
Loading