JavaMail与Spring整合

简介

javaMail与spring整合完成后,可大大加大邮件发送效率。当服务器一启动,配置文件就已加载。直接保存用户信息时,邮件可直接发送,大大提高了效率。

1.引入坐标


        <dependency>
          <groupId>javax.mailgroupId>
          <artifactId>mailartifactId>
          <version>1.4.4version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-context-supportartifactId>
          <version>4.2.4.RELEASEversion>
        dependency>

2.抽取MailUtils工具类

package cn.itcast.jk.utils;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class MailUtils {
    /**
     * 发送邮件
     * @throws Exception 
     * 
     */
    public static void sendMsg(String toAddress,String subject,String content) throws Exception{
        //1.设置邮件的一些信息
        Properties props = new Properties();
        //发送邮件的服务器地址
        props.put("mail.smtp.host", "smtp.163.com");//smtp.qq.com stmp.sina.com
        props.put("mail.smtp.auth", "true");
        //2.创建Session对象
        Session session =Session.getInstance(props);
        //3.创建出MimeMessage,邮件的消息对象
        MimeMessage message = new MimeMessage(session);
        //4.设置发件人
        Address fromAddr = new InternetAddress("发件人邮箱");
        message.setFrom(fromAddr);

        //5.设置收件人
        Address toAddr=new InternetAddress(toAddress);
        message.setRecipient(RecipientType.TO, toAddr);

        //6.设置邮件的主题
        message.setSubject(subject);

        //7.设置邮件的正文
        message.setText(content);
        message.saveChanges();//保存更新

        //8.得到火箭
        Transport transport = session.getTransport("smtp");

        transport.connect("smtp.163.com","发件人邮箱","发件人密码"); //设置了火箭的发射地址

        transport.sendMessage(message, message.getAllRecipients());//发送具体内容及接收人

        transport.close();
    }
}

3.mailproperties.xml

mail.host=smtp.163.com
mail.username=你的邮箱名——也就是@前面的东西
mail.password=密码
mail.from=你的邮箱地址

4.创建applicationContext-mail.xml


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

    <description>JavaMail的配置文件description>
    
    <context:property-placeholder location="classpath:mail.properties"/>


    
    <bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage">
         <property name="from" value="${mail.from}">property>
    bean>

        
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
         <property name="host" value="${mail.host}">property>
         <property name="username" value="${mail.username}">property>
         <property name="password" value="${mail.password}">property>
         <property name="defaultEncoding" value="UTF-8">property>
         <property name="javaMailProperties">
            <props>
                 <prop key="mail.smtp.auth">trueprop>
                 <prop key="mail.debug">trueprop>
                 <prop key="mail.smtp.timeout">0prop>
            props>
         property>
    bean>
beans>

5.applicationContext.xml引入applicationContext-mail.xml

<import resource="classpath:spring/applicationContext-mail.xml"/>

6.applicationContext-service.xml中注值

id="userService" class="cn.itcast.jk.service.impl.UserServiceImpl">
        <property name="baseDao" ref="baseDao">property>
        <property name="mailMessage" ref="mailMessage">property>
        <property name="mailSender" ref="mailSender">property>
    

mailMessage与mailSender注入到UserServiceImpl中

7.UserServiceImpl类中的saveorUpdate方法中加入

//spring整合javaMail需要注入:
    private SimpleMailMessage mailMessage;
    private JavaMailSender mailSender;

    public void setMailMessage(SimpleMailMessage mailMessage) {
        this.mailMessage = mailMessage;
    }

    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }
public void saveOrUpdate(final User entity) {       
        if(UtilFuns.isEmpty(entity.getId())){
            //判断id是否有值

            //说明id没有值,说明保存    
            entity.setState(1);  //1代表可用
            String id = UUID.randomUUID().toString();
            entity.setId(id);
            entity.getUserinfo().setId(id);

            //设置初始密码 需要将默认的密码加密后保存到数据库
            entity.setPassword(Encrypt.md5(SysConstant.DEFAULT_PASS, entity.getUserName()));
//final就是延长对象的生命周期,不然entity只能在saveOrUpdate中使用,使用完成后方法弹栈,而run方法内就无法再使用之前定义好的entity。
//使用spring与javaMail实现新员工入职时邮件的发送
//使用线程并try-catch的目的就是如果邮件发送失败,也不影响信息保存到数据库。邮件发送成为了一个独立的过程。
            Thread th = new Thread(new Runnable(){
                public void run(){
                    try {
                        mailMessage.setTo(entity.getUserinfo().getEmail());
                        mailMessage.setSubject("新员工入职信息");
                        mailMessage.setText("欢迎"+entity.getUserinfo().getName()+"加入廊坊思创志远科技有限公司,您在公司的账号:"+entity.getUserName()+",密码:"+SysConstant.DEFAULT_PASS);
                        mailSender.send(mailMessage);
                    } catch (MailException e) {
                        e.printStackTrace();
                    }
                }
            });
            th.start();
        }
        baseDao.saveOrUpdate(entity);
    }       

JavaMail的发送机制

你可能感兴趣的:(------【spring】,●编程语言,------【Java】,●架构设计,javamail,邮件,spring)