Java springboot 发送邮箱,普通文字、HTML(普通拼接HTML、使用freemaker 生成HTML)、附件、图片

一、maven项目添加依赖

<!-- 发送邮件 spring-boot-starter-mail -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- freemarker 模板 -->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
</dependency>

二、接口编写

service 层

/**
 * @Description 发送邮件接口
 */
public interface MailService {

    /**
     * @Description 发送简单的文本文件,to:收件人 subject:主题 content:内容
     * @Param [to, subject, content]
     **/
    public void sendSimpleMail(String to, String subject, String content);

    /**
     * @Description 发送html,to:收件人 subject:主题 content:内容
     * @Param [to, subject, content]
     **/
    public void sendHtmlMail(String to, String subject, String content);

    /**
     * @Description 发送一个带附件的邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     * @param filePath 文件路径
     */
    public void sendAttachmentMail(String to, String subject, String content, String filePath);
    
    /**
     * @Description 发送一个图片带附件的邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     * @param rscPath 图片
     */
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath);
}

serviceImpl 

import java.io.File;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

/**
 */
@Service
public class MailServiceImpl implements MailService {

    // 发送人的用户名,邮箱地址
    @Value("${spring.mail.username}")
    private String from;

    /**
     * JavaMailSender 用来发送邮件
     * springboot application.properties 文件设置 spring.mail
     */
    @Autowired
    private JavaMailSender mailSender;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(from);
        mailMessage.setTo(to);
        mailMessage.setSubject(subject);
        mailMessage.setText(content);
        mailSender.send(mailMessage);
    }

    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(message);

            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            //将content里面的标签进行处理,否则为正常的文本处理
            messageHelper.setText(content, true);
        } catch (MessagingException e) {
            logger.error("something wrong...");
            e.printStackTrace();
        }
        mailSender.send(message);

    }

    @Override
    public void sendAttachmentMail(String to, String subject, String content, String filePath) {

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            // 带上附件,参数传true,否则会报错.
            // Not in multipart mode - create an appropriate MimeMessageHelper via a constructor that takes a 'multipart' flag if you need to set alternative texts or add inline elements or attachments.
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            messageHelper.setFrom(from);

            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            messageHelper.setText(content);
            
            //设置附件
            FileSystemResource fileSystemResource = new FileSystemResource(new File(filePath));
            String filename = fileSystemResource.getFilename();
            messageHelper.addAttachment(filename, fileSystemResource);
        } catch (MessagingException e) {
            logger.error("something wrong...");
            e.printStackTrace();
        } finally {
		}
        mailSender.send(mimeMessage);
    }

    @Override
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath) {

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            //带上附件,参数传true,否则会报错.
            //Not in multipart mode - create an appropriate MimeMessageHelper via a constructor that takes a 'multipart' flag if you need to set alternative texts or add inline elements or attachments.
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            messageHelper.setText(content,true);
            //构造邮件内部的图片
            FileSystemResource file = new FileSystemResource(new File(rscPath));
            //对应的图片src路径
            messageHelper.addInline("img", file);
        } catch (MessagingException e) {
            logger.error("something wrong...");
            e.printStackTrace();
        }
        mailSender.send(mimeMessage);
    }
}

三、application.propertis 文件配置

springboot 使用邮箱的方式
# QQ/163邮箱
#smtp.163.com smtp.qq.com
#spring.mail.host=smtp.qq.com
#spring.mail.username=账号
#spring.mail.password=授权码
#spring.mail.properties.mail.smtp.auth=true
#spring.mail.properties.mail.smtp.starttls.enable=true
#spring.mail.properties.mail.smtp.starttls.required=true
#spring.mail.default-encoding=UTF-8

# 腾讯企业邮箱
spring.mail.host=smtp.exmail.qq.com
spring.mail.username=账号
spring.mail.password=密码
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback=false
#腾讯企业邮箱 端口的写法有些区别
spring.mail.properties.mail.smtp.socketFactory.port=465

QQ授权码获取: POP3/SMTP服务 开启后会得到授权码

163 (网易)开启授权码

XML 配置 FreeMarkerConfigurer / 也可直接创建对象(读取ftl文佳,生成HTML)

<!-- 配置freeMarkerConfigurer进行属性值的注入 -->  
<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">  
    <property name="templateLoaderPaths" value="classpath:templates" />  
    <property name="freemarkerSettings">  
        <props>  
             <prop key="template_update_delay">1800</prop>模板更新延时  
             <prop key="default_encoding">UTF-8</prop>  
             <prop key="locale">zh_CN</prop>  
        </props>  
    </property>
</bean>

mail.ftl freeMaker模板编写

<html>
    <head>
        <meta http-equiv="content-type" content="text/html;charset=utf8">
    </head>
    <body>
        用户名为:<font color='green' size='16'>${name}</font></br>
        <font color='blue' size='16'>${id}</font>
    </body>
</html>

四、springboot 测试

package com.monitor.application;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.monitor.email.MailService;

/**
 * springboot 邮箱测试类
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailSendTest {

    @Autowired
    private MailService mailService;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    
    private String to = "123456@qq.com";

    //主题
    String subject = "主题内容";

    @Test
    public void test01() {
        String content = "一个简单的文本发送";

        mailService.sendSimpleMail(to,subject,content);
    }

    @Test
    public void test02() {
        String content = "<html> <h1 style=\"color:red \" >一个简单的html发送</h1></html>";

        mailService.sendHtmlMail(to,subject,content);
    }

    @Test
    // XML配置:发送html文件,通过freemarker模板构造
    public void getFreemarkerByXml() throws IOException, TemplateException {
    	Template template =  freeMarkerConfigurer.getConfiguration().getTemplate("mail.ftl");
	    
	    // FreeMarker通过Map传递动态数据
	    Map<String,Object> map = new HashMap<String,Object>();
	    // 注意动态数据的key和模板标签中指定的属性相匹配
	    map.put("name","freeMarker 姓名");
	    map.put("id","ID:456125");
	    
	    // 解析模板并替换动态数据,最终content将替换模板文件中的${content}标签。
	    String htmlTxt = FreeMarkerTemplateUtils.processTemplateIntoString(template,map);
	    
	    mailService.sendHtmlMail(to, subject , htmlTxt);
    }

    @Test
    // 创建对象:通过freemarker模板构造邮件内容
    public void getFreemarkerByObject() throws IOException, TemplateException {
        
	    // 通过指定模板名获取FreeMarker模板实例
        
        FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
		
		Properties settings = new Properties();
		settings.setProperty("locale", "zh_CN");
		settings.setProperty("default_encoding", "UTF-8");
		freeMarkerConfigurer.setFreemarkerSettings(settings);
		
		String path = System.getProperty("user.dir");  // 获取项目根目录
		FileTemplateLoader ftl1 = new FileTemplateLoader(new File(path + "\\src\\main\\resources\\templates"));  // 拼接上自己对应的模板位置
		ClassTemplateLoader ctl = new ClassTemplateLoader(getClass(), "");
		TemplateLoader[] loaders = new TemplateLoader[] { ftl1, ctl };  // 可配置多个路径, ftl2,ftl3 ,添加在{} 里面即可.
		MultiTemplateLoader mtl = new MultiTemplateLoader(loaders);
		
		Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);  // 根据自己引入的版本设置
		configuration.setTemplateLoader(mtl);
		
		freeMarkerConfigurer.setConfiguration(configuration);
		
		
	    Template template =  freeMarkerConfigurer.getConfiguration().getTemplate("mail.ftl");
	    
	    // FreeMarker通过Map传递动态数据
	    Map<String,Object> map = new HashMap<String,Object>();
	    // 注意动态数据的key和模板标签中指定的属性相匹配
	    map.put("name","freeMarker 姓名");
	    map.put("id","ID456125");
	    
	    // 解析模板并替换动态数据,最终content将替换模板文件中的${content}标签。
	    String htmlTxt = FreeMarkerTemplateUtils.processTemplateIntoString(template,map);
	    
	    mailService.sendHtmlMail(to, subject , htmlTxt);
    }

    @Test
    public void test04() {
        String content = "一个简单的带附件发送";

        String filePath = "C:\\Users\\DELL\\Desktop\\Test.docx";
        mailService.sendAttachmentMail(to,subject,content,filePath);
    }

    @Test
    //发送图片
    public void test05() {
        //src对应img
        String content = "<html><body>一个简单的图片发送:<img src=\'cid:img" + "\'></img></body></html>";
        //图片地址
        String filePath = "D:\\head.png";
        mailService.sendInlineResourceMail(to,subject,content,filePath);
    }
}

五、验证邮箱是否真实有效

大佬文章:Java与邮件系统交互之使用Socket验证邮箱是否存在(非正则表达式)

 

其它实现大佬:Spring结合freemaker配置发送邮件, XML 文件配置

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用itextpdf和freemarker来实现Java中的HTML转PDF功能。首先,确保你的项目已经引入了相关的依赖,包括spring-boot-starter-freemarker、itextpdf、xmlworker和itext-asian。 接下来,你可以创建一个HtmlConvertPdfHelper类来实现HTML转PDF的功能。在这个类中,你可以使用freemarker来生成HTML内容,并使用itextpdf将HTML内容转换为PDF文件。可以参考以下代码: ```java import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.PdfWriter; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import java.io.*; import java.util.Map; public class HtmlConvertPdfHelper { public byte[] htmlConvertPDF(String templateName, Map<String, String> data) throws IOException, TemplateException, DocumentException { // 加载freemarker配置 Configuration configuration = new Configuration(Configuration.VERSION_2_3_23); configuration.setClassForTemplateLoading(getClass(), "/"); // 获取freemarker模板 Template template = configuration.getTemplate(templateName); // 使用StringWriter来保存生成HTML内容 StringWriter writer = new StringWriter(); template.process(data, writer); // 使用itextpdf将HTML内容转换为PDF Document document = new Document(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); document.open(); InputStream is = new ByteArrayInputStream(writer.toString().getBytes()); com.itextpdf.tool.xml.XMLWorkerHelper.getInstance().parseXHtml(PdfWriter.getInstance(document, baos), document, is); document.close(); // 返回转换后的PDF文件内容 return baos.toByteArray(); } } ``` 接下来,你可以在测试类中调用HtmlConvertPdfHelper类来完成HTML转PDF的操作。首先,创建一个Map对象来存储模板中的变量值,然后调用htmlConvertPDF方法将HTML内容转换为PDF,并将转换后的PDF内容保存到文件中。 ```java import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class Test { private static final Logger LOGGER = LoggerFactory.getLogger(Test.class); @Test public void aaa() throws IOException, TemplateException, com.itextpdf.text.DocumentException { Map<String, String> data = new HashMap<>(); data.put("name", "鹤顶红"); data.put("type", "毒药"); byte[] bytes = new HtmlConvertPdfHelper().htmlConvertPDF("demo.ftl", data); OutputStream os = new FileOutputStream("G:/text.pdf"); os.write(bytes, 0, bytes.length); os.flush(); os.close(); LOGGER.info("转换完成"); } } ``` 通过以上代码,你可以实现Java中的HTML转PDF功能。你需要按照你的实际情况进行适当的修改,如模板名称、变量值等。请确保模板文件存在,并且与HtmlConvertPdfHelper类处于相同的目录下。 希望这个回答能帮到你。如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值