使用hutool阿里云企业邮箱发送邮件和附件,包含PDF转图片base64,PDF转HTML

请务必开启阿里云服务器465 ssl邮件端口
废话不多,我们直接上代码。

maven添加依赖:

java 复制代码
<dependency>
  <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.22</version>
</dependency>

<dependency>
  <groupId>e-iceblue</groupId>
    <artifactId>spire.pdf.free</artifactId>
    <version>4.4.1</version>
</dependency>

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.24</version>
</dependency>


<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
    </repository>
</repositories>

完整代码:

java 复制代码
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.junit.jupiter.api.Test;

import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

import com.spire.pdf.*;

import javax.imageio.ImageIO;

/**
 * @author hsj
 * @description:阿里云企业邮箱发送邮件和附件(请开启阿里云服务器465端口)
 * @date 2024-4-25 8:59
 */
@Slf4j
public class Temail {
	/**
	 * @Description:发邮件
	 * @author HeShengjin 2356899074@qq.com
	 * @date 2024-4-25 10:11
	 */
	@Test
	public void t() throws IOException {
		InputStream inputStream = null;
		try {
			//公司阿里云企业邮箱
			String from = "你的阿里云企业邮箱";

			// 加载PDF文档URL
			URL url = new URL("https://jixujiaoyu-test.oss-cn-shenzhen.aliyuncs.com/upload/20240425/1954fae396aa5aa1eb3dbad8edc19547.pdf");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			inputStream = conn.getInputStream();

//			// 获取字节数组
			byte[] bytesPdf = readInputStream(inputStream);


			MailSSLSocketFactory sf = new MailSSLSocketFactory();
			sf.setTrustAllHosts(true);

			MailAccount account = new MailAccount();
			account.setHost("smtp.mxhichina.com");
			account.setPort(465);
			account.setAuth(true);
			account.setSslEnable(true);
			account.setFrom(from.trim());
			account.setUser(from.trim());
			account.setPass("你的阿里云企业邮箱密码");
			account.setCharset(CharsetUtil.CHARSET_UTF_8);
			account.setCustomProperty("mail.smtp.ssl.socketFactory", sf);
			MailUtil.send(account,
				CollUtil.newArrayList("你的要发送的目标邮箱"),//目标邮箱
				"主题名称",//邮件主题
				"<p>测试发送邮件,使用阿里云云邮箱(发送中文名字附件)。</p>",
				true,//支持HTML内容
				FileUtil.writeBytes(bytesPdf,String.format("%s%s",FileUtil.getTmpDirPath(),"中文名字附件.pdf")));
		} catch (Exception e){
			e.printStackTrace();
			log.error(String.format("发送邮件失败,%s",e.getMessage()));
		} finally {
			if (inputStream != null){
				inputStream.close();
			}
		}
	}

	/**
	 * @Description:PDF转HTML
	 * @author HeShengjin 2356899074@qq.com
	 * @date 2024-4-25 10:11
	 */
	@Test
	public void t2() throws IOException{
		InputStream inputStream = null;
		try {
			// 加载PDF文档URL
			URL url = new URL("https://jixujiaoyu-test.oss-cn-shenzhen.aliyuncs.com/upload/20240425/1954fae396aa5aa1eb3dbad8edc19547.pdf");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			inputStream = conn.getInputStream();

			// 获取字节数组
			byte[] bytes = readInputStream(inputStream);

			//加载PDF文档
			PdfDocument pdf = new PdfDocument();
			pdf.loadFromBytes(bytes);

			//设置useEmbeddedSvg和 useEmbeddedImg布尔值为true
			pdf.getConvertOptions().setPdfToHtmlOptions(true,true);

			//保存到流
			File outFile = new File("PDFtoHTML.html");
			OutputStream outputStream = new FileOutputStream(outFile);
			pdf.saveToStream(outputStream, FileFormat.HTML);
			pdf.close();

			System.out.println("PDF转换成HTML完成!");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null){
				inputStream.close();
			}
		}
	}
	/**
	 * @Description:PDF转图片base64
	 * @author HeShengjin 2356899074@qq.com
	 * @date 2024-4-25 10:12
	 */
	@Test
	public void t3() throws IOException{
		InputStream inputStream = null;
		ByteArrayOutputStream byteArrayOutputStream = null;
		try {
			// 加载PDF文档URL
			URL url = new URL("https://jixujiaoyu-test.oss-cn-shenzhen.aliyuncs.com/upload/20240425/1954fae396aa5aa1eb3dbad8edc19547.pdf");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			inputStream = conn.getInputStream();

//			// 获取字节数组
			byte[] bytesPdf = readInputStream(inputStream);
			List<BufferedImage> bufferedImages = pdfToImage(bytesPdf);

			byteArrayOutputStream = new  ByteArrayOutputStream();
			ImageIO.write(bufferedImages.get(0),"jpg",byteArrayOutputStream);//只要PDF第一页的一张图片
			// 清流
			byteArrayOutputStream.flush();
			// 转为byte[]
			byte[] byteImage = byteArrayOutputStream.toByteArray();

			// 将图片数据转换为Base64字符串
			String base64String = Base64.getEncoder().encodeToString(byteImage);
			String html = String.format("<img src=\"data:image/jpg;base64,%s\" />",base64String);
//
			//保存到流
			File outFile = new File("PDFtoIMGBase64.html");
			FileUtils.writeByteArrayToFile(outFile,html.getBytes(StandardCharsets.UTF_8));

			System.out.println("PDF转换成HTML完成!");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null){
				inputStream.close();
			}
			if (byteArrayOutputStream != null){
				// 关流
				byteArrayOutputStream.close();
			}
		}
	}

	/**
	 *
	 * @Description: (InputStream转字节数组)
	 * @author hsj
	 * @date 2019年8月8日
	 */
	public byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}

	/**
	 * PDF转图片 (一个PDF很多页,所以很多图片)
	 * @param bytes:文件输入流
	 * @return
	 */
	public List<BufferedImage> pdfToImage(byte[] bytes){
		List<BufferedImage> images = new ArrayList<>();
		PDDocument document = null;
		try {
			// 加载PDF文档
			document = PDDocument.load(bytes);
			// 创建PDFRenderer对象
			PDFRenderer renderer = new PDFRenderer(document);

			for (int i = 0; i < document.getNumberOfPages(); i++) {
				/**
				 * 《 72 》 此处设置得越大像素越高,生成得时候也会越久
				 * DPI 的设置一般根据具体的需求和使用场景来决定。DPI 越高,生成的图片分辨率越大,图像质量也越高,
				 * 但同时文件大小也会变得更大。通常情况下,如果需要对生成的图片进行放大、裁剪等操作,建议将 DPI 设置得较高,
				 * 以保证图像质量和细节的清晰度;如果只是需要简单地浏览或共享图片,可以适当降低 DPI 以减小文件大小。在实际开发中,
				 * 可以根据不同的应用场景进行调整。一般来说,72 DPI 是一个比较常见的默认值,可以作为参考。
				 */
				BufferedImage image = renderer.renderImageWithDPI(i, 72, ImageType.RGB);
				images.add(image);
			}
			return images;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			// 关闭文档
			try {
				if (document != null) {
					document.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


}
相关推荐
郏国上8 小时前
由于图片视频替换和删除导致阿里云上存在大量系统不再使用的文件如何处理
数据库·mongodb·阿里云
专注VB编程开发20年8 小时前
阿里云域名DNS解析URL转发不支持HTTPS?
阿里云·域名·dns·ddns·url转发
Lucifer三思而后行9 小时前
使用 BR 备份 TiDB 到阿里云 OSS 存储
阿里云·云计算·tidb
wsad05329 小时前
Ubuntu 24.04 更换国内软件源(以阿里云为例)
linux·ubuntu·阿里云
郏国上11 小时前
遍历访问阿里云节点下的所有文件信息并写入excel文件
数据库·mongodb·阿里云·excel
IFLY51321 小时前
使用arduino用 esp32 连接阿里云遇到的坑
阿里云·云计算
程序员小赵同学1 天前
Spring AI Alibaba文生图实战:从零开始编写AI图片生成Demo
阿里云·ai·springboot·springai
zz-zjx1 天前
云计算产品-介绍--计算篇
阿里云·云计算