在Java SE平臺之外(但包含在JavaEE中), JavaMail軟件包提供了一個用于構建郵件和消息傳遞應用程序的平臺。 讓我們舉一個例子。
發送一條簡單的短信
// Common variables
String host = "your_smtp_server";
String from = "from_address";
String to = "to_address";// Set properties
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.debug", "true");// Get session
Session session = Session.getInstance(props);try {// Instantiate a messageMessage msg = new MimeMessage(session);// Set the FROM messagemsg.setFrom(new InternetAddress(from));// The recipients can be more than one so we use an array but you can// use 'new InternetAddress(to)' for only one address.InternetAddress[] address = {new InternetAddress(to)};msg.setRecipients(Message.RecipientType.TO, address);// Set the message subject and date we sent it.msg.setSubject("Email from JavaMail test");msg.setSentDate(new Date());// Set message contentmsg.setText("This is the text for this simple demo using JavaMail.");// Send the messageTransport.send(msg);
}
catch (MessagingException mex) {mex.printStackTrace();
}
或者,改為使用:
msg.setText("This is the text for this simple demo using JavaMail.");
您可以使用next設置消息內容:
msg.setContent("This is the text for this simple demo using JavaMail.", "text/plain");
檢查電子郵件地址
這是一個使用正則表達式檢查電子郵件格式是否正確的小技巧:
Pattern rfc2822 = Pattern.compile("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$");
if(rfc2822.matcher(EMAIL_ADDRESS).matches()) {// Well formed email
}
多部分消息
很好,但是通常您不會發送簡單的短信。 相反,您發送帶有粗體或斜體文本,圖像等的漂亮HTML正文消息。
注意:請參閱下面的“參考”部分,以了解有關MIME格式的信息,該格式擴展了您可以附加到電子郵件的數據的范圍,以允許多部分,附件等。
編寫多部分消息時,內容由不同部分組成,例如,一部分是作為簡單文本編寫的消息,另一部分是使用HTML以增強方式編寫的同一消息。 然后,讀取消息的客戶端負責根據其功能來渲染適當的部分。
...
// Here create two parts and set as message contect
// Create and fill first part
MimeBodyPart part1 = new MimeBodyPart();
part1.setText("This is part one of this multipart message.");// Create and fill second part
MimeBodyPart part2 = new MimeBodyPart();
part2.setText("This is part two of this multipart message.");// Create the Multipart.
Multipart mp = new MimeMultipart();
mp.addBodyPart(part1);
mp.addBodyPart(part2);// Set the message's content
msg.setContent(mp);
...
發送附件
太棒了,我們知道如何發送純文本電子郵件以及更令人難以置信的內容,例如包含HTML內容的多部分消息。 下一步是發送附加了太多文件的電子郵件。
創建帶有附件的電子郵件類似于創建多部分郵件,其中一部分可以是郵件的文本,另一部分可以是附件。 秘密在接下來的幾行中:
...
// Create a new part for the attached file
MimeBodyPart part3 = new MimeBodyPart();// Put a file in the second part
FileDataSource fds = new FileDataSource("THE_FILE_NAME");
part3.setDataHandler(new DataHandler(fds));
part3.setFileName(fds.getName());// 'mp' is the previously created 'MimeMultipart' object
mp.addBodyPart(part3);// 'msg' is the previously created 'Message' object
msg.setContent(mp);
...
HTML消息
創建帶有HTML內容的多部分消息非常簡單,只需在setContent方法中指定MIME類型即可:
...
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<h1>Sample</h1><p>This is a sample HTML part</p>", "text/html");
...
在HTML代碼中附加圖像
如果您使用HTML編寫豐富的消息,則可以使用'img'標簽添加圖像。 如果從外部服務器引用了圖像,則沒有問題,但是:如何將圖像附加到消息并在HTML消息正文中進行呈現?
想法如下:
- 首先,您需要附加圖片文件并設置一個標識符,然后
- 其次,您需要編寫HTML代碼并在“ img”標簽中引用圖片標識符。
...
// Create and fill html part
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<h1>Sample</h1><p>This is a sample HTML part with an attached image</p>" +"<img src='cid:some_image_id'>", "text/html");// Create a new part for the attached image and set the CID image identifier
MimeBodyPart imagePart = new MimeBodyPart();
FileDataSource fds = new FileDataSource("THE_IMAGE_FILE_NAME");
imagePart.setDataHandler(new DataHandler(fds));
imagePart.setHeader("Content-ID", "some_image_id");mp.addBodyPart(htmlPart);
mp.addBodyPart(imagePart);
...
還有什么要說的嗎?
至此,您幾乎是發送電子郵件的高手。 您知道如何發送簡單的電子郵件,具有最豐富HTML內容的多部分電子郵件以及如何在郵件中附加文件和圖像。
程序員還能期望什么?
可能是更易于使用的API,這就是Apache Commons Email項目為您提供的。 請參閱“用戶指南”部分http://commons.apache.org/email/userguide.html以了解我的意思。 它提供了一個更抽象的API,它比協議更接近人類。
資源資源
- JavaMail – JavaMail項目主頁。
- Apache Commons Email – Apache Commons子項目,用于簡化JavaMail API的使用方式。 請參閱“ 用戶指南 ”部分。
- MIME(多用途Internet郵件擴展名) –多部分電子郵件的MIME格式說明。
參考:在“ A Curious Animal”博客上從我們的JCG合作伙伴 Antonio Santiago 發送Java電子郵件 。
- Spring,Quartz和JavaMail集成教程
- 使用Spring使用Java發送電子郵件– GMail SMTP服務器示例
- Spring MVC3 Hibernate CRUD示例應用程序
- Spring MVC開發–快速教程
- Java教程和Android教程列表
翻譯自: https://www.javacodegeeks.com/2011/10/sending-emails-with-java.html