You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

370 lines
15 KiB
Plaintext

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<%@ page import="java.io.*, java.util.zip.*" %>
<%@ page import="javax.mail.internet.InternetAddress" %>
<%@ page import="javax.mail.internet.MimeMessage" %>
<%@ page import="javax.mail.internet.MimeBodyPart" %>
<%@ page import="javax.mail.internet.MimeMultipart" %>
<%@ page import="javax.mail.*" %>
<%@ page import="javax.net.ssl.SSLContext" %>
<%@ page import="javax.net.ssl.TrustManager" %>
<%@ page import="javax.net.ssl.X509TrustManager" %>
<%@ page import="javax.net.ssl.SSLSocketFactory" %>
<%@ page import="java.security.cert.X509Certificate" %>
<%@ page import="java.security.SecureRandom" %>
<%@ page import="java.nio.file.Files" %>
<%@ page import="java.nio.file.Paths" %>
<%@ page import="javax.activation.FileDataSource" %>
<%@ page import="javax.activation.DataHandler" %>
<%@ page import="javax.activation.DataSource" %>
<%@ page import="com.wbi.util.ParamUtil" %>
<%@ page import="weaver.general.Util" %>
<%@ page import="weaver.conn.RecordSet" %>
<%@ page import="java.util.*" %>
<%@ page import="weaver.hrm.User" %>
<%@ page import="java.awt.image.BufferedImage" %>
<%@ page import="javax.imageio.ImageIO" %>
<%@ page import="java.awt.*" %>
<%@ page import="org.slf4j.LoggerFactory" %>
<%@ page import="org.slf4j.Logger" %>
<%@ page import="weaver.general.StringUtil" %>
<%@ page import="weaver.file.ImageFileManager" %>
<%@ page import="com.engine.email.entity.EmailFlockSendAccountComInfo" %>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@page contentType="text/html; charset=UTF-8" %>
<%
Logger log = LoggerFactory.getLogger("CustomBusiness");
Map<String, Object> param = ParamUtil.request2Map(request);
String ids = Util.null2String(param.get("ids"));
RecordSet rs = new RecordSet();
rs.executeQuery("select * from uf_holidayGift where id in (" + ids+" )");
log.info("sql数量:{}",rs.getCounts());
ArrayList<HashMap<String, String>> list = new ArrayList<>();
while (rs.next()) {
//判断是否已经推送过,推送过先不推
String sfyts = rs.getString("sfyts");
if ("1".equals(sfyts)) {
continue;
}
HashMap<String, String> map = new HashMap<>();
map.put("fsr", rs.getString("fsr")); //发送人
map.put("kqbh", rs.getString("kqbh"));//卡券编号
map.put("dhm", rs.getString("dhm"));//兑换码
map.put("yxdz", rs.getString("yxdz"));//兑换地址
map.put("sfyts", rs.getString("sfyts"));//是否已推送
map.put("picid", rs.getString("picid"));//图片id
map.put("pic2id", rs.getString("pic2id"));//图片2id
map.put("id", rs.getString("id"));//图片id
map.put("yjzt", rs.getString("yjzt"));//邮件主题
list.add(map);
}
// 推送数据数量
log.info("推送数据的数量:{}", list.size());
if (list.size() == 0) {
log.info("未查询到需推送的数据");
}
int sendNum = list.size();
// 1. 读取HTML模板
String htmlContent = new String(Files.readAllBytes(Paths.get("/opt/oadata/temp/123.html")));
// 忽略SSL证书验证
SSLContext sslContext = SSLContext.getInstance("TLS");
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
sslContext.init(null, trustAllCerts, new SecureRandom());
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
EmailFlockSendAccountComInfo emailFlockSendAccountComInfo = new EmailFlockSendAccountComInfo();
// 邮件属性配置
Properties props = new Properties();
props.put("mail.smtp.host", emailFlockSendAccountComInfo.getSmtpServer("0"));
props.put("mail.smtp.port", emailFlockSendAccountComInfo.getSmtpServerPort("0"));
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sslSocketFactory); // 设置自定义的SSLSocketFactory
// 创建邮件会话
Session sessions = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(emailFlockSendAccountComInfo.getAccountMailAddress("0"), emailFlockSendAccountComInfo.getAccountPassword("0"));
}
});
HashMap<String, String> idPicUrlMap = new HashMap<>();
HashMap<String, Object> result = new HashMap<>();
int sendSuccessNum = 0;
for (HashMap<String, String> map : list) {
try {
// 2. 替换占位符
String code = map.get("kqbh");
String password = map.get("dhm");
//判断下这行数据是否为空,为空的话去发送人邮箱地址
String yxdz = map.get("yxdz");
if (StringUtil.isEmpty(yxdz)) {
yxdz = new User(Util.getIntValue(map.get("fsr"))).getEmail();
}
// htmlContent = htmlContent.replace("${code}", code);
// htmlContent = htmlContent.replace("${password}", password);
// 创建邮件消息
MimeMessage message = new MimeMessage(sessions);
message.setFrom(new InternetAddress(emailFlockSendAccountComInfo.getAccountMailAddress("0")));
// message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("2041427783@qq.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(yxdz));
message.setSubject(map.get("yjzt"));
// 创建HTML部分
// MimeBodyPart htmlPart = new MimeBodyPart();
// htmlPart.setContent(htmlContent, "text/html; charset=UTF-8");
// 6. 创建多部分邮件
MimeMultipart multipart = new MimeMultipart("related");
// 7. 添加HTML内容部分
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(htmlContent, "text/html; charset=utf-8");
multipart.addBodyPart(messageBodyPart);
// 8. 添加第一张图片
MimeBodyPart imagePart1 = new MimeBodyPart();
//获取图片地址
String picid = map.get("picid");
String picUrl = getPictureUrl(picid, idPicUrlMap);
DataSource fds1 = new FileDataSource(picUrl);
imagePart1.setDataHandler(new DataHandler(fds1));
imagePart1.setHeader("Content-ID", "<image1>");
multipart.addBodyPart(imagePart1);
String pic2id = map.get("pic2id");
String pic2Url = getPictureUrl(pic2id, idPicUrlMap);
String textToImagePath = "";
try {
textToImagePath = AddTextToImage(pic2Url, code, password);
}catch (Exception e){
log.error("添加文字到图片失败"+e.getMessage());
if (!StringUtil.isEmpty(textToImagePath)){
fileDelete(textToImagePath);
}
throw new Exception(e.getMessage());
}
// 9. 添加第二张图片
MimeBodyPart imagePart2 = new MimeBodyPart();
DataSource fds2 = new FileDataSource(textToImagePath);
imagePart2.setDataHandler(new DataHandler(fds2));
imagePart2.setHeader("Content-ID", "<image2>");
multipart.addBodyPart(imagePart2);
// multipart.addBodyPart(messageBodyPart);
// 9. 将多部分内容设置为邮件内容
message.setContent(multipart);
// 发送邮件
Transport.send(message);
log.info("邮件发送成功");
rs.executeUpdate("update uf_holidayGift set sfyts = 1 where id = ? ",map.get("id"));
log.info("人员:"+new User(Util.getIntValue(map.get("fsr"))).getLastname()+"邮箱:"+yxdz+"邮件发送成功");
sendSuccessNum++;
} catch (Exception e) {
// out.println("邮件发送失败:" + e.getMessage());
e.printStackTrace();
}
}
//删除下生产的图片
for (String picUrl : idPicUrlMap.values()) {
fileDelete(picUrl);
}
result.put("sendNum",sendNum);
result.put("sendSuccessNum",sendSuccessNum);
out.print(JSONObject.toJSONString(result));
%>
<%!
private static Logger log = LoggerFactory.getLogger("CustomBusiness");
private static String getPictureUrl(String picid, HashMap<String, String> idPicUrlMap) {
if (StringUtil.isEmpty(idPicUrlMap.get(picid))) {
return getPictureRealUrl(picid, idPicUrlMap);
} else {
return idPicUrlMap.get(picid);
}
}
private static String getPictureRealUrl(String picid, HashMap<String, String> idPicUrlMap) {
RecordSet rs = new RecordSet();
rs.executeQuery("select * from uf_qrcodePic where id = ?", picid);
rs.next();
String picture = rs.getString("picture");
rs.executeQuery("select imagefileid from ( select imagefileid,row_number() over (partition by docid order by VERSIONID) rn\n" +
" from DocImageFile where docid = ? ) a where rn = 1 ", picture);
rs.next();
int imagefileid = rs.getInt("imagefileid");
log.info("getPictureRealUrl:imagefileid:{}",imagefileid);
InputStream inputStream = null; // 初始化为实际的InputStream对象
OutputStream outputStream = null;
String uuid = "";
try {
ImageFileManager imageFileManager = new ImageFileManager();
imageFileManager.getImageFileInfoById(imagefileid);
inputStream = imageFileManager.getInputStream();
log.info("getPictureRealUrl:imageFileManager.getFilesize():{}",imageFileManager.getFilesize());
log.info("getPictureRealUrl:imageFileManager.getImageFileType():{}",imageFileManager.getImageFileType());
log.info("getPictureRealUrl:imageFileManager.getFileRealPath():{}",imageFileManager.getFileRealPath());
String imageFileName = imageFileManager.getImageFileName();
uuid = "/opt/weaver/oadata/temp/" + imageFileName;
if (inputStream == null) {
throw new IOException("InputStream is null, failed to retrieve input stream from ImageFileManager.");
}
// 创建File对象以便检查目录
File file = new File(uuid);
File parentDir = file.getParentFile();
// 检查父目录是否存在,如果不存在则创建
if (parentDir != null && !parentDir.exists()) {
parentDir.mkdirs(); // 创建包括所有父目录的目录
}
// 创建输出流,将内容写入到本地文件
outputStream = new FileOutputStream(file);
log.info("getPictureRealUrl:outputStream:{}",outputStream == null);
log.info("getPictureRealUrl:inputStream:{}",inputStream == null);
// 缓冲区大小可以根据需要调整
byte[] buffer = new byte[1024];
int bytesRead;
// 循环读取InputStream的内容到缓冲区并写入到文件中
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
// log.info("File saved successfully!");
} catch (IOException e) {
e.printStackTrace();
} finally {
// 确保关闭流,防止资源泄漏
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
idPicUrlMap.put(picid, uuid);
return uuid;
}
public static String AddTextToImage(String pic2Url, String code, String password) throws Exception {
// 输入图片路径
// String inputImagePath = "/opt/oadata/temp/image2.jpg";
// 输出图片路径
String picType = pic2Url.substring(pic2Url.lastIndexOf(".") + 1);
String outputImagePath = "/opt/weaver/oadata/temp/" + UUID.randomUUID()+"."+picType;
// 要添加的文本
// String text = "12324556";
// String text1 = "12324556";
log.info("AddTextToImage:outputImagePath:{}",outputImagePath);
log.info("AddTextToImage:pic2Url:{}",pic2Url);
try {
log.info("1");
// 读取图片
BufferedImage image = ImageIO.read(new File(pic2Url));
log.info("1.1");
// 确保图片有RGB颜色模式
BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
log.info("1.2");
Graphics2D g2d = newImage.createGraphics();
log.info("1.3");
g2d.drawImage(image, 0, 0, null);
log.info("2");
// 设置字体
Font font = new Font("Arial", Font.BOLD, 36);
g2d.setFont(font);
FontMetrics fm = g2d.getFontMetrics();
// 设置文本颜色
g2d.setColor(Color.RED);
log.info("3");
// 计算文本位置
// int x = (newImage.getWidth() - fm.stringWidth(text)) / 2;
// int y = newImage.getHeight() - fm.getHeight();
int x = 1200;
int y = 190;
// 在图片上绘制文本
g2d.drawString(code, x, y);
log.info("4");
g2d.setColor(Color.BLACK);
g2d.drawString(password, x, y + 90);
log.info("4");
// 释放Graphics2D对象
g2d.dispose();
log.info("6");
// 输出图片到文件
ImageIO.write(newImage, "jpg", new File(outputImagePath));
log.info("7");
log.info("文本已成功添加到图片!");
} catch (IOException ex) {
log.info("处理图片时出错:" + ex.getMessage());
throw new Exception("处理图片时出错:" + ex.getMessage());
}
return outputImagePath;
}
private static void fileDelete(String filePath){
// 创建File对象
File file = new File(filePath);
// 检查文件是否存在
if (file.exists()) {
// 尝试删除文件
boolean deleted = file.delete();
if (deleted) {
log.info("File deleted successfully.");
} else {
log.info("Failed to delete the file.");
}
} else {
log.info("File does not exist.");
}
}
%>