使用SpringMail发现邮件
package com.rocky.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; public class SendMail { public ApplicationContext ctx = null; public SendMail() { // 获取上下文 ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); } public void send() { // 获取JavaMailSender bean JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender"); SimpleMailMessage mail = new SimpleMailMessage(); // <span // style="color: #ff0000;">注意SimpleMailMessage只能用来发送text格式的邮件</span> try { mail.setTo("464193096@qq.com");// 接受者 mail.setFrom("rocky2171@163.com");// 发送者,这里还可以另起Email别名,不用和xml里的username一致 mail.setSubject("spring mail test!");// 主题 mail.setText("springMail的简单发送测试\r\n恭喜呀");// 邮件内容 sender.send(mail); } catch (Exception e) { e.printStackTrace(); } } //测试发送邮件
public static void main(String[] args) { new SendMail().send(); } }
//applicationContext.xml
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!-- 注意:这里的参数(如用户名、密码)都是针对邮件发送者的 -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host">
<value>smtp.163.com</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>rocky2171@163.com</value>
</property>
<property name="password">
<value>********(邮箱密码)</value>
</property>
</bean>
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="username" value="x3513tj@gmail.com" />
<property name="password" value="x3513x3513" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.timeout">25000</prop>
<prop key="mail.smtp.port">465</prop>
<prop key="mail.smtp.socketFactory.port">465</prop>
<prop key="mail.smtp.socketFactory.fallback">false</prop>
<prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
</props>
</property>
</bean>
</beans>

//需要这5个包。可能运行会出现包冲突,如果使用myeclipse自带的javaee.jar,会和mail.jar冲突,那时移除javaee.jar,自己手工添加javaee.jar包。

浙公网安备 33010602011771号