在上一篇 ,硬编码的所有电子邮件属性和消息的方法体中的内容,这是不实际的,应予以避免。应该考虑在Spring bean 配置文件中定义电子邮件模板。
1.Spring的邮件发件人
Java类使用 Spring的MailSender接口发送电子邮件,并使用 String.Format 传递变量bean配置文件替换电子邮件中的 '%s'。
File : MailMail.java
package com.yiibai.common;import org.springframework.mail.MailSender;import org.springframework.mail.SimpleMailMessage;public class MailMail{ private MailSender mailSender; private SimpleMailMessage simpleMailMessage; public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) { this.simpleMailMessage = simpleMailMessage; } public void setMailSender(MailSender mailSender) { this.mailSender = mailSender; } public void sendMail(String dear, String content) { SimpleMailMessage message = new SimpleMailMessage(simpleMailMessage); message.setText(String.format( simpleMailMessage.getText(), dear, content)); mailSender.send(message); } }
2. Bean的配置文件
定义电子邮件模板“customeMailMessage' 和邮件发件人信息的bean配置文件。
File : Spring-Mail.xml
true true
4. 运行它
package com.yiibai.common;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class App { public static void main( String[] args ) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); MailMail mm = (MailMail) context.getBean("mailMail"); mm.sendMail("Yiibai", "This is text content"); }}
输出
Dear Yiibai, Mail Content : This is text content
代码下载 –