SpringBoot-实现邮件发送功能(邮件正文带表格)

描述:实现一个正文带表格的邮件发送功能,基于freemarker
技术:springboot+freemarker+邮件

1.实现效果

fE8DRR8iSz.jpg

2.程序实现

2.1项目结构

图片.png

2.2配置类

图片.png

2.3模板

<!DOCTYPE html>
<html>
<head><meta http-equiv=Content-Type content="text/html; charset=utf-8"/></head>
    <table style=font-size:12px border=1 cellspacing=0 width=100%  bordercolorlight=DarkGray bordercolordark=#efefef>
        <tr><th>序号</th><th>编号</th><th>名字</th><th>详情</th></tr>
        <#if faultOptimizationPlans1?? && (faultOptimizationPlans1?size>0)>
            <#list faultOptimizationPlans1 as item>
                <tr height=""18>
                    <td class="xl63">${(item.index)!}</td>
                    <td class="xl63">${(item.id)!}</td>
                    <td class="xl63">${(item.name)!}</td>
                    <td class="xl63">${(item.remark)!}</td>
                </tr>
            </#list>
        </#if>
    </table>
<br>
</html>

2.4邮件服务

2.4.1domain
public class Row {
    private String index;
    private String id;
    private String name;
    private String remark;
    public Row(String index, String id, String name, String remark) {
        this.index = index;
        this.id = id;
        this.name = name;
        this.remark = remark;
    }
    public String getIndex() {
        return index;
    }
    public String getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public String getRemark() {
        return remark;
    }
}
2.4.2dao
public interface IMailDAO {
    boolean sendTemplateMail(String title, String toUser, String templateName, Map<String, Object> params);
}
2.4.3service
public interface MailService {
    boolean sendTemplateMail(String title, String toUser, String templateName, Map<String, Object> params);
}
2.4.4impl
import cn.com.crv.event.service.service.MailService;
import freemarker.template.Configuration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Properties;
@Slf4j
@Service
public class MailServiceImpl implements MailService {
    @Autowired
    private JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String from;
    @Value("${spring.mail.host}")
    private String host;
    @Override
    public boolean sendTemplateMail(String title, String toUser, String templateName, Map<String, Object> params) {
        try {
            Properties prop = new Properties();
            prop.setProperty("mail.debug", "true");
            prop.setProperty("mail.host", host);
            prop.setProperty("mail.transport.protocol", "smtp");
            prop.setProperty("mail.smtp.auth", "true");
            Session session = Session.getInstance(prop);
            MimeMessage mimeMessage = new MimeMessage(session);
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, StandardCharsets.UTF_8.name());
            // 发件人
            helper.setFrom(from);
            //收件人
            helper.setTo(toUser);
            //邮件标题
            helper.setSubject(title);
            Configuration configuration = new Configuration();
          configuration.setClassForTemplateLoading(this.getClass(), "/templates");
            String text = FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate(templateName), params);
            //// text:内容,true:为HTML邮件(false则为普通文本邮件)
            helper.setText(text, true);
            mailSender.send(mimeMessage);
            log.info("邮件发送成功");
        } catch (Exception e) {
            log.error("sendTemplateMail 发送模板邮件错误,", e);
            throw new RuntimeException(e);
        }
        return true;
    }
}

2.5测试类

import cn.com.crv.event.service.domain.Row;
import cn.com.crv.event.service.service.MailService;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.*;
import java.util.*;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes={Application.class})
@Slf4j
public class EmailTest {
    @Autowired
    private MailService mailService;
    @Test
    public void sendTemplateMailTest() throws IOException, TemplateException {
        String subject = "这是一封测试邮件";
        List<Row> rows = new ArrayList<>();
        rows.add(new Row("1", "A1", "Name1", "Remark1"));
        rows.add(new Row("2", "A2", "Name2", "Remark2"));
        rows.add(new Row("3", "A3", "Name3", "Remark3"));
        Map<String,Object> mailContentMap = new HashMap<>();
        mailContentMap.put("faultOptimizationPlans1", rows);
        try {
            mailService.sendTemplateMail(subject, "接受收者的邮箱地址","normal.ftl", mailContentMap);
        } catch (Exception e) {
            log.error("邮件发送失败:{}", mailContentMap , e);
        }
    }

2.6相关依赖

   <!--spring email -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
        <!--    邮箱发送依赖-->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>${freemarker.version}</version>
        </dependency>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容