发送html格式邮件很简单,下面给出个例子
先是一个抽象的基类
1 package com.educast.mail;
2
3 import org.springframework.mail.javamail.JavaMailSender;
4
5 /**
6 * @author mfc42d
7 *
8 */
9 public abstract class BaseMailSender {
10
11 protected String to;
12 protected String from;
13 protected String subject;
14 protected JavaMailSender sender;
15
16
17 public void setTo(String to) {
18 this.to = to;
19 }
20
21 public void setFrom(String from) {
22 this.from = from;
23 }
24
25 public void setSubject(String subject) {
26 this.subject = subject;
27 }
28
29 public void setJavaMailSender(JavaMailSender sender) {
30 this.sender = sender;
31 }
32 }
33
34 下面是具体的实现类
35 package com.educast.mail;
36
37
38 import javax.mail.MessagingException;
39 import javax.mail.internet.MimeMessage;
40
41 import org.springframework.context.ApplicationContext;
42 import org.springframework.context.support.FileSystemXmlApplicationContext;
43 import org.springframework.mail.javamail.MimeMessageHelper;
44
45 /**
46 * @author mfc42d
47 *
48 */
49 public class SimpleHtmlMailSender extends BaseMailSender {
50
51 public void sendMessage() throws MessagingException {
52 MimeMessage msg = sender.createMimeMessage();
53 MimeMessageHelper helper = new MimeMessageHelper(msg, true, "GB2312");
54
55 helper.setTo(to);
56 helper.setFrom(from);
57 helper.setSubject(subject);
58 helper.setText("<html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"></head><body><h1><a href='#'>郁闷!"
59 + "</a></h1></body></html>", true);
60
61 sender.send(msg);
62 }
63
64 public static void main(String[] args) throws Exception {
65 ApplicationContext ctx = new FileSystemXmlApplicationContext(
66 new String[] { "D:\\WORK\\JDBC\\mail\\src\\MailSender.xml" });
67
68 SimpleHtmlMailSender sender = (SimpleHtmlMailSender) ctx
69 .getBean("messageSender");
70 sender.sendMessage();
71 }
72 }
73
74
最后是spring配置文件
1 <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
2 <beans>
3 <bean id="sender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
4 <property name="host">
5 <value>mail.mymail.cn</value>
6 </property>
7 <property name="username">
8 <value>webmaster</value>
9 </property>
10 <property name="password">
11 <value>password</value>
12 </property>
13 <property name="javaMailProperties">
14 <props>
15 <prop key="mail.smtp.auth">true</prop>
16 </props>
17 </property>
18
19 </bean>
20
21 <bean id="messageSender" class="com.educast.mail.SimpleHtmlMailSender">
22 <property name="javaMailSender">
23 <ref bean="sender"/>
24 </property>
25 <property name="to">
26 <value>mfc42d@163.com</value>
27 </property>
28 <property name="from">
29 <value>webmaster@mymail.cn</value>
30 </property>
31 <property name="subject">
32 <value>test</value>
33 </property>
34 </bean>
35 </beans>
36 使用esmtp认证必须添加红色部分
37
posted on 2005-11-12 02:36
老妖 阅读(5479)
评论(1) 编辑 收藏 所属分类:
spring