項目總結之spring如何實現發送郵件功能

說在前面

這幾天有點亂七八糟,前幾天實現了ping++的微信支付,后來覺得免費版的ping++有點坑,一個月只提供1000次api調用(我們自己做測試都用去了差不多200次),而基礎版一年999的只提供5000次,所以果斷棄坑(這里有點對不起金亦冶大哥),選擇原生的微信支付,今天順便搞定了郵件發送,現在要說的就是如何使用JavaMail實現郵件發送,這么晚了就長話短說了,直接進入!


問題描述

由于自己實現了微信支付總覺得安全性不夠高,所以打算加個郵件報警功能,如果用戶采用了非法操作就直接發郵件提醒我們幾個項目的管理人員。


要添加的maven依賴:

    <!-- 郵件 -->
    <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中增加一個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">

    <!-- 實現郵件服務 -->
    <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中引入對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);

}

提供實現類

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;
    }

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

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

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

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

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

    }
}

最后提供測試,直接訪問傳參即可

/**
 * @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("這是來自xx的一封信,如果你收到了,證明xxx的郵件功能搞定了!");
        mm.setSubject("xx測試(來自稀飯的一封信)");
        mailService.sendAttachMail(mm);
    }
}

這里要提及幾個點:
使用的時候如果出現了Authentication failed; nested exception is javax.mail.AuthenticationFailedException這個bug,可以考慮以下兩個地方入手解決:

  • 1、開啟POP3/SMTP服務,具體步驟看圖:
image.png

開啟后會獲取一個密碼,而這個密碼正式spring-mail.xml中的配置密碼,切記!

  • 2、發件人必須是你在spring-mail.xml中填寫的郵箱。

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

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,971評論 6 342
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,991評論 19 139
  • 13. Hook原理介紹 13.1 Objective-C消息傳遞(Messaging) 對于C/C++這類靜態語...
    Flonger閱讀 1,458評論 0 3
  • 今天,我明白我并非我的假我,或是我出生時被給予的姓名。事實上我就是真正的我――宇宙的延伸和一個非常非常富足的...
    雨敲窗閱讀 88評論 0 0
  • 父母是孩子一生中的啟蒙老師。 沒學過如何做父母的家長就跟沒有駕照上高速的司機一樣危險。 現在有些家長由于忙工作,忙...
    春風涼意閱讀 656評論 4 7