日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Spring在bean配置文件中定义电子邮件模板

發布時間:2024/9/20 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring在bean配置文件中定义电子邮件模板 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在上一篇Spring電子郵件教程,硬編碼的所有電子郵件屬性和消息的方法體中的內容,這是不實際的,應予以避免。應該考慮在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

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"><bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"><property name="host" value="smtp.gmail.com" /><property name="port" value="587" /><property name="username" value="username" /><property name="password" value="password" /><property name="javaMailProperties"><props><prop key="mail.smtp.auth">true</prop><prop key="mail.smtp.starttls.enable">true</prop></props></property> </bean><bean id="mailMail" class="com.yiibai.common.MailMail"><property name="mailSender" ref="mailSender" /><property name="simpleMailMessage" ref="customeMailMessage" /> </bean><bean id="customeMailMessage"class="org.springframework.mail.SimpleMailMessage"><property name="from" value="from@no-spam.com" /><property name="to" value="to@no-spam.com" /><property name="subject" value="Testing Subject" /><property name="text"><value><![CDATA[Dear %s,Mail Content : %s]]></value></property> </bean></beans>

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 代碼下載 –??http://pan.baidu.com/s/1c0UPsFA

總結

以上是生活随笔為你收集整理的Spring在bean配置文件中定义电子邮件模板的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。