前言:新书系统上传完文件之后,需要给每个用户发送邮件提醒,并携带附件发送,每个邮件主题,正文都是固定的,附件内容也是固定的,但是给每个人发的附件内的名字要和收件人相同,日期也要是发送时的当前日期,同时要把修改后的附件word要转成pdf格式之后再发送。
一,后端接口
var express = require('express');
var router = express.Router();
const nodemailer = require('nodemailer');
const path = require('path');
const fs = require('fs');
const doc2pdf = require('doc2pdf');
const docx = require('docx');
const PizZip = require("pizzip");
const moment = require("moment");
const Docxtemplater = require("docxtemplater");
const docxtopdf = require("docx-to-pdf");
const docxConverter = require('docx-pdf');
const { exec } = require('child_process');
// const { Document,Paragraph,Packer } = require('docx')
// console.log(docx);
/* GET home page. */
router.get('/', function(req, res, next) {
// 解析 sss文件
console.log(req.query);
try {
const content = fs.readFileSync(
path.resolve(__dirname, "../public/index/book.docx"),
"binary"
);
const zip = new PizZip(content);
const doc = new Docxtemplater(zip, {
paragraphLoop: true,
linebreaks: true,
});
let dates = moment().format('YYYY年MM月DD日')
doc.render({
username: req.query.name,
date:dates,
});
const buf = doc.getZip().generate({
type: "nodebuffer",
// compression: DEFLATE adds a compression step.
// For a 50MB output document, expect 500ms additional CPU time
compression: "DEFLATE",
});
fs.writeFileSync(path.resolve(__dirname, "../public/index/newBook.docx"), buf);
const convertDocxToPdf = () => {
console.log('111111111');
// 使用 pandoc 命令将 .docx 文件转换为 PDF
exec(`soffice --headless --convert-to pdf ${path.resolve(__dirname, "../public/index/newBook.docx")}`, (error, stdout, stderr) => {
if (error) {
console.error('Error occurred:', error);
return;
}
console.log('Conversion successful. PDF saved.');
let transporter = nodemailer.createTransport({
service:'163',//邮箱
secure:true,//安全发送模式
auth:{
user:'chenlun20208888@163.com',//发件人
pass:'IMJNXIKYICQRYECD'
}
})
let mailOptions = {
from:'chenlun20208888@163.com',//发件的人
to:req.query.email,//收件的人
subject:'《油气数字化架构与生态》',//邮件主题
text:'《油气数字化架构与生态》电子版',//邮件正文
attachments: [
{
filename: 'sendBook.pdf',
path: path.join(__dirname, "../../myStudy/newBook.pdf")
}
]
}
transporter.sendMail(mailOptions,(err,data)=>{
if (err) {
res.send('发送失败4');
}else{
res.send({
status:0,
message:'发送成功',
})
}
})
});
};
convertDocxToPdf();
} catch (error) {
res.send('发送失败3');
}
});
module.exports = router;
附言:转pdf下载了它,使用了
并改了源码;