今天来试着用SpringMVC发送邮件,主要需要依赖以下两个包;
org.springframework
spring-context-support
${spring.version}
javax.mail
mail
1.4.5
spring-mail.xml配置文件如下:
${email.auth}
${email.timout}
${email.default.text}
这里加载了发送邮件相关的配置文件email.properties:
email.protocol=smtp email.host=smtp.163.com email.port=25 email.username=132312312@163.com email.password=yourpassword email.default.to=123121@126.com email.default.subject=Hello email.default.text=how are you email.auth=true email.timout=25000
发送简单邮件代码:
public class EmailServiceImpl implements EmailService {
private static final Logger LOGGER = LoggerFactory.getLogger(EmailServiceImpl.class);
private JavaMailSender javaMailSender;
private SimpleMailMessage simpleMailMessage;
@Override
public void sendMailSimple(String to, String subject, String content) throws Exception {
try {
//用于接收邮件的邮箱
simpleMailMessage.setTo(to);
//邮件的主题
simpleMailMessage.setSubject(subject);
//邮件的正文,第二个boolean类型的参数代表html格式
simpleMailMessage.setText(content);
LOGGER.info("---------------------------{}", simpleMailMessage);
//发送
javaMailSender.send(simpleMailMessage);
} catch (Exception e) {
throw new MessagingException("failed to send mail!", e);
}
}
public void setJavaMailSender(JavaMailSender javaMailSender) {
this.javaMailSender = javaMailSender;
}
public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
this.simpleMailMessage = simpleMailMessage;
}
}
跑单元测试的时候报:Could not resolve placeholder异常,不可以解析email.protocol
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'javaMailSender' defined in class path resource [config/spring-mail.xml]: Could not resolve placeholder 'email.protocol' in value "${email.protocol}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'email.protocol' in value "${email.protocol}"
可能的原因:
1、location中的属性文件配置错误;
2、location中定义的配置文件里面没有对应的placeholder值;
3、Spring容器的配置问题,很有可能是使用了多个PropertyPlaceholderConfigurer或者多个context:property-placeholder的原因。
排查以后发现,
applicationContext.xml和spring-mail.xml两个文件都使用了context:property-placeholder,前者加载数据库连接配置,后者加载发送邮件相关配置。
这个是Spring容器采用反射扫描的发现机制决定的,在Spring 3.0中,可以加ignore-unresolvable="true"解决。
注意:必须两个都要加,加一个也不行。
在Spring 2.5中,context:property-placeholder没有ignore-unresolvable属性,此时可以改用PropertyPlaceholderConfigurer。其实
修改以后,测试用类运行成功:
发送邮件成功:
其实发送邮件还可以用JavaMail实现,需要依赖两个包:
activation-1.1.jar
mail-1.4.2.jar



