1.环境准备,所需jar包
2。在src目录下建立一个maisender.properties文件,里面写一些常用的配置
如果邮箱服务器采用QQ邮箱则下面书写
mail.host=smtp.qq.com
mail.username=XXXXXXXXXX@qq.com
mail.password=XXXXXXXX
如果126邮箱服务器
mail.host=smtp.126.com
mail.username=xxxxxxxx@qq.com
mail.password=xxxxxxxx
3.在src目录下建立一个applicationContext.xml文件,这个是使用spring框架的配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.*"></context:component-scan>
<mvc:annotation-driven/>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="fileEncoding" value="utf-8" />
<property name="locations">
<list>
<value>mailsender.properties</value>
</list>
</property>
</bean>
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host">
<value>${mail.host}</value>
</property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.timeout">25000</prop>
</props>
</property>
<property name="username">
<value>${mail.username}</value>
</property>
<property name="password">
<value>${mail.password}</value>
</property>
</bean>
</beans>
4.在src目录下新建java文件
package com.email;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
public class SpringSimpleEmail {
public static void main(String[] args) {
try {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
JavaMailSender sender = (JavaMailSender)ctx.getBean("javaMailSender");
MimeMessage msg = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(msg,true,"utf-8");
helper.setFrom("xxxxxxx@qq.com");
helper.setTo("xxxxxx@qq.com");
helper.setText("tets this is a spring mvc email");
helper.setSubject("xxxxxxx");
sender.send(msg);
System.out.println("email send ok");
} catch (MessagingException e) {
System.out.println("send fail");
e.printStackTrace();
}
}
}
5.点击运行便可收到邮件。。笔者亲自测试的。