发送带有Spring Boot邮件的HTML表格

huangapple go评论64阅读模式
英文:

Send html table with Spring Boot Mail

问题

我想创建一个服务,用于向收件人发送电子邮件消息。这个消息应该呈现为一个表格,该表格是从实体字段中填充的。我正在使用Spring Boot Mail。

用StringBuilder解决了这个任务。

简单的MailSender配置:

@Bean
public JavaMailSender getJavaMailSender() {
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setHost("smtp.gmail.com");
    mailSender.setPort(587);
    
    mailSender.setUsername("my.gmail@gmail.com");
    mailSender.setPassword("password");
    
    Properties props = mailSender.getJavaMailProperties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.debug", "true");
    
    return mailSender;
}

实体:

@Entity
...
public class Mark {

    @Column(name = "account_login")
    private String accountLogin;

    @Id
    @Column(name = "account_view_id")
    private String accountViewId;

    @Column(name = "mark_text")
    private String text;

    @Column(name = "report_date")
    private LocalDate reportDate;
    //tostring, getters, setters, constructors
}

一个服务中用于发送电子邮件的方法:

public void send(String subject, String htmlMsg, String sendTo)  {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, false, "utf-8");
            message.setContent(htmlMsg, "text/html");
            helper.setTo(sendTo);
            helper.setSubject(subject);
            mailSender.send(message);
        } catch (MessagingException e) {
            log.error(e.toString());
        }
    }

生成HTML表格的服务:

@Service
public class TableGenerationService {

    @Autowired
    private Mark markRepository;

    public String generateReportMessage(List<Mark> marks) {
        StringBuilder stringBuilder = generateCommonHtmlHead();

        for (Mark mark : marks) {

            stringBuilder.append("<tr>");
            stringBuilder.append("<td>").append(mark.getAccountLogin()).append("</td>");
            stringBuilder.append("<td>").append(mark.getText()).append("</td>");
            stringBuilder.append("<td>").append(mark.getId()).append("</td>");
            stringBuilder.append("<td>").append(mark.getReportDate()).append("</td>");
            stringBuilder.append("</tr>");
        }
        generateCommonFooter(stringBuilder);
        return stringBuilder.toString();
    }

    private StringBuilder generateCommonHtmlHead() {
        StringBuilder stringBuilder = new StringBuilder();

        return stringBuilder.append("<head>")
                .append("<h1>Status<h1>")
                .append("</head>")
                .append("<body>")
                .append("<table border=1>")
                .append("<tr>")
                .append("<th>Author id</th><th>Authour Name</th><th>Content</th><th>Date</th>")
                .append("</tr>");
    }

    private void generateCommonFooter(StringBuilder stringBuilder) {
        stringBuilder.append("</table></body>");
    }

    public String generateReportMessage() {
        List<Mark> all = markRepository.findAll();
        return generateReportMessage(all);
    }
}

我测试了这个方法,它工作得相当好。但我认为对于这个任务来说,StringBuilder可能不是一个好主意。
是否有其他工具可以用于生成HTML表格?我应该使用Thymeleaf/Freemarker吗?如果我想要向表格添加CSS,该怎么办?StringBuilder的解决方案可能难以阅读。如果没有其他工具可用,我该如何改进使用StringBuilder的解决方案?

英文:

I want to create service that will send email messages to recipients. This message should be presented as a table which is filled from entity fields. I'm using Spring Boot Mail.

Solved this task with StringBuilder.

Simple MailSender configuration:

@Bean
public JavaMailSender getJavaMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(&quot;smtp.gmail.com&quot;);
mailSender.setPort(587);
mailSender.setUsername(&quot;my.gmail@gmail.com&quot;);
mailSender.setPassword(&quot;password&quot;);
Properties props = mailSender.getJavaMailProperties();
props.put(&quot;mail.transport.protocol&quot;, &quot;smtp&quot;);
props.put(&quot;mail.smtp.auth&quot;, &quot;true&quot;);
props.put(&quot;mail.smtp.starttls.enable&quot;, &quot;true&quot;);
props.put(&quot;mail.debug&quot;, &quot;true&quot;);
return mailSender;
}

Entity:

@Entity
...
public class Mark {
@Column(name = &quot;account_login&quot;)
private String accountLogin;
@Id
@Column(name = &quot;account_view_id&quot;)
private String accountViewId;
@Column(name = &quot;mark_text&quot;)
private String text;
@Column(name = &quot;report_date&quot;)
private LocalDate reportDate;
//tostring, getters, setters, constructors
}

Method in one of the service to send email:

public void send(String subject, String htmlMsg, String sendTo)  {
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, false, &quot;utf-8&quot;);
message.setContent(htmlMsg, &quot;text/html&quot;);
helper.setTo(sendTo);
helper.setSubject(subject);
mailSender.send(message);
} catch (MessagingException e) {
log.error(e.toString());
}
}

Service which generates html table:

@Service
public class TableGenerationService {
@Autowired
private Mark markRepository;
public String generateReportMessage(List&lt;Mark&gt; marks) {
StringBuilder stringBuilder = generateCommonHtmlHead();
for (Mark mark : marks) {
stringBuilder.append(&quot;&lt;tr&gt;&quot;);
stringBuilder.append(&quot;&lt;td&gt;&quot;).append(mark.getAccountLogin()).append(&quot;&lt;/td&gt;&quot;);
stringBuilder.append(&quot;&lt;td&gt;&quot;).append(mark.getText()).append(&quot;&lt;/td&gt;&quot;);
stringBuilder.append(&quot;&lt;td&gt;&quot;).append(mark.getId()).append(&quot;&lt;/td&gt;&quot;);
stringBuilder.append(&quot;&lt;td&gt;&quot;).append(message.getReportDate()).append(&quot;&lt;/td&gt;&quot;);
stringBuilder.append(&quot;&lt;/tr&gt;&quot;);
}
generateCommonFooter(stringBuilder);
return stringBuilder.toString();
}
private StringBuilder generateCommonHtmlHead() {
StringBuilder stringBuilder = new StringBuilder();
return stringBuilder.append(&quot;&lt;head&gt;&quot;)
.append(&quot;&lt;h1&gt;Status&lt;h1&gt;&quot;)
.append(&quot;&lt;/head&gt;&quot;)
.append(&quot;&lt;body&gt;&quot;)
.append(&quot;&lt;table border=1&gt;&quot;)
.append(&quot;&lt;tr&gt;&quot;)
.append(&quot;&lt;th&gt;Author id&lt;/th&gt;&lt;th&gt;Authour Name&lt;/th&gt;&lt;th&gt;Content&lt;/th&gt;&lt;th&gt;Date&lt;/th&gt;&quot;)
.append(&quot;&lt;/tr&gt;&quot;);
}
private void generateCommonFooter(StringBuilder stringBuilder) {
stringBuilder.append(&quot;&lt;/table&gt;&lt;/body&gt;&quot;);
}
public String generateReportMessage() {
List&lt;Mark&gt; all = markRepository.findAll();
return generateReportMessage(all);
}
}

I tested this and it works kinda good. But I think StringBuilder is not good idea for this task.
Are there other tools for generating html tables? Should i use thymeleaf/freemarker? What if i want to add css to table? This solution with StringBuilder will be hard to read. Or if no other tools are available, how can I improve the solution with StringBuilder?

答案1

得分: 1

我通常使用 Apache FreeMarker 来处理这类任务,以下是你也应该使用模板引擎的原因:

  • 你已经意识到如果添加额外的内容,比如 CSS 样式,阅读起来会很困难;
  • 你的内容呈现与逻辑耦合,需要手动构建,遍历数据等等。FreeMarker(或其他模板引擎)可以为你完成这些操作;
  • 更新 模板 和升级 数据模型 要比每次修改代码更容易;
  • 你将需要一个基本的 配置 和实现,以便使用模板和数据模型创建内容,这样你就可以重复使用,而不是重复编写构建各种具体内容的代码。

这里有一个很好的入门示例(还有表格的示例):https://www.dariawan.com/tutorials/spring/spring-boot-freemarker-crud-example/

英文:

I generally use Apache FreeMarker for such tasks, and here’s why you should use the template engine too:

  • You already realized that it would be hard to read if you add additional content such as CSS styles;
  • Your content presentation is coupled with the logic, you build it manually, looping through data etc. – FreeMarker (or another template engine) does that for you;
  • It is way easier to update the template and upgrade the data model than to modify the code every time;
  • You will need a basic configuration and implementation for creating the content with templates and data models that you can reuse instead of duplicating or adding the code for building various specifics manually.

Here is a pretty good example to get started (has an example for tables too): https://www.dariawan.com/tutorials/spring/spring-boot-freemarker-crud-example/

huangapple
  • 本文由 发表于 2020年10月6日 23:38:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/64229183.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定