使用spring发送邮件,主要还是在实现org.springframework.mail.javamail.JavaMailSender这个接口,在借助于IoC的情况下我们可以通过配置来实现.
1 <bean id="mailsender"
2 class="org.springframework.mail.javamail.JavaMailSenderImpl">
3 <property name="host">
4 <value>smtp.gmail.com</value>
5 </property>
6 <property name="javaMailProperties">
7 <props>
8 <prop key="mail.smtp.auth">true</prop>
9 <prop key="mail.smtp.timeout">25000</prop>
10 <prop key="mail.smtp.starttls.enable">true</prop>
11 <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory </prop>
12 <prop key="mail.smtp.socketFactory.fallback">false</prop>
13 </props>
14 </property>
15 <property name="port">
16 <value>465</value>
17 </property>
18 <property name="username">
19 <value>username@gmail.com</value>
20 </property>
21 <property name="password">
22 <value>password</value>
23 </property>
24 </bean>
我们创建一个mail的服务,上面配置用户名处和密码根据需要修改,主要关键是因为gmail必须要SSL认证,所以在10到12行写了SSL的配置,由于只是简单应用我就不需要写接口什么的了
package kafei.time;
public class MailService {
private JavaMailSender mailSender;
public FeedbackService() {}
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void send() {
//创建一个多媒体的邮件
MimeMessage me=mailSender.createMimeMessage();
MimeMessageHelper message=new MimeMessageHelper(me,true);
message.setTo("user@gmail.com");
message.setSubject("test");
message.setText("这是一个测试");
FileSystemResource img=new FileSystemResource(
new File("E:\\workspace\\founder\\src\\kafeitime.jpg"));
message.addInline("png", img);
//message.addAttachment("png",img); //将文件作为附件发送
mailsender.send(me);
System.out.println("邮件发送成功");
}
}
这样就可以了
下面在bean的配置文件中再写入
<bean id="mailService"
class="kafei.time.MailService">
<property name="mailSender">
<ref bean="mailSender" />
</property>
</bean>
最后就是做一个测试文件了
public class MailTest {
public static void main(String[] args) {
Resource rs =
new FileSystemResource("beans-config.xml");
BeanFactory factory =
new XmlBeanFactory(rs);
kafei.time.MailService mailservice =
(HelloBean) factory.getBean("mailService");
mailservice.send();
}
}
这个例子我测试成功过,不过有可能在写的时候导致一些错误,请有疑问的朋友留言