iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >JavaMail整合Spring实现邮件发送功能
  • 348
分享到

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

JavaMailSpring邮件发送 2022-11-13 14:11:18 348人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

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

简介

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 {
    
    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的发送机制 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。

--结束END--

本文标题: JavaMail整合Spring实现邮件发送功能

本文链接: https://www.lsjlt.com/news/172405.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作