Spring整合javamail 用gmail发送邮件
时间:2010-12-19 BlogJava 郑成桥
Spring整合javamail成功之后,把大量的代码配置到spring的配置文件里了 ,从而降低了Javamail对邮箱、端口、协议、主题、内容…… 的耦合。在客户端上只需要调用一行代码就可以发送邮件了。
首先不需要往项目的lib里导入jar,但是需要在tomcat的lib里导入3个jar文 件activation.jar ,jspsmartupload.jar,mail.jar 导入这3个jar文件,这样 tomcat就不会报错了。
SendManagerService .java
package com.cgt.itspiderman.service.email;
public interface SendManagerService {
public void sendMail(String email);
}
定义一个发送邮件的接口.
SendManagerServiceImp.java
package com.cgt.itspiderman.service.email;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
public class SendManagerServiceImp implements SendManagerService {
private JavaMailSender mailSender;
private SimpleMailMessage message;
public void sendMail(final String email) {
// TODO Auto-generated method stub
MimeMessagePreparator preparator = new MimeMessagePreparator()
{
public void prepare(MimeMessage mimeMessage) throws Exception {
mimeMessage.setRecipient (Message.RecipientType.TO, new InternetAddress(email));
mimeMessage.setFrom(new InternetAddress(message.getFrom()));
mimeMessage.setSubject (message.getSubject(),"gbk");
mimeMessage.setText(message.getText (),"gbk");
}
};
mailSender.send(preparator);
}
public JavaMailSender getMailSender() {
return mailSender;
}
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public SimpleMailMessage getMessage() {
return message;
}
public void setMessage(SimpleMailMessage message) {
this.message = message;
}
}
Spring整合javamail 用gmail发送邮件(2)
时间:2010-12-19 BlogJava 郑成桥
发送邮件的实现类.
然后在WEB-INF下面创建一个文件messages.properties,以后修改配置信息 直接在这里修改就可以了。
host=smtp.gmail.com
username=zhengchengqiaobusiness@gmail.com
password=xxxxxx
port=465
mail.smtp.auth=true
mail.smtp.timeout=25000
mail.smtp.starttls.enable=true
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.socketFactory.fallback=false
from=zhengchengqiaobusiness@gmail.com
subject=\u6807\u9898
text=\u5185\u5BB9\u554A
applicationContext.xml
.......................
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderCon figure
|