依赖的jar包
Spring Mail API在org.springframework.mail及其子包中封装,只提供了邮件发送的封装。
spring-context-support.jar
javax.mail.jar
Spring的配置applicationContext.xml
<!--java发送邮件-->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="username" value="cheng@mail.com"/>
<property name="password" value="123"/>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.host">mail.com</prop>
</props>
</property>
</bean>
JUnit测试类
//Spring注入
private JavaMailSenderImpl mailSender;
@Resource
public void setMailSender(JavaMailSenderImpl mailSender) {
this.mailSender = mailSender;
}
@Test
public void fun() {
// 建立邮件消息
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom("cheng@mail.com");
mailMessage.setTo("xiao@mail.com");
mailMessage.setSubject("你好");
mailMessage.setText("来自Spring");
mailSender.send(mailMessage);
}