1. 程式人生 > 程式設計 >Simple Java Mail郵件傳送實現過程解析

Simple Java Mail郵件傳送實現過程解析

前言

在我們日常工作中,郵件傳送服務經常會用到,我們常用的java郵件服務實現方案有:java原生自帶的javamail、apache commons mail工具包、spring mail。但是個人使用這麼久而言,感覺使用起來都不太順手,也略顯複雜

在此推薦一個簡單易用的類庫simple-java-mail

github地址: http://www.simplejavamail.org

下面我會介紹一下這個mail工具類的基本用法,不過基本都是來自於官網,隨後我會基於這個mail工具類去封裝一個基本通用的郵件服務。

maven引入

<dependency>
  <groupId>org.simplejavamail</groupId>
  <artifactId>simple-java-mail</artifactId>
  <version>4.2.3-java6-release</version>
</dependency>

例子

傳送一封簡易郵件

寫法1 Builder模式:

Email email = new EmailBuilder()
.from("Michel Baker","[email protected]")
.to("mom","[email protected]")
.to("dad","[email protected]")
.subject("My Bakery is finally open!")
.text("Mom,Dad. We did the opening ceremony of our bakery!!!")
.build();

new Mailer("server",25,"username","password").sendMail(email);

寫法二 常規模式:

Email email = new Email();

email.setFromAddress("Michel Baker","[email protected]");
email.addRecipient("mom","[email protected]",RecipientType.TO);
email.addRecipient("dad","[email protected]",RecipientType.TO);
email.setSubject("My Bakery is finally open!");
email.setText("Mom,Dad. We did the opening ceremony of our bakery!!!");

new Mailer("server","password").sendMail(email);

和spring結合使用

<bean id="inhouseMailer" class="org.simplejavamail.mailer.Mailer">
  <constructor-arg value="server" />
  <constructor-arg value="25" />
  <constructor-arg value="username" />
  <constructor-arg value="password" />
</bean>

@Autowired 
Mailer inhouseMailer; 
inhouseMailer.sendMail(email);
inhouseMailer.sendMail(anotherEmail);

新增多個接收者

//新增多個接收者
email.addRecipients(yourRecipient1,yourRecipient2...);
//也可以通過逗號“,”分割多個抄送人
String list = "[email protected],[email protected];[email protected]";
emailNormal.addRecipients(list,RecipientType.BCC);

builder模式:
.to(yourRecipient1,yourRecipient2...)
.bcc("[email protected],[email protected];[email protected]")
...
.build();

支援非同步傳送

// 第二個引數是true則是非同步傳送,false則是同步傳送
mailer.sendMail(email,true);

配置SSL或TLS

Email email = new Email();

mailer.sendMail(email,TransportStrategy.SMTP_PLAIN); // 此為預設值,不加巢狀任何傳輸協議
mailer.sendMail(email,TransportStrategy.SMTP_SSL);
mailer.sendMail(email,TransportStrategy.SMTP_TLS);

我們也可以在初始化郵件伺服器配置時宣告傳輸協議

new Mailer("smtp.gmail.com","your user","your password",TransportStrategy.SMTP_TLS).sendMail(email);
new Mailer("smtp.gmail.com",587,465,TransportStrategy.SMTP_SSL).sendMail(email);

傳送附件

Email email = new Email();

email.addAttachment("dresscode.txt",new ByteArrayDataSource("Black Tie Optional","text/plain"));
email.addAttachment("location.txt","On the moon!".getBytes(Charset.defaultCharset()),"text/plain");

// 當然,你可以傳輸任何檔案格式的附件

email.addAttachment("invitation.pdf",new FileDataSource("invitation_v8.3.pdf"));

內容巢狀圖片

Email email = new Email();

email.addEmbeddedImage("smiley",new FileDataSource("smiley.jpg"));

String base64String = "iVBORw0KGgoAAAANSUhEUgAAA ...snip";
email.addEmbeddedImage("thumbsup",parseBase64Binary(base64String),"image/png");

// 圖片需要在html文字中通過cid:xxxx,的方式引用
<p>Let's go!</p>![](cid:thumbsup)<br/>
<p>Smile!</p>![](cid:smiley)

自定義傳送頭

Email email = new Email();

email.addHeader("X-Priority",2);
email.addHeader("X-MC-GoogleAnalyticsCampaign","halloween_sale");
email.addHeader("X-MEETUP-RECIP-ID","71415272");
email.addHeader("X-my-custom-header","foo");

驗證郵箱合法性

具體使用的工具類是email-rfc2822-validator

github地址:https://github.com/bbottema/email-rfc2822-validator

//經過使用發現,貌似只是用正則表示式去驗證郵箱是否合法
EmailAddressValidator.isValid("[email protected]",
EmailAddressCriteria.RFC_COMPLIANT);
EmailAddressValidator.isValid("[email protected]",
EnumSet.of(EmailAddressCriteria.ALLOW_QUOTED_IDENTIFIERS,EmailAddressCriteria.ALLOW_PARENS_IN_LOCALPART));

使用代理髮送

// anonymous proxy
new Mailer(serverConfig,new ProxyConfig("proxy.host.com",1080));

// authenticated proxy
new Mailer(serverConfig,1080,"proxy username","proxy password"));

總結

此工具類方便易用,簡潔明瞭,而且支援Builder模式鏈式呼叫。有興趣的同學可以嘗試使用,個人感覺比原生mail,spring mail等易用,更多用法請自行檢視官網例子。至於一開始說到的封裝通用的郵件服務,這個由於時間關係,我放到下一次再實現。謝謝大家的支援,如果此文對你有所幫助,請點個贊,謝謝。

https://github.com/bbottema/simple-java-mail/

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。