spring发邮件
先来看看发送Email吧,在Spring中发送Email是很简单的,使用Spring提高的MailSender和MailMessage就可以了,配置代码如下:
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEbeansPUBLIC"-//SPRING//DTDBEAN//EN""spring-beans.dtd">
<beans>
<beanid="mailSender"class="org.springframework.mail.javamail.JavaMailSenderImpl">
<propertyname="host">
<value>smtp.163.com</value>
</property>
<propertyname="javaMailProperties">
<props>
<!--如果要使用用户名和密码验证,这一步需要-->
<propkey="mail.smtp.auth">true</prop>
</props>
</property>
<propertyname="username">
<value>你的Email地址</value>
</property>
<propertyname="password">
<value>你的Email密码</value>
</property>
</bean>
<!--简单的message-->
<beanid="mailMessage"class="org.springframework.mail.SimpleMailMessage">
<propertyname="to">
<value>收件人地址</value>
</property>
<propertyname="from">
<value>你的地址</value>
</property>
<propertyname="subject"><!--Email标题-->
<value>ASpringMailsender</value>
</property>
</bean>
<!--测试发送的类-->
<beanid="testMailSender"class="test.mail.TestSenderMail">
<propertyname="mailMessage">
<refbean="mailMessage"/>
</property>
<propertyname="mailSender">
<refbean="mailSender"/>
</property>
</bean>
</beans>
上面的配置好以后就可以直接发送了,看看TestSenderMail.java的代码:
packagetest.mail;
importorg.springframework.mail.MailException;
importorg.springframework.mail.MailSender;
importorg.springframework.mail.SimpleMailMessage;
publicclassTestSenderMail{
privateMailSendermailSender;
privateSimpleMailMessagemailMessage;
publicTestSenderMail(){}
publicSimpleMailMessagegetMailMessage(){
returnmailMessage;}
publicvoidsetMailMessage(SimpleMailMessagemailMessage){
this.mailMessage=mailMessage;}
publicMailSendergetMailSender(){
returnmailSender;}
publicvoidsetMailSender(MailSendermailSender){
this.mailSender=mailSender;}
publicvoidsendMail(){
SimpleMailMessagemessage=newSimpleMailMessage(mailMessage);//设置email内容,
message.setText("测试Spring发送Email.");
try{
mailSender.send(message);
}catch(MailExceptione){
System.out.println("O.发送Email失败了....");
e.printStackTrace();
}
}
}
很简单吧.下面是测试类:TestApp.java
packagetest.mail;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
publicclassTestApp{
publicstaticvoidmain(String[]args){
ApplicationContextcontext=newClassPathXmlApplicationContext("test/mail/mail.xml");
TestSenderMailsender=(TestSenderMail)context.getBean("testMailSender");
sender.sendMail();
}
//抛出如下异常,是瑞星监控的问题,关闭就可以了
/***DEBUGSMTP:QUITfailedwith250O.发送Email失败了....
*org.springframework.mail.MailSendException:Couldnotsendmails:354
**com.sun.mail.smtp.SMTPSendFailedException:354**at*com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1388)*atcom.sun.mail.smtp.SMTPTransport.finishData(SMTPTransport.java:1215)at*com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:586)*/
}
呵呵,现在就可以发送Email了.
最后提醒一下,记得要将:activation.jar和mail.jar两个包导入到工程
文章來源:http://www.itbdqn.com/Html/ChangGui/Class5/Class284/284_5416.html