码迷,mamicode.com
首页 > 编程语言 > 详细

关于使用 Spring 发送简单邮件

时间:2016-10-10 23:13:03      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

  这是通过Spring 框架内置的功能完成简单邮件发送的测试用例。

  1. 导入相关的 jar 包.

Spring 邮件抽象层的主要包为 org.springframework.mail

它包括了发送电子邮件的主要接口 MailSender,和值对象 SimpleMailMessage,它封装了简单邮件的属性。

如 from,to,cc, subject,text。

  2. 在邮箱设置中打开邮件的发送服务:

  技术分享

  3. 在src目录下建立mail.properties文件里边包含一下内容

mail.host=smtp.exmail.qq.com (邮箱的发送域名设置)
mail.username=你的邮箱名
mail.password=你的邮箱密码
mail.from=发送方的邮箱

  4. spring配置

 1 <!-- 加载Properties文件 -->
 2 <bean id="configurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
 3     <property name="locations">
 4         <list>
 5             <value>classpath:mail.properties</value>
 6         </list>
 7     </property>
 8 </bean>
 9 <bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage">
10     <property name="from">
11         <value>${mail.from}</value>
12     </property>
13     <!-- 查看SimpleMailMessage源码还可以注入标题,内容等 -->
14 </bean>
15 <!-- 申明JavaMailSenderImpl对象 -->
16 <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
17     <property name="defaultEncoding" value="UTF-8" />
18     <property name="host" value="${mail.host}" />
19     <property name="username" value="${mail.username}" />
20     <property name="password" value="${mail.password}" />
21     <property name="javaMailProperties">
22         <props>
23             <!-- 设置认证开关 -->
24             <prop key="mail.smtp.auth">true</prop>
25             <!-- 启动调试开关 -->
26             <prop key="mail.debug">true</prop>
27             <!-- 设置发送延时 -->
28             <prop key="mail.smtp.timeout">0</prop>
29         </props>
30     </property>
31 </bean>
32 </beans>

  5. action中添加简单的发送方法

 1 /**
 2 * 本类测试邮件发送Html形式
 3 */
 4 public class SingleMailSend {
 5     static ApplicationContext actx =
 6         new ClassPathXmlApplicationContext("applicationContext.xml");
 7     static MailSender sender = (MailSender) actx.getBean("mailSender");
 8     static SimpleMailMessage mailMessage =
 9         (SimpleMailMessage) actx.getBean("mailMessage");
10     public static void main(String args[]) throws MessagingException {
11         mailMessage.setSubject("你好");
12         mailMessage.setText("这个是一个通过Spring框架来发送邮件的小程序");
13         mailMessage.setTo("******@qq.com");
14         sender.send(mailMessage);
15     }
16 }

 

关于使用 Spring 发送简单邮件

标签:

原文地址:http://www.cnblogs.com/applerosa/p/5947607.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!