項(xiàng)目總結(jié)之spring如何實(shí)現(xiàn)發(fā)送郵件功能

說(shuō)在前面

這幾天有點(diǎn)亂七八糟,前幾天實(shí)現(xiàn)了ping++的微信支付,后來(lái)覺(jué)得免費(fèi)版的ping++有點(diǎn)坑,一個(gè)月只提供1000次api調(diào)用(我們自己做測(cè)試都用去了差不多200次),而基礎(chǔ)版一年999的只提供5000次,所以果斷棄坑(這里有點(diǎn)對(duì)不起金亦冶大哥),選擇原生的微信支付,今天順便搞定了郵件發(fā)送,現(xiàn)在要說(shuō)的就是如何使用JavaMail實(shí)現(xiàn)郵件發(fā)送,這么晚了就長(zhǎng)話(huà)短說(shuō)了,直接進(jìn)入!


問(wèn)題描述

由于自己實(shí)現(xiàn)了微信支付總覺(jué)得安全性不夠高,所以打算加個(gè)郵件報(bào)警功能,如果用戶(hù)采用了非法操作就直接發(fā)郵件提醒我們幾個(gè)項(xiàng)目的管理人員。


要添加的maven依賴(lài):

    <!-- 郵件 -->
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.1</version>
    </dependency>
    <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>

    <dependency>
        <groupId>freemarker</groupId>
        <artifactId>freemarker</artifactId>
        <version>2.3.8</version>
    </dependency>

在resources中增加一個(gè)spring-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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"
    default-autowire="byName">

    <!-- 實(shí)現(xiàn)郵件服務(wù) -->
    <bean id="mimeMessage" class="javax.mail.internet.MimeMessage"
        factory-bean="javaMailSender" factory-method="createMimeMessage" />


    <bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.qq.com" />
        <property name="username" value="xxxx@qq.com" />
        <!-- //你的郵箱 -->
        <property name="password" value="yyyy" />
        <!-- //郵箱密碼 -->
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.host">smtp.qq.com</prop>
                <prop key="mail.smtp.timeout">25000</prop>
                <prop key="mail.smtp.port">25</prop>
                <prop key="mail.smtp.socketFactory.port">465</prop>
                <prop key="mail.smtp.socketFactory.fallback">false</prop>
                <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
            </props>
        </property>
    </bean>

    <bean id="mailService" class="ssm.aidai.serviceImpl.MailServiceImpl">
        <property name="mailSender" ref="javaMailSender" />
        <property name="mimeMessage" ref="mimeMessage" />
    </bean>
</beans>

在web.xml中引入對(duì)spring-mail.xml文件的掃描

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <!-- 更多的是bean文件的配置 -->
        <param-value>classpath:conf/spring-mail.xml</param-value>
    </context-param>

提供service接口

package ssm.aidai.service;

import ssm.aidai.pojo.MailModel;

public interface MailService {

public void sendAttachMail(MailModel mail);

}

提供實(shí)現(xiàn)類(lèi)

package ssm.aidai.serviceImpl;
import java.io.File;
import java.util.Date;

import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import ssm.aidai.pojo.MailModel;
import ssm.aidai.service.MailService;

public class MailServiceImpl implements MailService {

    private JavaMailSender mailSender;
    private MimeMessage mimeMessage;
    private static Logger logger = Logger.getLogger(MailServiceImpl.class);
    
    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void setMimeMessage(MimeMessage mimeMessage) {
        this.mimeMessage = mimeMessage;
    }

    /**
     * 發(fā)送html格式的,帶附件的郵件
     */
    @Override
    public void sendAttachMail(MailModel mail) {

        try {
            MimeMessageHelper mailMessage = new MimeMessageHelper(
                    this.mimeMessage, true, "UTF-8");
            mailMessage.setFrom(mail.getFromAddress());// 設(shè)置郵件消息的發(fā)送者

            mailMessage.setSubject(mail.getSubject());// 設(shè)置郵件消息的主題
            mailMessage.setSentDate(new Date());// 設(shè)置郵件消息發(fā)送的時(shí)間
            mailMessage.setText(mail.getContent(), true); // 設(shè)置郵件正文,true表示以html的格式發(fā)送

            String[] toAddresses = mail.getToAddresses().split(";");// 得到要發(fā)送的地址數(shù)組
            for (int i = 0; i < toAddresses.length; i++) {
                mailMessage.setTo(toAddresses[i]);
                for (String fileName : mail.getAttachFileNames()) {
                    mailMessage.addAttachment(fileName, new File(fileName));
                }
                // 發(fā)送郵件
                this.mailSender.send(this.mimeMessage);
                logger.info("send mail ok=" + toAddresses[i]);
            }
             

        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
        }

    }
}

最后提供測(cè)試,直接訪(fǎng)問(wèn)傳參即可

/**
 * @author:稀飯
 * @time:2017年3月6日 下午7:40:42
 * @filename:TestDemo.java
 */
package ssm.aidai.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import ssm.aidai.pojo.MailModel;
import ssm.aidai.service.MailService;

import com.sun.istack.logging.Logger;

@Controller
@RequestMapping("/testController")
public class TestDemo {
    Logger logger = Logger.getLogger(TestDemo.class);
    @Autowired
    private MailService mailService;

    @RequestMapping(value = "/send")
    @ResponseBody
    public void sendEmail(HttpServletRequest request) {
        MailModel mm = new MailModel();
        //附件
        String fileNames[] = { "G:/profession/Java/project/aidai/src/main/resources/conf/spring.xml" };
        mm.setAttachFileNames(fileNames);
        mm.setFromAddress("xxx@qq.com");
        mm.setToAddresses("yyy@qq.com;");
        mm.setContent("這是來(lái)自xx的一封信,如果你收到了,證明xxx的郵件功能搞定了!");
        mm.setSubject("xx測(cè)試(來(lái)自稀飯的一封信)");
        mailService.sendAttachMail(mm);
    }
}

這里要提及幾個(gè)點(diǎn):
使用的時(shí)候如果出現(xiàn)了Authentication failed; nested exception is javax.mail.AuthenticationFailedException這個(gè)bug,可以考慮以下兩個(gè)地方入手解決:

  • 1、開(kāi)啟POP3/SMTP服務(wù),具體步驟看圖:
image.png

開(kāi)啟后會(huì)獲取一個(gè)密碼,而這個(gè)密碼正式spring-mail.xml中的配置密碼,切記!

  • 2、發(fā)件人必須是你在spring-mail.xml中填寫(xiě)的郵箱。

**ps: 如果有demo源碼需求可以考慮私聊我! **

Note:發(fā)布的這些文章全都是自己邊學(xué)邊總結(jié)的,難免有紕漏,如果發(fā)現(xiàn)有不足的地方,希望可以指出來(lái),一起學(xué)習(xí)咯,么么噠。
開(kāi)源愛(ài)好者,相信開(kāi)源的力量必將改變世界:
** osc :** https://git.oschina.net/xi_fan
github: https://github.com/wiatingpub

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,253評(píng)論 6 342
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評(píng)論 19 139
  • 13. Hook原理介紹 13.1 Objective-C消息傳遞(Messaging) 對(duì)于C/C++這類(lèi)靜態(tài)語(yǔ)...
    Flonger閱讀 1,529評(píng)論 0 3
  • 今天,我明白我并非我的假我,或是我出生時(shí)被給予的姓名。事實(shí)上我就是真正的我――宇宙的延伸和一個(gè)非常非常富足的...
    雨敲窗閱讀 99評(píng)論 0 0
  • 父母是孩子一生中的啟蒙老師。 沒(méi)學(xué)過(guò)如何做父母的家長(zhǎng)就跟沒(méi)有駕照上高速的司機(jī)一樣危險(xiǎn)。 現(xiàn)在有些家長(zhǎng)由于忙工作,忙...
    春風(fēng)涼意閱讀 711評(píng)論 4 7

友情鏈接更多精彩內(nèi)容