• 关于使用 Spring 发送简单邮件


      这是通过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 }
  • 相关阅读:
    关于oracle的导入数据流程,以及错误解决
    解决 lombok 和 freemarker 下载慢问题 以及安装方法
    解决maven项目没有Maven Dependencies
    将maven仓库改为阿里仓库
    Dos攻击和校网渗透
    KaliLinux切换python版本
    Kali国内更新源
    linux安装jdk(.rpm)
    Centos 关于 mysql 命令
    Linux删除命令
  • 原文地址:https://www.cnblogs.com/applerosa/p/5947607.html
Copyright © 2020-2023  润新知