Spring通過Gmail SMTP服務器MailSender發送電子郵件
Spring提供了一個有用的「org.springframework.mail.javamail.JavaMailSenderImpl」類,通過JavaMail API 簡化郵件發送過程。這裏有一個項目中使用Spring 「JavaMailSenderImpl」通過Gmail SMTP服務器發送電子郵件。
1. Spring郵件發件人
Java 類使用 Spring 的 MailSender 接口發送電子郵件。
File : MailMail.java
package com.yiibai.common;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
public class MailMail
{
private MailSender mailSender;
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
public void sendMail(String from, String to, String subject, String msg) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(msg);
mailSender.send(message);
}
}
2. bean配置文件
配置 mailSender bean 並指定Gmail的SMTP服務器電子郵件的詳細信息。
注
Gmail的配置細節(這裏是牆,該翻的翻) – http://mail.google.com/support/bin/answer.py?hl=en&answer=13287
File : Spring-Mail.xml
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
運行它
package com.yiibai.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App
{
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext("Spring-Mail.xml");
MailMail mm = (MailMail) context.getBean("mailMail");
mm.sendMail("[email protected]",
"[email protected]",
"Testing123",
"Testing only \\n\\n Hello Spring Email Sender");
}
}
下載源代碼 – http://pan.baidu.com/s/1gepbWEf