使用spring發送郵件

來源:互聯網
上載者:User

 最近想做一個網站,註冊那部分想做成將密碼資訊發送到客戶郵件中的那種,隨即翻了翻資料做了個例子

建立一個設定檔Bean.xml,內容如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
  <bean id="mailSender"
        class="org.springframework.mail.javamail.JavaMailSenderImpl">
       <property name="host">
         <value>smtp.163.com</value>
       </property>
       <property name="username">
         <value>flatfish93</value>
      </property>
      <property name="password">
         <value>password</value>
      </property>

      /////////////////////////smtp驗證///////////////////////
      <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">true</prop>
        </props>
      </property>
     ////////////////////////////////////////////////////////////////////
 </bean>

 <bean id="mailMessage"
        class="org.springframework.mail.SimpleMailMessage">
      <property name="to">
       <value>f9inux@gmail.com</value>
      </property>
      <property name="from">
        <value>flatfish93@163.com</value>
      </property>
      <property name="subject">
        <value>Hello</value>
      </property>
      <property name="text">
       <value>ghjgjhghghghgjhgjgjhgj</value>
      </property>
</bean>
</beans>

上面那一部分寫的很粗糙,畢竟我沒有時間去細化它。本人建議大家將mailSender中的username,password放入properties中。在使用mailMessage的contrller中引入執行個體,配置property中的to、subject、text。

在測試類別中這樣寫

   ApplicationContext ctx=new FileSystemXmlApplicationContext("src/Bean.xml");
   JavaMailSenderImpl senderImpl=(JavaMailSenderImpl)ctx.getBean("mailSender");
   SimpleMailMessage ms=(SimpleMailMessage)ctx.getBean("mailMessage");
   senderImpl.send(ms);                  //發送郵件的方法

大概就是這麼多,僅供大家學習參考

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.