溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

JavaMail怎么整合Spring實(shí)現(xiàn)郵件發(fā)送功能

發(fā)布時(shí)間:2022-08-11 11:22:06 來(lái)源:億速云 閱讀:165 作者:iii 欄目:開(kāi)發(fā)技術(shù)

這篇“JavaMail怎么整合Spring實(shí)現(xiàn)郵件發(fā)送功能”文章的知識(shí)點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來(lái)看看這篇“JavaMail怎么整合Spring實(shí)現(xiàn)郵件發(fā)送功能”文章吧。

簡(jiǎn)介

javaMail與spring整合完成后,可大大加大郵件發(fā)送效率。當(dāng)服務(wù)器一啟動(dòng),配置文件就已加載。直接保存用戶(hù)信息時(shí),郵件可直接發(fā)送,大大提高了效率。

1.引入坐標(biāo)

<!-- 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工具類(lèi)

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 {
    /**
     * 發(fā)送郵件
     * @throws Exception 
     * 
     */
    public static void sendMsg(String toAddress,String subject,String content) throws Exception{
        //1.設(shè)置郵件的一些信息
        Properties props = new Properties();
        //發(fā)送郵件的服務(wù)器地址
        props.put("mail.smtp.host", "smtp.163.com");//smtp.qq.com stmp.sina.com
        props.put("mail.smtp.auth", "true");
        //2.創(chuàng)建Session對(duì)象
        Session session =Session.getInstance(props);
        //3.創(chuàng)建出MimeMessage,郵件的消息對(duì)象
        MimeMessage message = new MimeMessage(session);
        //4.設(shè)置發(fā)件人
        Address fromAddr = new InternetAddress("發(fā)件人郵箱");
        message.setFrom(fromAddr);

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

        //6.設(shè)置郵件的主題
        message.setSubject(subject);

        //7.設(shè)置郵件的正文
        message.setText(content);
        message.saveChanges();//保存更新

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

        transport.connect("smtp.163.com","發(fā)件人郵箱","發(fā)件人密碼"); //設(shè)置了火箭的發(fā)射地址

        transport.sendMessage(message, message.getAllRecipients());//發(fā)送具體內(nèi)容及接收人

        transport.close();
    }
}

3.mailproperties.xml

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

4.創(chuàng)建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"/>


    <!-- 簡(jiǎn)單消息對(duì)象創(chuàng)建 -->
    <bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage">
         <property name="from" value="${mail.from}"></property>
    </bean>

    <!-- 2.創(chuàng)建發(fā)送器 -->    
    <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類(lèi)中的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是否有值

            //說(shuō)明id沒(méi)有值,說(shuō)明保存    
            entity.setState(1);  //1代表可用
            String id = UUID.randomUUID().toString();
            entity.setId(id);
            entity.getUserinfo().setId(id);

            //設(shè)置初始密碼 需要將默認(rèn)的密碼加密后保存到數(shù)據(jù)庫(kù)
            entity.setPassword(Encrypt.md5(SysConstant.DEFAULT_PASS, entity.getUserName()));
//final就是延長(zhǎng)對(duì)象的生命周期,不然entity只能在saveOrUpdate中使用,使用完成后方法彈棧,而run方法內(nèi)就無(wú)法再使用之前定義好的entity。
//使用spring與javaMail實(shí)現(xiàn)新員工入職時(shí)郵件的發(fā)送
//使用線(xiàn)程并try-catch的目的就是如果郵件發(fā)送失敗,也不影響信息保存到數(shù)據(jù)庫(kù)。郵件發(fā)送成為了一個(gè)獨(dú)立的過(guò)程。
            Thread th = new Thread(new Runnable(){
                public void run(){
                    try {
                        mailMessage.setTo(entity.getUserinfo().getEmail());
                        mailMessage.setSubject("新員工入職信息");
                        mailMessage.setText("歡迎"+entity.getUserinfo().getName()+"加入廊坊思創(chuàng)志遠(yuǎn)科技有限公司,您在公司的賬號(hào):"+entity.getUserName()+",密碼:"+SysConstant.DEFAULT_PASS);
                        mailSender.send(mailMessage);
                    } catch (MailException e) {
                        e.printStackTrace();
                    }
                }
            });
            th.start();
        }
        baseDao.saveOrUpdate(entity);
}

以上就是關(guān)于“JavaMail怎么整合Spring實(shí)現(xiàn)郵件發(fā)送功能”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對(duì)大家有幫助,若想了解更多相關(guān)的知識(shí)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI