温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JavaMail怎么整合Spring实现邮件发送功能

发布时间:2022-08-11 11:22:06 来源:亿速云 阅读:149 作者:iii 栏目:开发技术

这篇“JavaMail怎么整合Spring实现邮件发送功能”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“JavaMail怎么整合Spring实现邮件发送功能”文章吧。

简介

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

1.引入坐标

<!-- Javamail -->
        <dependency>
          <groupId>javax.mail</groupId>
          <artifactId>mail</artifactId>
          <version>1.4.4</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context-support</artifactId>
          <version>4.2.4.RELEASE</version>
</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

<?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: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>
    <!-- 加载mail.properties配置文件 -->
    <context:property-placeholder location="classpath:mail.properties"/>


    <!-- 简单消息对象创建 -->
    <bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage">
         <property name="from" value="${mail.from}"></property>
    </bean>

    <!-- 2.创建发送器 -->    
    <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">true</prop>
                 <prop key="mail.debug">true</prop>
                 <prop key="mail.smtp.timeout">0</prop>
            </props>
         </property>
    </bean>
</beans>

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

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

6.applicationContext-service.xml中注值

<bean 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>
    </bean>

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实现邮件发送功能”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI