71 lines
2.1 KiB
TypeScript
71 lines
2.1 KiB
TypeScript
import * as os from 'os';
|
|
import * as path from 'path';
|
|
import * as fs from 'fs';
|
|
import * as https from 'https';
|
|
import { getLogger } from "../shared/config";
|
|
import formData from 'form-data';
|
|
import Mailgun from 'mailgun.js';
|
|
const { convert } = require('html-to-text');
|
|
|
|
const mailgun = new Mailgun(formData);
|
|
const logger = getLogger();
|
|
|
|
export async function sendEmailWithAttachmentUtil(
|
|
toAddress: string,
|
|
subject: string,
|
|
message: string,
|
|
fileUrl: string,
|
|
fileName?: string
|
|
): Promise<any> {
|
|
try {
|
|
const tempFilePath = path.join(os.tmpdir(), fileName || 'attachment.pdf');
|
|
await new Promise<void>((resolve, reject) => {
|
|
const file = fs.createWriteStream(tempFilePath);
|
|
https.get(fileUrl, (res) => {
|
|
res.pipe(file);
|
|
file.on('finish', () => {
|
|
file.close();
|
|
resolve();
|
|
});
|
|
}).on('error', (err) => {
|
|
fs.unlink(tempFilePath, () => {});
|
|
reject(err);
|
|
});
|
|
});
|
|
|
|
try {
|
|
const client = mailgun.client({ username: 'api', key: process.env.MAILGUN_API_KEY! });
|
|
const options = {
|
|
wordwrap: 130,
|
|
};
|
|
const textMessage = convert(message, options);
|
|
const fileBuffer = fs.readFileSync(tempFilePath);
|
|
const attachmentFilename = fileName || path.basename(fileUrl.split('?')[0]);
|
|
|
|
const data = {
|
|
from: process.env.MAILGUN_FROM_ADDRESS,
|
|
to: toAddress,
|
|
subject: subject,
|
|
text: textMessage,
|
|
html: message,
|
|
attachment: {
|
|
data: fileBuffer,
|
|
filename: attachmentFilename,
|
|
contentType: 'application/pdf',
|
|
}
|
|
};
|
|
|
|
const result = await client.messages.create(process.env.MAILGUN_SERVER!, data);
|
|
fs.unlinkSync(tempFilePath);
|
|
logger.info('Email with attachment from URL sent successfully');
|
|
return { success: true, result };
|
|
} catch (e) {
|
|
logger.error(`Error while sending E-mail. Error: ${e}`);
|
|
throw e;
|
|
}
|
|
} catch (error) {
|
|
logger.error('Error sending email with attachment from URL:', error);
|
|
throw error;
|
|
}
|
|
}
|