使用Spring使用Java發送電子郵件– GMail SMTP服務器示例

對于使用Java發送電子郵件, JavaMail API是標準解決方案。 如官方網頁所述,“ JavaMail API提供了獨立于平臺和協議的框架來構建郵件和消息傳遞應用程序”。 必需的類包含在JavaEE平臺中,但是要在獨立的JavaSE應用程序中使用它,您必須從這里下載相應的JAR。

注意:除非您使用Java SE 6,否則還需要提供javax.activation包的JavaBeans激活框架(JAF)擴展。 我們建議您使用最新版本的JAF 1.1.1版本。 JAF包含在Java SE 6中。

不幸的是,JavaMail可能有點笨拙,并且難以配置和使用。 如果您已經為應用程序擁抱了Spring框架 ,那么您將很高興發現Spring提供了一個郵件抽象層。 如參考文檔所述,“ Spring框架提供了一個有用的實用程序庫,用于發送電子郵件,該電子郵件使用戶免受底層郵件系統的限制,并負責代表客戶端進行低級資源處理。” 太好了,現在讓我們看看如何利用這個庫。

首先,創建一個名為“ SpringMailProject”的新Eclipse項目。 在項目的類路徑中,確保包括以下庫(請注意,使用的是3.0.2.RELEASE Spring版本):

  • mail.jar(JavaMail的核心類)
  • org.springframework.asm-3.0.2.RELEASE.jar
  • org.springframework.beans-3.0.2.RELEASE.jar
  • org.springframework.context.support-3.0.2.RELEASE.jar
  • org.springframework.core-3.0.2.RELEASE.jar
  • org.springframework.expression-3.0.2.RELEASE.jar
  • com.springsource.org.apache.commons.logging-1.1.1.jar

注意1:需要Apache的commons-logging庫,該庫包含在classpath中
注意2:如果您使用的是Java 1.5或更早版本,則還需要Java激活框架。

我們將使用MailSender ,這是一個Spring接口,用于定義發送簡單郵件的策略。 由于這只是一個接口,因此我們需要一個具體的實現,并以JavaMailSenderImpl的形式出現。 此類同時支持JavaMail MimeMessage和Spring SimpleMailMessage 。

我們將創建一個簡單的Spring服務,該服務將用于發送郵件。 一種方法將在現場創建SimpleMailMessage ,而另一種方法將使用預配置的默認消息。 該服務的源代碼如下:

package com.javacodegeeks.spring.mail;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;@Service("mailService")
public class MailService {@Autowiredprivate MailSender mailSender;@Autowiredprivate SimpleMailMessage alertMailMessage;public void sendMail(String from, String to, String subject, String body) {SimpleMailMessage message = new SimpleMailMessage();message.setFrom(from);message.setTo(to);message.setSubject(subject);message.setText(body);mailSender.send(message);}public void sendAlertMail(String alert) {SimpleMailMessage mailMessage = new SimpleMailMessage(alertMailMessage);mailMessage.setText(alert);mailSender.send(mailMessage);}}

該類只是一個POJO,其服務名稱為“ mailService”,由構造型Service批注標記。 使用的bean接線策略是自動裝配之一 ,因此使用了Autowired注釋。 注意,可以使用bean的名稱和類型來執行自動裝配。

引導容器的相應Spring 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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"xmlns:jee="http://www.springframework.org/schema/jee" xmlns:task="http://www.springframework.org/schema/task"xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"
><context:component-scan base-package="com.javacodegeeks.spring.mail" />??? <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"><property name="host" value="smtp.gmail.com"/><property name="port" value="25"/><property name="username" value="myusername@gmail.com"/><property name="password" value="mypassword"/><property name="javaMailProperties"><props><!-- Use SMTP transport protocol --><prop key="mail.transport.protocol">smtp</prop><!-- Use SMTP-AUTH to authenticate to SMTP server --><prop key="mail.smtp.auth">true</prop><!-- Use TLS to encrypt communication with SMTP server --><prop key="mail.smtp.starttls.enable">true</prop><prop key="mail.debug">true</prop></props></property></bean><bean id="alertMailMessage" class="org.springframework.mail.SimpleMailMessage"><property name="from">??????????? <value>myusername@gmail.com</value></property><property name="to">??????????? <value>myusername@gmail.com</value></property><property name="subject" value="Alert - Exception occurred. Please investigate"/></bean></beans>

這是一個非常簡單的Spring配置文件。 不過,有些事情要提及:

  • 聲明從其開始上下文掃描的基本軟件包,并將其設置為“ com.javacodegeeks.spring.mail”。
  • 聲明了“ mailSender” bean,并適當設置了其一堆屬性(使用您自己的SMTP服務器配置屬性和憑據)。
  • “ alertMailMessage”是預配置的Spring SimpleMailMessage,將使用“按名稱自動裝配”將其注入“ MailService”類中。

如果您希望使用Gmail的SMTP服務器,請確保正確配置了以下JavaMail屬性:

host=smtp.gmail.com
port=25
username=your-gmail-username
password=your-gmail-password
mail.transport.protocol=smtp
mail.smtp.auth=true
mail.smtp.starttls.enable=true

在開發階段,如果希望郵件客戶端生成信息性日志,請將“ mail.debug”設置為true。 但是,請記住在生產時將其設置為false,因為日志量可能會降低應用程序的性能和/或填充硬盤。

最后,我們創建一個類,該類將用于創建Spring容器并測試我們創建的簡單郵件服務。 源代碼如下:

package com.javacodegeeks.spring.mail;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;public class MailServiceTest {public static void main(String[] args) {ApplicationContext context = new FileSystemXmlApplicationContext("conf/spring.xml");MailService mailService = (MailService) context.getBean("mailService");mailService.sendMail("myusername@gmail.com", "myusername@gmail.com", "Testing123", "Testing only \n\n Hello Spring Email Sender");mailService.sendAlertMail("Exception occurred");}}

FileSystemXmlApplicationContext類用作ApplicationContext 。 我們在構造函數中傳遞Spring的XML文件位置,該類創建容器,實例化Bean并處理依賴項。 你不愛春天嗎? 接下來,我們使用“ getBean ”方法檢索“ MailService”服務的引用,并調用這兩個方法。

就這樣。 與往常一樣,您可以從此處下載完整的Eclipse項目。

相關文章 :
  • 依賴注入–手動方式
  • 使用Spring Security保護GWT應用程序
  • 帶有Spring和Maven教程的JAX–WS
  • 建立自己的GWT Spring Maven原型
  • 使用Spring AspectJ和Maven進行面向方面的編程
  • Spring3 RESTful Web服務
  • JBoss 4.2.x Spring 3 JPA Hibernate教程

翻譯自: https://www.javacodegeeks.com/2010/07/java-mail-spring-gmail-smtp.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/374589.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/374589.shtml
英文地址,請注明出處:http://en.pswp.cn/news/374589.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Java字符與數字的計算

先看例子&#xff1a; char ch;int x;int y 7;System.out.print("7的ASCII碼值是&#xff1a;");System.out.println(y);ch 7 2;System.out.print("7 2的char型&#xff1a;");System.out.println(ch);x 7 2;System.out.print("7 2的int型&…

wordcount

源代碼如下 package org.apache.hadoop.examples; import java.io.IOException; import java.util.StringTokenizer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io…

EJB 3.1全局JNDI訪問

如本系列前面的部分所述&#xff0c;EJB 3.0版規范的主要缺點是缺少可移植的全局JNDI名稱。 這意味著沒有可移植的方式將EJB引用鏈接到應用程序外部的Bean。 EJB v。3.1規范用自己的話填補了這一定義&#xff1a; “一個標準化的全局JNDI名稱空間和一系列相關的名稱空間&#…

Git 分支管理和沖突解決

創建分支 git branch 沒有參數&#xff0c;顯示本地版本庫中所有的本地分支名稱。 當前檢出分支的前面會有星號。 git branch newname 在當前檢出分支上新建分支&#xff0c;名叫newname。 git checkout newname 檢出分支&#xff0c;即切換到名叫newname的分支。 git checkout…

力扣打開轉盤鎖

打開轉盤鎖 評論區大神代碼&#xff1a; public int openLock(String[] deadends, String target) {Set<String> set new HashSet<>(Arrays.asList(deadends));//開始遍歷的字符串是"0000"&#xff0c;相當于根節點String startStr "0000";i…

EJB程序化查找

在上一篇文章中&#xff0c;我們了解了EJB 引用和EJB 注入 。 盡管EJB注入是一種強大的容器工具&#xff0c;可以簡化模塊化應用程序的開發&#xff0c;但有時還是需要執行程序化EJB查找。 讓我們假設&#xff0c;例如&#xff0c;一組不同的EJB實現了由公共業務接口定義的公共…

git克隆/更新/提交代碼步驟及示意圖

1. git clone ssh://flycm.intel.com/scm/at/atSrc 或者git clone ssh://flycm.intel.com/scm/at/atJar 或者git clone ssh://flycm.intel.com/scm/at/atFramework 2. git checkout cpeg/scm/stable 切換分支&#xff0c;然后更新代碼 3. git pull 先把遠程分支上最新的代碼拉到…

C++面試寶典

1.new、delete、malloc、free關系 delete會調用對象的析構函數,和new對應free只會釋放內存&#xff0c;new調用構造函數。malloc與free是C/C語言的標準庫函數&#xff0c;new/delete是C的運算符。它們都可用于申請動態內存和釋放內存。對于非內部數據類型的對象而言&#xff0c…

Google App Engine:在您自己的域中托管應用程序

在Google App Engine中創建新應用程序時&#xff0c;您將獲得一個域名“ yourapp.appspot.com”。 但是&#xff0c;誰會想要以這樣的后綴托管他們的應用程序&#xff08;除非您喜歡它&#xff01;&#xff09;&#xff1f; 為了改善您的應用品牌&#xff0c;最好的辦法是將您的…

從零開始學 iOS 開發的15條建議

事情困難是事實&#xff0c;再困難的事還是要每天努力去做是更大的事實。 因為我是一路自學過來的&#xff0c;并且公認沒什么天賦的前提下&#xff0c;進步得不算太慢&#xff0c;所以有很多打算從零開始的朋友會問我&#xff0c;該怎么學iOS開發。跟粉絲群的朋友交流了一下&a…

垂直居中-父元素高度確定的多行文本(方法二)

除了上一節講到的插入table標簽&#xff0c;可以使父元素高度確定的多行文本垂直居中之外&#xff0c;本節介紹另外一種實現這種效果的方法。但這種方法兼容性比較差&#xff0c;只是提供大家學習參考。 在 chrome、firefox 及 IE8 以上的瀏覽器下可以設置塊級元素的 display 為…

13. 羅馬數字轉整數

羅馬數字轉整數 class Solution {public int romanToInt(String s) {Map<Character,Integer> map new HashMap<Character,Integer>(){{put(I,1);put(V,5);put(X,10);put(L,50);put(C,100);put(D,500);put(M,1000);}};int res 0;for(int i 0;i<s.length();i)…

互聯網金融P2P主業務場景自動化測試

互聯網金融P2P行業&#xff0c;近三年來發展迅速&#xff0c;如火如荼。據不完全統計&#xff0c;全國有3000的企業。“互聯網”企業&#xff0c;幾乎每天都會碰到一些奇奇怪怪的bug&#xff0c;作為在互聯網企業工作的測試人員&#xff0c;風險和壓力都巨大。那么我們如何降低…

OSGi將Maven與Equinox結合使用

很長時間以來&#xff0c;我一直在努力理解OSGi的真正含義。 它已經存在很長時間了&#xff0c;但是沒有多少人意識到這一點。 人們已經大肆宣傳它是一種非常復雜的技術。 這是我為所有Java開發人員簡化的嘗試。 簡而言之&#xff0c; OSGi是一組規范&#xff0c;這些規范允許對…

note05-計算機網絡

5.網絡安全 被動攻擊(UDP報文被截獲 被 進行流量分析) 主動攻擊 1.篡改(更改報文流 偽報文) 2.惡意程序(病毒、木馬、蠕蟲、炸彈) 3.拒絕服務Dos 密碼體制 1.對稱密鑰密碼體制(DES IDEA) 即加密和解密的密鑰K相同 2.公鑰密碼體制(RSA) A加密使用PKB公鑰 B解密使用對應的私鑰SK…

825. 適齡的朋友

適齡的朋友 在社交媒體網站上有 n 個用戶。給你一個整數數組 ages &#xff0c;其中 ages[i] 是第 i 個用戶的年齡。 如果下述任意一個條件為真&#xff0c;那么用戶 x 將不會向用戶 y&#xff08;x ! y&#xff09;發送好友請求&#xff1a; age[y] < 0.5 * age[x] 7 ag…

struts2設置文件上傳大小

利用struts2想要設置或者限制上傳文件的大小,可以在struts.xml配置文件里面進行如下配置: <constant name"struts.multipart.maxSize" value"10000000" /> 上面這句話的意思是設置文件上傳大小&#xff0c;最大不超過9.8M。計算方式如下&#xff1a;…

Java命名約定

我想寫這篇簡短的文章來幫助某些難以記住Java API類和方法名稱的人。 如您所知&#xff0c;Java是區分大小寫的語言&#xff0c;要構建Java程序&#xff0c;您需要使用許多內置API類和方法。 而且&#xff0c;初學者發現很難準確地記住方法名稱和類名稱而不改變大小寫。 但是實…

smarty引擎之練習

關于smarty最直觀的感受就是分離了頁面中html和php的代碼&#xff0c;頁面不再混亂&#xff0c;很清晰了…… smarty->assign();//注冊 smarty->display();//加載模板 除了老師給的表&#xff0c;kemu,nandu,type都建了表格&#xff0c;便于使用 main.php <?phpinclu…

Heron 論文翻譯及理解

Heron 論文翻譯及理解 背景介紹&#xff1a; Heron是號稱Twitter流數據處理的新一代實現&#xff0c;是StormV2。我們首先回顧一下Storm系統的問題 worker日志混亂&#xff0c;如果一個bolt日志過大&#xff0c;會沖掉其他bolt的日志worker之間因為沒有資源隔離&#xff0c;因此…