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.xuhuhu.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

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
	<property name="host" value="smtp.gmail.com" />
	<property name="port" value="587" />
	<property name="username" value="xuhuhu.com@gmail.com" />
	<property name="password" value="password" />

	<property name="javaMailProperties">
	   <props>
       	      <prop key="mail.smtp.auth">true</prop>
       	      <prop key="mail.smtp.starttls.enable">true</prop>
       	   </props>
	</property>
</bean>

<bean id="mailMail" class="com.xuhuhu.common.MailMail">
	<property name="mailSender" ref="mailSender" />
</bean>

</beans>

運行它

package com.xuhuhu.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("from@no-spam.com",
    		   "to@no-spam.com",
    		   "Testing123",
    		   "Testing only \n\n Hello Spring Email Sender");

    }
}

下載源代碼 –  http://pan.baidu.com/s/1gepbWEf

上一篇: Spring AOP在Hibernate事務管理 下一篇: Spring在bean配置檔中定義電子郵件範本