mirror of
https://github.com/OpenSignLabs/OpenSign.git
synced 2026-08-21 23:22:35 +02:00
v2.38.0
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import axios from 'axios';
|
||||
import { appName, cloudServerUrl, serverAppId } from '../../Utils.js';
|
||||
import { appName } from '../../Utils.js';
|
||||
import sendMailWithAttachment from './sendMailWithAttachment.js';
|
||||
|
||||
export default async function forwardDoc(request) {
|
||||
try {
|
||||
@@ -28,9 +28,9 @@ export default async function forwardDoc(request) {
|
||||
const docName = _docRes.Name;
|
||||
const extUserId = _docRes?.ExtUserPtr?.objectId;
|
||||
const TenantAppName = appName;
|
||||
const from = _docRes?.ExtUserPtr?.Email;
|
||||
const replyTo = _docRes?.ExtUserPtr?.Email;
|
||||
const senderName = _docRes?.ExtUserPtr?.Name;
|
||||
const from = _docRes?.SenderName || _docRes?.ExtUserPtr?.Email;
|
||||
const replyTo = _docRes?.SenderMail || _docRes?.ExtUserPtr?.Email;
|
||||
const senderName = _docRes?.SenderName || _docRes?.ExtUserPtr?.Name;
|
||||
|
||||
try {
|
||||
let mailRes;
|
||||
@@ -53,15 +53,10 @@ export default async function forwardDoc(request) {
|
||||
`<p style='padding:20px;font-family:system-ui;font-size:14px'>A copy of the document <strong>${docName}</strong> is attached to this email. Kindly download the document from the attachment.</p>` +
|
||||
`</div></div><div><p>This is an automated email from ${TenantAppName}. For any queries regarding this email, please contact the sender ${replyTo} directly.</p></div></div></body></html>`,
|
||||
};
|
||||
mailRes = await axios.post(`${cloudServerUrl}/functions/sendmailv3`, params, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Parse-Application-Id': serverAppId,
|
||||
'X-Parse-Master-Key': process.env.MASTER_KEY,
|
||||
},
|
||||
});
|
||||
mailRes = await sendMailWithAttachment(params);
|
||||
// console.log('mailRes', mailRes);
|
||||
}
|
||||
return mailRes.data?.result;
|
||||
return mailRes;
|
||||
} catch (error) {
|
||||
const msg =
|
||||
error?.response?.data?.error ||
|
||||
|
||||
@@ -110,8 +110,12 @@ async function sendMail(document, publicUrl) {
|
||||
year: 'numeric',
|
||||
});
|
||||
let signerMail = document.Placeholders?.filter(x => x?.Role !== 'prefill');
|
||||
const senderName = document.ExtUserPtr.Name;
|
||||
const senderEmail = document.ExtUserPtr.Email;
|
||||
const senderName = document?.SenderName || document.ExtUserPtr.Name;
|
||||
const senderEmail = document?.SenderMail || document.ExtUserPtr.Email;
|
||||
const from =
|
||||
document?.SenderName || document?.ExtUserPtr?.UseNameAsSender === true
|
||||
? document.ExtUserPtr.Name
|
||||
: senderEmail;
|
||||
|
||||
if (document.SendinOrder) {
|
||||
signerMail = signerMail.slice();
|
||||
@@ -171,7 +175,7 @@ async function sendMail(document, publicUrl) {
|
||||
extUserId: document.ExtUserPtr.objectId,
|
||||
recipient: existSigner?.Email || signerMail[i].email,
|
||||
subject: replaceVar?.subject ? replaceVar?.subject : mailTemplate(mailparam).subject,
|
||||
from: document.ExtUserPtr.Email,
|
||||
from: from,
|
||||
replyto: senderEmail || '',
|
||||
html: replaceVar?.body ? replaceVar?.body : mailTemplate(mailparam).body,
|
||||
};
|
||||
@@ -215,6 +219,7 @@ async function startBulkSendInBackground(userId, Documents, Ip, parseConfig, typ
|
||||
}
|
||||
let mailBody = x?.ExtUserPtr?.TenantId?.RequestBody || '';
|
||||
let mailSubject = x?.ExtUserPtr?.TenantId?.RequestSubject || '';
|
||||
let EmailEditorType = x?.ExtUserPtr?.TenantId?.EmailEditorType || '';
|
||||
return {
|
||||
method: 'POST',
|
||||
path: '/app/classes/contracts_Document',
|
||||
@@ -261,12 +266,16 @@ async function startBulkSendInBackground(userId, Documents, Ip, parseConfig, typ
|
||||
IsEnableOTP: x?.IsEnableOTP || false,
|
||||
IsTourEnabled: x?.IsTourEnabled || false,
|
||||
AllowModifications: x?.AllowModifications || false,
|
||||
...(x?.SenderName ? { SenderName: x?.SenderName } : {}),
|
||||
...(x?.SenderMail ? { SenderMail: x?.SenderMail } : {}),
|
||||
...(type === 'bulksend' ? { BulkSendToken: generateId(10) } : {}),
|
||||
...(x?.SignatureType ? { SignatureType: x?.SignatureType } : {}),
|
||||
...(x?.NotifyOnSignatures ? { NotifyOnSignatures: x?.NotifyOnSignatures } : {}),
|
||||
...(x?.Bcc?.length > 0 ? { Bcc: x?.Bcc } : {}),
|
||||
...(x?.RedirectUrl ? { RedirectUrl: x?.RedirectUrl } : {}),
|
||||
...(mailBody ? { RequestBody: mailBody } : {}),
|
||||
...(mailSubject ? { RequestSubject: mailSubject } : {}),
|
||||
...(EmailEditorType ? { EmailEditorType: EmailEditorType } : {}),
|
||||
...(x?.objectId
|
||||
? {
|
||||
TemplateId: {
|
||||
@@ -294,6 +303,7 @@ async function startBulkSendInBackground(userId, Documents, Ip, parseConfig, typ
|
||||
createdAt: response.data[0]?.success?.createdAt,
|
||||
};
|
||||
deductcount(response.data.length, resExt.id);
|
||||
console.log('here');
|
||||
sendMail(updateDocuments, publicUrl); //sessionToken
|
||||
return { total: 1, created: 1, failed: 0 };
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ export default async function getReport(request) {
|
||||
const limit = request.params.limit;
|
||||
const skip = request.params.skip;
|
||||
const searchTerm = request.params.searchTerm || '';
|
||||
const signerStatus = request.params.signerStatus || '';
|
||||
|
||||
const serverUrl = cloudServerUrl; //process.env.SERVER_URL;
|
||||
const appId = serverAppId;
|
||||
@@ -67,13 +68,23 @@ export default async function getReport(request) {
|
||||
}
|
||||
}
|
||||
paramsObj = applySearch({ reportId, baseWhere: paramsObj, searchTerm });
|
||||
|
||||
const clsName = json?.reportClass ? json.reportClass : 'contracts_Document';
|
||||
|
||||
if (clsName === 'contracts_Document' && signerStatus) {
|
||||
const normalizedStatus =
|
||||
signerStatus === 'viewed' ? 'Viewed' : signerStatus === 'signed' ? 'Signed' : '';
|
||||
if (normalizedStatus) {
|
||||
paramsObj = { ...paramsObj, 'AuditTrail.Activity': normalizedStatus };
|
||||
}
|
||||
}
|
||||
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Parse-Application-Id': appId,
|
||||
'X-Parse-Master-Key': masterKey,
|
||||
};
|
||||
|
||||
const clsName = json?.reportClass ? json.reportClass : 'contracts_Document';
|
||||
const orderBy = '-updatedAt';
|
||||
const include = 'AuditTrail.UserPtr,Placeholders.signerPtr,ExtUserPtr.TenantId';
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import { Placeholder } from './Placeholder.js';
|
||||
import { SignPdf } from '@signpdf/signpdf';
|
||||
import { P12Signer } from '@signpdf/signer-p12';
|
||||
import { buildDownloadFilename, parseUploadFile } from '../../../utils/fileUtils.js';
|
||||
import sendMailWithAttachment from '../sendMailWithAttachment.js';
|
||||
|
||||
const serverUrl = cloudServerUrl; // process.env.SERVER_URL;
|
||||
const APPID = serverAppId;
|
||||
@@ -224,7 +225,7 @@ async function sendCompletedMail(obj) {
|
||||
const variables = {
|
||||
document_title: pdfName,
|
||||
note: doc?.Note,
|
||||
sender_name: sender.Name,
|
||||
sender_name: doc?.SenderName || sender.Name,
|
||||
sender_mail: doc?.SenderMail || sender.Email,
|
||||
sender_phone: sender?.Phone || '',
|
||||
receiver_name: sender.Name,
|
||||
@@ -249,8 +250,8 @@ async function sendCompletedMail(obj) {
|
||||
const params = {
|
||||
extUserId: sender.objectId,
|
||||
url: url,
|
||||
from: TenantAppName,
|
||||
replyto: doc?.ExtUserPtr?.Email || '',
|
||||
from: doc?.SenderName || TenantAppName,
|
||||
replyto: doc?.SenderMail || doc?.ExtUserPtr?.Email || '',
|
||||
recipient: recipient,
|
||||
subject: subject,
|
||||
pdfName: pdfName,
|
||||
@@ -261,9 +262,9 @@ async function sendCompletedMail(obj) {
|
||||
filename: docName,
|
||||
};
|
||||
try {
|
||||
const res = await axios.post(serverUrl + '/functions/sendmailv3', params, { headers });
|
||||
// console.log('res', res.data.result);
|
||||
if (res.data?.result?.status !== 'success') {
|
||||
const res = await sendMailWithAttachment(params);
|
||||
// console.log("res ", res)
|
||||
if (res?.status !== 'success') {
|
||||
unlinkFile(`./exports/signed_certificate_${doc.objectId}.pdf`);
|
||||
}
|
||||
} catch (err) {
|
||||
|
||||
@@ -18,6 +18,8 @@ export default function reportJson(id, currentUserId) {
|
||||
'Placeholders',
|
||||
'TemplateId',
|
||||
'ExpiryDate',
|
||||
'SenderName',
|
||||
'SenderMail',
|
||||
];
|
||||
const inProgressKeys = [
|
||||
...commanKeys,
|
||||
@@ -25,8 +27,10 @@ export default function reportJson(id, currentUserId) {
|
||||
'SendMail',
|
||||
'RequestBody',
|
||||
'RequestSubject',
|
||||
'EmailEditorType',
|
||||
'ExtUserPtr.TenantId.RequestBody',
|
||||
'ExtUserPtr.TenantId.RequestSubject',
|
||||
'ExtUserPtr.TenantId.EmailEditorType',
|
||||
'DocSentAt',
|
||||
];
|
||||
const filterKeys = [
|
||||
|
||||
@@ -29,11 +29,11 @@ export default async function saveAsTemplate(request) {
|
||||
templateCls.set('IsEnableOTP', _docRes?.IsEnableOTP === true ? true : false);
|
||||
templateCls.set('IsTourEnabled', _docRes?.IsTourEnabled === true ? true : false);
|
||||
templateCls.set('AllowModifications', _docRes?.AllowModifications || false);
|
||||
templateCls.set('EmailSenderName', _docRes?.EmailSenderName);
|
||||
templateCls.set('SenderName', _docRes?.SenderName);
|
||||
templateCls.set('SenderMail', _docRes?.SenderMail);
|
||||
templateCls.set('RequestBody', _docRes?.RequestBody);
|
||||
templateCls.set('RequestSubject', _docRes?.RequestSubject);
|
||||
if (_docRes?.EmailEditorType) templateCls.set('EmailEditorType', _docRes?.EmailEditorType);
|
||||
templateCls.set('NextReminderDate', _docRes?.NextReminderDate);
|
||||
templateCls.set('RedirectUrl', _docRes?.RedirectUrl);
|
||||
templateCls.set(
|
||||
|
||||
@@ -24,6 +24,19 @@ const refreshAccessToken = async refreshToken => {
|
||||
return response.data.access_token;
|
||||
};
|
||||
|
||||
const getGmail = async (access_token, displayName) => {
|
||||
try {
|
||||
const res = await axios.get('https://www.googleapis.com/oauth2/v2/userinfo', {
|
||||
headers: { Authorization: `Bearer ${access_token}` },
|
||||
});
|
||||
|
||||
const gmail = res.data.email;
|
||||
return `${displayName} <${gmail}>`;
|
||||
} catch (err) {
|
||||
console.log('gmail retrive error ', err);
|
||||
return displayName;
|
||||
}
|
||||
};
|
||||
// Function to create a raw email message
|
||||
const makeEmail = async (
|
||||
to,
|
||||
@@ -101,7 +114,7 @@ const makeEmail = async (
|
||||
}
|
||||
} catch (err) {
|
||||
attachments = [file];
|
||||
console.log('Err in read certificate sendmailv3', err);
|
||||
console.log('sendMailGmailProvider read certificate error', err);
|
||||
}
|
||||
}
|
||||
const attachmentParts = attachments.map(attachment => {
|
||||
@@ -166,7 +179,8 @@ export default async function sendMailGmailProvider(_extRes, template) {
|
||||
|
||||
try {
|
||||
// Construct email message
|
||||
const from = sender || _extRes.Email || 'me';
|
||||
const displayName = sender || _extRes.Email || 'me';
|
||||
const from = await getGmail(access_token, displayName);
|
||||
const to = receiver;
|
||||
const randomNumber = Math.floor(Math.random() * 5000);
|
||||
const testPdf = `test_${randomNumber}.pdf`;
|
||||
@@ -203,7 +217,7 @@ export default async function sendMailGmailProvider(_extRes, template) {
|
||||
try {
|
||||
fs.unlinkSync(testPdf);
|
||||
} catch (err) {
|
||||
console.log('Err in unlink pdf sendmailv3');
|
||||
console.log('sendMailGmailProvider unlink pdf error');
|
||||
}
|
||||
}
|
||||
return { code: 200, message: 'Email sent successfully' };
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
import fs from 'node:fs';
|
||||
import https from 'https';
|
||||
import formData from 'form-data';
|
||||
import Mailgun from 'mailgun.js';
|
||||
import { appName, smtpenable, smtpsecure, updateMailCount } from '../../Utils.js';
|
||||
import { createTransport } from 'nodemailer';
|
||||
import axios from 'axios';
|
||||
|
||||
function safeUnlink(filePath, label = 'file') {
|
||||
if (fs.existsSync(filePath)) {
|
||||
try {
|
||||
fs.unlinkSync(filePath);
|
||||
} catch (err) {
|
||||
console.log(`sendMailWithAttachment unlink ${label} error`);
|
||||
}
|
||||
}
|
||||
}
|
||||
async function sendMailProvider(params) {
|
||||
const app = appName;
|
||||
const extUserId = params?.extUserId || '';
|
||||
const reportMsg = `<p style="font-size: 13px; color:grey; text-align: center;">If you think this email is inappropriate or spam, you may file a complaint with OpenSign™ <a href="mailto:complaints@opensignlabs.com?subject=Spam%20report%20for%20user%20ID%20${extUserId}&body=Hello%20Support%20Team%2C%0D%0A%0D%0AI%E2%80%99m%20reporting%20spam%20activity%20coming%20from%20a%20sender%20using%20your%20platform.%0D%0A%0D%0AThe%20messages%20I%20received%20appear%20unsolicited%20and%20suspicious.%20The%20user%20ID%20associated%20with%20the%20emails%20is%3A%20${extUserId}.%20Please%20investigate%20this%20account%20and%20take%20appropriate%20action%20to%20prevent%20further%20abuse.%0D%0A%0D%0AIf%20you%20need%20additional%20details%2C%20I%E2%80%99m%20happy%20to%20provide%20the%20original%20email%20headers%20or%20screenshots.%0D%0A%0D%0AThank%20you%20for%20looking%20into%20this.%0D%0A%0D%0ABest%20regards%2C%0D%0A%5BYour%20Name%5D">here</a>.</p>`;
|
||||
|
||||
const mailgunApiKey = process.env.MAILGUN_API_KEY;
|
||||
try {
|
||||
let transporterSMTP;
|
||||
let mailgunClient;
|
||||
let mailgunDomain;
|
||||
if (smtpenable) {
|
||||
let transporterConfig = {
|
||||
host: process.env.SMTP_HOST,
|
||||
port: process.env.SMTP_PORT || 465,
|
||||
secure: smtpsecure,
|
||||
};
|
||||
|
||||
// ✅ Add auth only if BOTH username & password exist
|
||||
const smtpUser = process.env.SMTP_USERNAME;
|
||||
const smtpPass = process.env.SMTP_PASS;
|
||||
|
||||
if (smtpUser && smtpPass) {
|
||||
transporterConfig.auth = {
|
||||
user: process.env.SMTP_USERNAME ? process.env.SMTP_USERNAME : process.env.SMTP_USER_EMAIL,
|
||||
pass: smtpPass,
|
||||
};
|
||||
}
|
||||
transporterSMTP = createTransport(transporterConfig);
|
||||
} else {
|
||||
if (mailgunApiKey) {
|
||||
const mailgun = new Mailgun(formData);
|
||||
mailgunClient = mailgun.client({ username: 'api', key: mailgunApiKey });
|
||||
mailgunDomain = process.env.MAILGUN_DOMAIN;
|
||||
}
|
||||
}
|
||||
if (params.url) {
|
||||
const randomNumber = Math.floor(Math.random() * 5000);
|
||||
const testPdf = `test_${randomNumber}.pdf`;
|
||||
try {
|
||||
let Pdf = fs.createWriteStream(testPdf);
|
||||
const writeToLocalDisk = () => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const isSecure =
|
||||
new URL(params.url)?.protocol === 'https:' &&
|
||||
new URL(params.url)?.hostname !== 'localhost';
|
||||
if (isSecure) {
|
||||
https
|
||||
.get(params.url, async function (response) {
|
||||
response.pipe(Pdf);
|
||||
response.on('end', () => resolve('success'));
|
||||
})
|
||||
.on('error', e => {
|
||||
console.error(`error: ${e.message}`);
|
||||
resolve('error');
|
||||
});
|
||||
} else {
|
||||
const httpsAgent = new https.Agent({ rejectUnauthorized: false }); // Disable SSL validation
|
||||
const localUrl = params.url;
|
||||
const newlocalUrl = localUrl.replace(
|
||||
'https://localhost:3001/api',
|
||||
'http://localhost:8080'
|
||||
);
|
||||
axios
|
||||
.get(newlocalUrl, { responseType: 'stream', httpsAgent: httpsAgent })
|
||||
.then(response => {
|
||||
response.data.pipe(Pdf);
|
||||
Pdf.on('finish', () => resolve('success'));
|
||||
Pdf.on('error', () => resolve('error'));
|
||||
})
|
||||
.catch(e => {
|
||||
console.log('error in localurl', e.message);
|
||||
resolve('error');
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
// `writeToLocalDisk` is used to create pdf file from doc url
|
||||
const ress = await writeToLocalDisk();
|
||||
if (ress) {
|
||||
function readTolocal() {
|
||||
return new Promise((resolve, reject) => {
|
||||
setTimeout(() => {
|
||||
let PdfBuffer = fs.readFileSync(Pdf.path);
|
||||
resolve(PdfBuffer);
|
||||
}, 100);
|
||||
});
|
||||
}
|
||||
// `PdfBuffer` used to create buffer from pdf file
|
||||
let PdfBuffer = await readTolocal();
|
||||
const pdfName = params.pdfName && `${params.pdfName}.pdf`;
|
||||
const filename = params.filename;
|
||||
const file = {
|
||||
filename: filename || pdfName || 'exported.pdf',
|
||||
content: smtpenable ? PdfBuffer : undefined,
|
||||
data: smtpenable ? undefined : PdfBuffer,
|
||||
};
|
||||
|
||||
let attachment;
|
||||
const certificatePath = params.certificatePath || `./exports/certificate.pdf`;
|
||||
if (fs.existsSync(certificatePath)) {
|
||||
try {
|
||||
// `certificateBuffer` used to create buffer from pdf file
|
||||
const certificateBuffer = fs.readFileSync(certificatePath);
|
||||
const certificate = {
|
||||
filename: 'certificate.pdf',
|
||||
content: smtpenable ? certificateBuffer : undefined, //fs.readFileSync('./exports/exported_file_1223.pdf'),
|
||||
data: smtpenable ? undefined : certificateBuffer,
|
||||
};
|
||||
attachment = [file, certificate];
|
||||
} catch (err) {
|
||||
attachment = [file];
|
||||
console.log('sendMailWithAttachment read certificate error', err);
|
||||
}
|
||||
} else {
|
||||
attachment = [file];
|
||||
}
|
||||
const from = params.from || '';
|
||||
const mailsender = smtpenable ? process.env.SMTP_USER_EMAIL : process.env.MAILGUN_SENDER;
|
||||
const replyto = params?.replyto || '';
|
||||
const messageParams = {
|
||||
from: from + ' <' + mailsender + '>',
|
||||
to: params.recipient,
|
||||
subject: params.subject,
|
||||
text: params.text || 'mail',
|
||||
html: params?.html ? params.html + reportMsg : '',
|
||||
attachments: smtpenable ? attachment : undefined,
|
||||
attachment: smtpenable ? undefined : attachment,
|
||||
bcc: params.bcc ? params.bcc : undefined,
|
||||
replyTo: replyto ? replyto : undefined,
|
||||
};
|
||||
const cleanupPaths = [
|
||||
{ path: certificatePath, label: 'certificate' },
|
||||
{ path: testPdf, label: 'pdf' },
|
||||
];
|
||||
if (transporterSMTP) {
|
||||
const res = await transporterSMTP.sendMail(messageParams);
|
||||
console.log('smtp transporter res: ', res?.response);
|
||||
if (!res.err) {
|
||||
if (extUserId) {
|
||||
await updateMailCount(extUserId);
|
||||
}
|
||||
|
||||
cleanupPaths.forEach(file => safeUnlink(file.path, file.label));
|
||||
return { status: 'success' };
|
||||
}
|
||||
} else {
|
||||
if (mailgunApiKey) {
|
||||
const res = await mailgunClient.messages.create(mailgunDomain, messageParams);
|
||||
console.log('mailgun res: ', res?.status);
|
||||
if (res.status === 200) {
|
||||
if (extUserId) {
|
||||
await updateMailCount(extUserId);
|
||||
}
|
||||
cleanupPaths.forEach(file => safeUnlink(file.path, file.label));
|
||||
return { status: 'success' };
|
||||
}
|
||||
} else {
|
||||
cleanupPaths.forEach(file => safeUnlink(file.path, file.label));
|
||||
return { status: 'error' };
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(`sendMailWithAttachment error: ${err}`);
|
||||
safeUnlink(testPdf, 'testPdf');
|
||||
if (err) return { status: 'error' };
|
||||
}
|
||||
} else {
|
||||
const from = params.from || '';
|
||||
const mailsender = smtpenable ? process.env.SMTP_USER_EMAIL : process.env.MAILGUN_SENDER;
|
||||
const replyto = params?.replyto || '';
|
||||
const messageParams = {
|
||||
from: from + ' <' + mailsender + '>',
|
||||
to: params.recipient,
|
||||
subject: params.subject,
|
||||
text: params.text || 'mail',
|
||||
html: params?.html ? params.html + reportMsg : '',
|
||||
bcc: params.bcc ? params.bcc : undefined,
|
||||
replyTo: replyto ? replyto : undefined,
|
||||
};
|
||||
|
||||
if (transporterSMTP) {
|
||||
const res = await transporterSMTP.sendMail(messageParams);
|
||||
console.log('smtp transporter res: ', res?.response);
|
||||
if (!res.err) {
|
||||
if (extUserId) {
|
||||
await updateMailCount(extUserId);
|
||||
}
|
||||
return { status: 'success' };
|
||||
}
|
||||
} else {
|
||||
if (mailgunApiKey) {
|
||||
const res = await mailgunClient.messages.create(mailgunDomain, messageParams);
|
||||
console.log('mailgun res: ', res?.status);
|
||||
if (res.status === 200) {
|
||||
if (extUserId) {
|
||||
await updateMailCount(extUserId);
|
||||
}
|
||||
return { status: 'success' };
|
||||
}
|
||||
} else {
|
||||
return { status: 'error' };
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(`sendMailWithAttachment Error: ${err}`);
|
||||
if (err) {
|
||||
return { status: 'error' };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// `sendMailWithAttachment` function is used to send completion and forwarded document mail and it also fix security issue.
|
||||
export default async function sendMailWithAttachment(params) {
|
||||
const nonCustomMail = await sendMailProvider(params);
|
||||
return nonCustomMail;
|
||||
}
|
||||
@@ -40,220 +40,45 @@ async function sendMailProvider(req) {
|
||||
mailgunDomain = process.env.MAILGUN_DOMAIN;
|
||||
}
|
||||
}
|
||||
if (req.params.url) {
|
||||
const randomNumber = Math.floor(Math.random() * 5000);
|
||||
const testPdf = `test_${randomNumber}.pdf`;
|
||||
try {
|
||||
let Pdf = fs.createWriteStream(testPdf);
|
||||
const writeToLocalDisk = () => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const isSecure =
|
||||
new URL(req.params.url)?.protocol === 'https:' &&
|
||||
new URL(req.params.url)?.hostname !== 'localhost';
|
||||
if (isSecure) {
|
||||
https
|
||||
.get(req.params.url, async function (response) {
|
||||
response.pipe(Pdf);
|
||||
response.on('end', () => resolve('success'));
|
||||
})
|
||||
.on('error', e => {
|
||||
console.error(`error: ${e.message}`);
|
||||
resolve('error');
|
||||
});
|
||||
} else {
|
||||
const httpsAgent = new https.Agent({ rejectUnauthorized: false }); // Disable SSL validation
|
||||
const localUrl = req.params.url;
|
||||
const newlocalUrl = localUrl.replace(
|
||||
'https://localhost:3001/api',
|
||||
'http://localhost:8080'
|
||||
);
|
||||
axios
|
||||
.get(newlocalUrl, { responseType: 'stream', httpsAgent: httpsAgent })
|
||||
.then(response => {
|
||||
response.data.pipe(Pdf);
|
||||
Pdf.on('finish', () => resolve('success'));
|
||||
Pdf.on('error', () => resolve('error'));
|
||||
})
|
||||
.catch(e => {
|
||||
console.log('error in localurl', e.message);
|
||||
resolve('error');
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
// `writeToLocalDisk` is used to create pdf file from doc url
|
||||
const ress = await writeToLocalDisk();
|
||||
if (ress) {
|
||||
function readTolocal() {
|
||||
return new Promise((resolve, reject) => {
|
||||
setTimeout(() => {
|
||||
let PdfBuffer = fs.readFileSync(Pdf.path);
|
||||
resolve(PdfBuffer);
|
||||
}, 100);
|
||||
});
|
||||
}
|
||||
// `PdfBuffer` used to create buffer from pdf file
|
||||
let PdfBuffer = await readTolocal();
|
||||
const pdfName = req.params.pdfName && `${req.params.pdfName}.pdf`;
|
||||
const filename = req.params.filename;
|
||||
const file = {
|
||||
filename: filename || pdfName || 'exported.pdf',
|
||||
content: smtpenable ? PdfBuffer : undefined,
|
||||
data: smtpenable ? undefined : PdfBuffer,
|
||||
};
|
||||
|
||||
let attachment;
|
||||
const certificatePath = req.params.certificatePath || `./exports/certificate.pdf`;
|
||||
if (fs.existsSync(certificatePath)) {
|
||||
try {
|
||||
// `certificateBuffer` used to create buffer from pdf file
|
||||
const certificateBuffer = fs.readFileSync(certificatePath);
|
||||
const certificate = {
|
||||
filename: 'certificate.pdf',
|
||||
content: smtpenable ? certificateBuffer : undefined, //fs.readFileSync('./exports/exported_file_1223.pdf'),
|
||||
data: smtpenable ? undefined : certificateBuffer,
|
||||
};
|
||||
attachment = [file, certificate];
|
||||
} catch (err) {
|
||||
attachment = [file];
|
||||
console.log('Err in read certificate sendmailv3', err);
|
||||
}
|
||||
} else {
|
||||
attachment = [file];
|
||||
}
|
||||
const from = req.params.from || '';
|
||||
const mailsender = smtpenable ? process.env.SMTP_USER_EMAIL : process.env.MAILGUN_SENDER;
|
||||
const replyto = req.params?.replyto || '';
|
||||
const messageParams = {
|
||||
from: from + ' <' + mailsender + '>',
|
||||
to: req.params.recipient,
|
||||
subject: req.params.subject,
|
||||
text: req.params.text || 'mail',
|
||||
html: req.params?.html ? req.params.html + reportMsg : '',
|
||||
attachments: smtpenable ? attachment : undefined,
|
||||
attachment: smtpenable ? undefined : attachment,
|
||||
bcc: req.params.bcc ? req.params.bcc : undefined,
|
||||
replyTo: replyto ? replyto : undefined,
|
||||
};
|
||||
if (transporterSMTP) {
|
||||
const res = await transporterSMTP.sendMail(messageParams);
|
||||
console.log('smtp transporter res: ', res?.response);
|
||||
if (!res.err) {
|
||||
if (extUserId) {
|
||||
await updateMailCount(extUserId);
|
||||
}
|
||||
if (fs.existsSync(certificatePath)) {
|
||||
try {
|
||||
fs.unlinkSync(certificatePath);
|
||||
} catch (err) {
|
||||
console.log('Err in unlink certificate sendmailv3');
|
||||
}
|
||||
}
|
||||
if (fs.existsSync(testPdf)) {
|
||||
try {
|
||||
fs.unlinkSync(testPdf);
|
||||
} catch (err) {
|
||||
console.log('Err in unlink pdf sendmailv3');
|
||||
}
|
||||
}
|
||||
return { status: 'success' };
|
||||
}
|
||||
} else {
|
||||
if (mailgunApiKey) {
|
||||
const res = await mailgunClient.messages.create(mailgunDomain, messageParams);
|
||||
console.log('mailgun res: ', res?.status);
|
||||
if (res.status === 200) {
|
||||
if (extUserId) {
|
||||
await updateMailCount(extUserId);
|
||||
}
|
||||
if (fs.existsSync(certificatePath)) {
|
||||
try {
|
||||
fs.unlinkSync(certificatePath);
|
||||
} catch (err) {
|
||||
console.log('Err in unlink certificate sendmailv3');
|
||||
}
|
||||
}
|
||||
if (fs.existsSync(testPdf)) {
|
||||
try {
|
||||
fs.unlinkSync(testPdf);
|
||||
} catch (err) {
|
||||
console.log('Err in unlink pdf sendmailv3');
|
||||
}
|
||||
}
|
||||
return { status: 'success' };
|
||||
}
|
||||
} else {
|
||||
if (fs.existsSync(certificatePath)) {
|
||||
try {
|
||||
fs.unlinkSync(certificatePath);
|
||||
} catch (err) {
|
||||
console.log('Err in unlink certificate sendmailv3');
|
||||
}
|
||||
}
|
||||
if (fs.existsSync(testPdf)) {
|
||||
try {
|
||||
fs.unlinkSync(testPdf);
|
||||
} catch (err) {
|
||||
console.log('Err in unlink pdf sendmailv3');
|
||||
}
|
||||
}
|
||||
return { status: 'error' };
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(`Error in sendmailv3: ${err}`);
|
||||
if (fs.existsSync(testPdf)) {
|
||||
try {
|
||||
fs.unlinkSync(testPdf);
|
||||
} catch (err) {
|
||||
console.log('Err in unlink pdf sendmailv3');
|
||||
}
|
||||
}
|
||||
if (err) {
|
||||
return { status: 'error' };
|
||||
const from = req.params.from || '';
|
||||
const mailsender = smtpenable ? process.env.SMTP_USER_EMAIL : process.env.MAILGUN_SENDER;
|
||||
const replyto = req.params?.replyto || '';
|
||||
const messageParams = {
|
||||
from: from + ' <' + mailsender + '>',
|
||||
to: req.params.recipient,
|
||||
subject: req.params.subject,
|
||||
text: req.params.text || 'mail',
|
||||
html: req.params?.html ? req.params.html + reportMsg : '',
|
||||
bcc: req.params.bcc ? req.params.bcc : undefined,
|
||||
replyTo: replyto ? replyto : undefined,
|
||||
};
|
||||
|
||||
if (transporterSMTP) {
|
||||
const res = await transporterSMTP.sendMail(messageParams);
|
||||
console.log('smtp transporter res: ', res?.response);
|
||||
if (!res.err) {
|
||||
if (extUserId) {
|
||||
await updateMailCount(extUserId);
|
||||
}
|
||||
return { status: 'success' };
|
||||
}
|
||||
} else {
|
||||
const from = req.params.from || '';
|
||||
const mailsender = smtpenable ? process.env.SMTP_USER_EMAIL : process.env.MAILGUN_SENDER;
|
||||
const replyto = req.params?.replyto || '';
|
||||
const messageParams = {
|
||||
from: from + ' <' + mailsender + '>',
|
||||
to: req.params.recipient,
|
||||
subject: req.params.subject,
|
||||
text: req.params.text || 'mail',
|
||||
html: req.params?.html ? req.params.html + reportMsg : '',
|
||||
bcc: req.params.bcc ? req.params.bcc : undefined,
|
||||
replyTo: replyto ? replyto : undefined,
|
||||
};
|
||||
|
||||
if (transporterSMTP) {
|
||||
const res = await transporterSMTP.sendMail(messageParams);
|
||||
console.log('smtp transporter res: ', res?.response);
|
||||
if (!res.err) {
|
||||
if (mailgunApiKey) {
|
||||
const res = await mailgunClient.messages.create(mailgunDomain, messageParams);
|
||||
console.log('mailgun res: ', res?.status);
|
||||
if (res.status === 200) {
|
||||
if (extUserId) {
|
||||
await updateMailCount(extUserId);
|
||||
}
|
||||
return { status: 'success' };
|
||||
}
|
||||
} else {
|
||||
if (mailgunApiKey) {
|
||||
const res = await mailgunClient.messages.create(mailgunDomain, messageParams);
|
||||
console.log('mailgun res: ', res?.status);
|
||||
if (res.status === 200) {
|
||||
if (extUserId) {
|
||||
await updateMailCount(extUserId);
|
||||
}
|
||||
return { status: 'success' };
|
||||
}
|
||||
} else {
|
||||
return { status: 'error' };
|
||||
}
|
||||
return { status: 'error' };
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(`Error in sendmailv3: ${err}`);
|
||||
console.log(`sendmailv3 Error: ${err}`);
|
||||
if (err) {
|
||||
return { status: 'error' };
|
||||
}
|
||||
|
||||
@@ -24,6 +24,8 @@ export default async function updateEmailTemplates(request) {
|
||||
}
|
||||
}
|
||||
});
|
||||
if (details?.EmailEditorType) extUserRes.set('EmailEditorType', details.EmailEditorType);
|
||||
|
||||
const updateExtRes = await extUserRes.save(null, { useMasterKey: true });
|
||||
if (updateExtRes) {
|
||||
const res = JSON.parse(JSON.stringify(updateExtRes));
|
||||
|
||||
@@ -5,6 +5,7 @@ export default async function updatePreferences(request) {
|
||||
const SignatureType = request.params.SignatureType || [];
|
||||
const NotifyOnSignatures = request.params.NotifyOnSignatures;
|
||||
const Timezone = request.params.Timezone;
|
||||
const UseNameAsSender = request.params.UseNameAsSender;
|
||||
if (SignatureType?.length > 0 || NotifyOnSignatures !== undefined || Timezone) {
|
||||
try {
|
||||
const orgQuery = new Parse.Query('contracts_Users');
|
||||
@@ -60,6 +61,9 @@ export default async function updatePreferences(request) {
|
||||
if (request.params.DownloadFilenameFormat) {
|
||||
newOrg.set('DownloadFilenameFormat', request.params.DownloadFilenameFormat);
|
||||
}
|
||||
if (UseNameAsSender !== undefined) {
|
||||
newOrg.set('UseNameAsSender', UseNameAsSender);
|
||||
}
|
||||
const updateUserRes = await newOrg.save(null, { useMasterKey: true });
|
||||
if (updateUserRes) {
|
||||
const _updateUserRes = JSON.parse(JSON.stringify(updateUserRes));
|
||||
|
||||
@@ -22,6 +22,7 @@ export default async function updateTenant(request) {
|
||||
}
|
||||
}
|
||||
});
|
||||
if (details?.EmailEditorType) tenant.set('EmailEditorType', details.EmailEditorType);
|
||||
|
||||
const tenantRes = await tenant.save(null, { useMasterKey: true });
|
||||
if (tenantRes) {
|
||||
|
||||
Reference in New Issue
Block a user