SpringMVC實現發送郵件

正文

今天來試着用SpringMVC發送郵件,主要須要依賴如下兩個包;html

<!--spring發送郵件依賴spring.version=4.3.8.RELEASE-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>

<!-- Javamail API -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5</version>
</dependency>

spring-mail.xml配置文件以下:前端

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

<!-- 引入屬性文件 -->
   <context:property-placeholder location="classpath:config/email.properties" ignore-unresolvable="true"/>

  <!-- <bean id="local" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
       <property name="location" value="classpath:config/email.properties" />
       <property name="ignoreUnresolvablePlaceholders" value="true" />
   </bean>-->
   <!--
       下面列出網易的SMTP服務器名和端口號:
        網易郵箱          SMTP服務器     SMTP端口     POP3服務器       POP3端口
        @126.com        smtp.126.com      25          pop3.126.com      110
        @163.com        smtp.163.com      25          pop3.163.com      110
        @yeah.net       smtp.yeah.net      25          pop3.yeah.net     110
    -->
   <bean id="javaMailSender"
         class="org.springframework.mail.javamail.JavaMailSenderImpl">
       <property name="protocol" value="${email.protocol}"/>
       <property name="host" value="${email.host}"/>
       <property name="port" value="${email.port}"/>
       <property name="username" value="${email.username}"/>
       <property name="password" value="${email.password}"/>
       <property name="defaultEncoding" value="UTF-8"></property>
       <property name="javaMailProperties">
           <props>
               <prop key="mail.auth">${email.auth}</prop>
               <prop key="mail.smtp.timeout">${email.timout}</prop>
           </props>
       </property>

   </bean>

   <bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage">
       <!-- 發件人email -->
       <property name="from" value="${email.username}" />
        <!--收件人email-->
       <property name="to" value="${email.default.to}" />
       <!--email主題(標題)-->
       <property name="subject" value="${email.default.subject}" />
       <!--email主題內容-->
       <property name="text">
         <value>${email.default.text}</value>
       </property>
   </bean>

   <bean id="emailService"
         class="com.website.service.impl.EmailServiceImpl">
       <property name="javaMailSender" ref="javaMailSender"/>
       <property name="simpleMailMessage" ref="simpleMailMessage"/>
   </bean>
</beans>

這裏加載了發送郵件相關的配置文件email.properties:java

email.protocol=smtp
email.host=smtp.163.com
email.port=25
email.username=132312312@163.com
email.password=yourpassword
email.default.to=123121@126.com
email.default.subject=Hello
email.default.text=how are you
email.auth=true
email.timout=25000

發送簡單郵件代碼:python

public class EmailServiceImpl implements EmailService {

   private static final Logger LOGGER = LoggerFactory.getLogger(EmailServiceImpl.class);

   private JavaMailSender javaMailSender;

   private SimpleMailMessage simpleMailMessage;

   /**
    * @方法名: sendMailSimple
    * @參數名:@param subject  郵件主題
    * @參數名:@param content 郵件內容
    * @參數名:@param to     收件人Email地址
    * @描述語: 發送郵件
    */
   @Override
   public void sendMailSimple(String to, String subject, String content) throws Exception {

       try {
           //用於接收郵件的郵箱
           simpleMailMessage.setTo(to);
           //郵件的主題
           simpleMailMessage.setSubject(subject);
           //郵件的正文,第二個boolean類型的參數表明html格式
           simpleMailMessage.setText(content);

           LOGGER.info("---------------------------{}", simpleMailMessage);
           //發送
           javaMailSender.send(simpleMailMessage);

       } catch (Exception e) {
           throw new MessagingException("failed to send mail!", e);
       }
   }

   public void setJavaMailSender(JavaMailSender javaMailSender) {
       this.javaMailSender = javaMailSender;
   }

   public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
       this.simpleMailMessage = simpleMailMessage;
   }
}

跑單元測試的時候報:Could not resolve placeholder異常,不能夠解析email.protocolweb

Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'javaMailSender' defined in class path resource [config/spring-mail.xml]: Could not resolve placeholder 'email.protocol' in value "${email.protocol}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'email.protocol' in value "${email.protocol}"

可能的緣由:面試

一、location中的屬性文件配置錯誤;spring

二、location中定義的配置文件裏面沒有對應的placeholder值;數據庫

三、Spring容器的配置問題,頗有多是使用了多個PropertyPlaceholderConfigurer或者多個<context:property-placeholder>的緣由。編程

排查之後發現,服務器

applicationContext.xml和spring-mail.xml兩個文件都使用了<context:property-placeholder>,前者加載數據庫鏈接配置,後者加載發送郵件相關配置。

<context:property-placeholder location="classpath:config/db.properties"/>
<context:property-placeholder location="classpath:config/email.properties"/>

這個是Spring容器採用反射掃描的發現機制決定的,在Spring 3.0中,能夠加ignore-unresolvable="true"解決。

<context:property-placeholder location="classpath:config/db.properties" ignore-unresolvable="true"/>
<context:property-placeholder location="classpath:config/email.properties" ignore-unresolvable="true"/>

注意:必須兩個都要加,加一個也不行。

在Spring 2.5中,<context:property-placeholder>沒有ignore-unresolvable屬性,此時能夠改用PropertyPlaceholderConfigurer。其實<context:property-placeholder location="xxx.properties" ignore-unresolvable="true" />與下面的配置是等價的。

<bean id="local" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
       <property name="location" value="classpath:config/email.properties" />
       <property name="ignoreUnresolvablePlaceholders" value="true" />
   </bean>

修改之後,測試用類運行成功:

在這裏插入圖片描述

發送郵件成功:
在這裏插入圖片描述

其實發送郵件還能夠用JavaMail實現,須要依賴兩個包:

activation-1.1.jar

mail-1.4.2.jar




本公衆號免費提供csdn下載服務,海量IT學習資源,若是你準備入IT坑,勵志成爲優秀的程序猿,那麼這些資源很適合你,包括但不限於java、go、python、springcloud、elk、嵌入式 、大數據、面試資料、前端 等資源。同時咱們組建了一個技術交流羣,裏面有不少大佬,會不定時分享技術文章,若是你想來一塊兒學習提升,能夠公衆號後臺回覆【2】,免費邀請加技術交流羣互相學習提升,會不按期分享編程IT相關資源。


掃碼關注,精彩內容第一時間推給你

image

相關文章
相關標籤/搜索