对于可回调Message的实现,需要子类化MimeMessagePreparator(可匿名)并new一个该子类实例,在子类化实现prepare时完成Message的重构。
配置发送mail的bean。
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host">
<value>192.168.1.1</value><!--smtp server ip/name-->
</property>
<property name="username">
<value>user</value> <!--authenicated user name-->
</property>
<property name="password">
<value>password</value><!--authenicated user password-->
</property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">false</prop><!--authenication needed?-->
<prop key="mail.smtp.timeout">25000</prop>
<prop key="mail.smtp.sendpartial">true</prop>
</props>
</property>
</bean>
发送端代码大概可以如下(假设你的类有属性引用到bean mailSender:需要注意的是setText第二个参数true表示支持HTML在body内。
MimeMessagePreparator preparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage)
throws Exception {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage,
true, "UTF-8");
message.setTo(to);
message.setFrom(from);
message.setSubject(subject);
message.setText(textStr, true);
}
};
mailSender.send(preparator);
本文转自 dannyy1026 51CTO博客,原文链接:http://blog.51cto.com/dannyyuan/272639