Simple Java Mail的使用

Simple Java Mail是一個非常強大的郵件發送框架,非常值得使用。

本文翻譯Simple Java Mail的官方實例文檔,可以參考使用。

官方網站:http://www.simplejavamail.org/#/about

原文:http://www.simplejavamail.org/#/features

基本用法

創建Email,填充你的數據,創建Mailer然後發送Email實例,mailer也可以是你自己的Session實例。
Mailer 是單例模式。

Email email = new Email();

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

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

使用建造者模式的流式接口

前一個例子用流式接口可以更簡潔。

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

一次配置多次使用

    你可以預配置一個Mailer,然後無限次使用

    Mailer inhouseMailer = new Mailer("server", 25, "username", "password");

    inhouseMailer.sendMail(email);
    inhouseMailer.sendMail(anotherEmail);


    或者配置成一個Spring Bean 

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


    或者用Spring的默認值

    @Autowired Mailer mailer; // configured completely using default properties

幾乎所有都可以替代的API

有幾種方法可以在電子郵件中做幾乎所有的事情,只是爲了適應你已經擁有的東西。

Email:

// You can add your own Recipient instances for example
email.addRecipients(yourRecipient1, yourRecipient2...);

// or add comma / semicolon separated addresses (without names)
String list = "[email protected],[email protected];[email protected]";
emailNormal.addBccRecipients(list);
// or:
emailNormal.addNamedToRecipients("maintenance group", list);

// what about a group with one deviating name?
String list = "[email protected], [email protected]; Security Group <[email protected]>";
emailNormal.addNamedToRecipients("stakeholders", list);
// bob and gene are named "stakeholders", "Security Group" get its own name

EmailBuilder:

.to(yourRecipient1, yourRecipient2...)
.cc("stakeholders", "[email protected]", "[email protected]", "Security Group <[email protected]>")
.cc("stakeholders", "[email protected], [email protected]; Security Group <[email protected]>")
.bcc("[email protected],[email protected];[email protected]")
...
.build();

Through properties:

simplejavamail.defaults.bcc.name=
simplejavamail.defaults.bcc.address=twister@sweets.com,blue.tongue@sweets.com;[email protected]

異步並行批量發送

默認是同步的發送方式,閉塞執行直到email被處理且返回成功的結果。
你也可以異步或者批量發送,或者使用fire-and-forget發送方式
如果認證的代理接口正在被使用,這個接口會一直保持到最後一封發送完畢。
依靠SMTP 服務(和代理服務如果可以)這個可以快速發送。

mailer.sendMail(email, true);

用自己的Session實例發送

如果你更喜歡使用預配置的Session實例發送,仍然可以使用。
    Email email = new Email();
    ...

    new Mailer(yourSession).sendMail(email);

在發送的電子郵件中設置自定義郵件ID

消息ID通常由底層的JavaMail框架生成,但如果需要,您可以提供自己的框架。
只需確保您自己的id符合rfc5322 msg-id格式標準

Email email = new Email()
    email.setId("<123@456>");

Or:
Email email = new EmailBuilder()
    .id("<123@456>")
    .build();

用SSL和TLS發送

激活SSL或TLS是非常簡單的。 只需使用適當的TransportStrategy枚舉。

Email email = new Email();

mailer.sendMail(email, TransportStrategy.SMTP_PLAIN); // default if omitted
mailer.sendMail(email, TransportStrategy.SMTP_SSL);
mailer.sendMail(email, TransportStrategy.SMTP_TLS);

SSL和TLS與Google郵件

這裏有個例子關於用SSL和TLS使用gMail。
如果您啓用two-factor(雙重認證)登錄,則需要從Google帳戶生成專用密碼。

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

添加附件

你可以輕鬆添加附件,但您必須自己提供數據。 簡單的Java Mail接受byte []和DataSource對象。

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");

// ofcourse it can be anything: a pdf, doc, image, csv or anything else

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

嵌入圖片

嵌入圖片比較簡單,但是你必須自己在HTML中添加佔位符

Email email = new Email();

email.addEmbeddedImage("smiley", new FileDataSource("smiley.jpg"));
// this example is included in the demo package in MailTestApp.java
String base64String = "iVBORw0KGgoAAAANSUhEUgAAA ...snip";
email.addEmbeddedImage("thumbsup", parseBase64Binary(base64String), "image/png");

// the corresponding HTML should contain the placeholders
<p>Let's go!</p><img src='cid:thumbsup'><br/>
<p>Smile!</p><img src='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");

在內部會話中設置自定義屬性

如果你需要修改內部Session對象,那需要你基礎的javax.mail支持來配置,這也非常簡單。

Properties props = new Properties();
props.setProperty("mail.smtp.timeout", 30 * 1000);
props.setProperty("mail.smtp.connectiontimeout", 10 * 1000);

Mailer mailer = new Mailer();
mailer.applyProperties(props);

直接訪問會話內部

對於緊急情況,你還可以獲取內部會話實例本身。雖然你不太可能需要它,如果這樣做意味着Simple Java Mail 無法簡化你的配置過程。
請讓我們知道如何幫助緩解這種需求。

Mailer mailer = new Mailer();

Session session = mailer.getSession();
// do your thing with session

用DKIM簽名電子郵件

Simple Java Mail還支持使用DKIM域密鑰進行簽名。 
它使用java-utils-mail-dkim(依賴性打包)來執行給定域上的DNS DKIM記錄檢查。

Email signedEmail = new Email();

signedEmail.signWithDomainKey(
   privateKey byte[] / File / InputStream,
   "your_domain.org",
   "your_selector");

new Mailer().sendMail(signedEmail);

配置傳送/讀取收據

對於支持它的服務器和客戶端(主要是Outlook),Simple Java Mail已經內置了“送貨收據”和“讀取收據”的支持,
這可以通過標題分別返回收貨和處理通知。

你可以明確定義電子郵件地址以將收據退回到或其他Simple Java Mail將默認爲replyTo地址(如果可用)或其他fromAddress。

Email email = new Email();
email.setUseDispositionNotificationTo();
email.setUseReturnReceiptTo();
// or:
email.setDispositionNotificationTo(new Recipient("name", "[email protected]"));
email.setReturnReceiptTo(new Recipient("name", "[email protected]"));

// or:
Email email = new EmailBuilder()
  (..)
  .withDispositionNotificationTo()
  .withReturnReceiptTo()
  // or:
  .withDispositionNotificationTo("[email protected]")
  .withReturnReceiptTo("name", "[email protected]")
  .build();

驗證郵箱地址

Simple Java Mail可以驗證你的郵箱地址。不是簡單的正則匹配,而是針對RFC-2822的完整和強大的完整驗證。 
它通過在庫中包含電子郵件-rfc2822驗證器來實現。


EmailAddressValidator.isValid("[email protected]",
   EmailAddressCriteria.RFC_COMPLIANT);

// or, fine-tuned to be less strict:
EmailAddressValidator.isValid("[email protected]",
   of(ALLOW_QUOTED_IDENTIFIERS, ALLOW_PARENS_IN_LOCALPART));

Email, MimeMessage, EML and Outlook .msg之間的轉換

使用Simple Java Mail你可以輕鬆裝換其他類型。
比如,如果你需要MimeMessage,你可以轉換Email,EML數據甚至Outlook .msg文件。

如果你已經有MimeMessage,您可以將它變成一個Email實例,其中包含嵌入圖像和附件,標題不變。

如果你喜歡,你甚至可以構建一個大量的Outlook .msg到EML轉換器!

// from Email
String eml =              EmailConverter.emailToEML(yourEmail);
MimeMessage mimeMessage = EmailConverter.emailToMimeMessage(yourEmail);
MimeMessage mimeMessage = EmailConverter.emailToMimeMessage(yourEmail, yourSession);

// from MimeMessage
Email email =             EmailConverter.mimeMessageToEmail(yourMimeMessage);
String eml =              EmailConverter.mimeMessageToEML(yourMimeMessage);

// from EML
Email email =             EmailConverter.emlToEmail(emlDataString);
MimeMessage mimeMessage = EmailConverter.emlToMimeMessage(emlDataString);
MimeMessage mimeMessage = EmailConverter.emlToMimeMessage(emlDataString, yourSession);

// from Outlook .msg
Email email =             EmailConverter.outlookMsgToEmail(readToString("yourMessage.msg"));
Email email =             EmailConverter.outlookMsgToEmail(new File("yourMessage.msg"));
Email email =             EmailConverter.outlookMsgToEmail(getInputStream("yourMessage.msg"));
String eml =              EmailConverter.outlookMsgToEML(readToString("yourMessage.msg"));
String eml =              EmailConverter.outlookMsgToEML(new File("yourMessage.msg"));
String eml =              EmailConverter.outlookMsgToEML(getInputStream("yourMessage.msg"));
MimeMessage mimeMessage = EmailConverter.outlookMsgToMimeMessage(readToString("yourMessage.msg"));
MimeMessage mimeMessage = EmailConverter.outlookMsgToMimeMessage(new File("yourMessage.msg"));
MimeMessage mimeMessage = EmailConverter.outlookMsgToMimeMessage(getInputStream("yourMessage.msg"));

使用代理髮送

Simple Java Mail支持通過代理髮送電子郵件。 它也是世界上唯一支持通過身份驗證的代理髮送電子郵件的Java郵件框架。

原因是底層本機Javax Mail框架支持匿名SOCKS5代理,但不支持身份驗證代理。

爲了使此工作通過身份驗證,Simple Java Mail使用一個技巧:它設置一個臨時匿名代理服務器爲Javax Mail連接到,
然後中繼連接到目標代理執行Javax Mail之外的身份驗證。

該臨時服務器稱爲代理橋接服務器。

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

// authenticated proxy
new Mailer(serverConfig, new ProxyConfig("proxy.host.com", 1080, "proxy username", "proxy password"));
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章