- JavaMail API 教程
- JavaMail - 首頁
- JavaMail API - 概述
- JavaMail - 環境設定
- JavaMail - 核心類
- JavaMail - 傳送郵件
- JavaMail - 檢查郵件
- JavaMail - 獲取郵件
- JavaMail - 身份驗證
- JavaMail - 回覆郵件
- JavaMail - 轉發郵件
- JavaMail - 刪除郵件
- JavaMail - Gmail SMTP 伺服器
- JavaMail - 資料夾管理
- JavaMail - 配額管理
- JavaMail - 退信
- JavaMail API 協議
- JavaMail - SMTP 伺服器
- JavaMail - IMAP 伺服器
- JavaMail - POP3 伺服器
- JavaMail API 有用資源
- JavaMail - 快速指南
- JavaMail - 有用資源
- JavaMail - 討論
JavaMail API - 獲取郵件
在上一章中,我們學習瞭如何檢查郵件。現在讓我們看看如何獲取每封郵件並讀取其內容。讓我們編寫一個 Java 類 **FetchingEmail**,它將讀取以下型別的郵件:
簡單的郵件
帶有附件的郵件
帶有內嵌影像的郵件
程式碼中遵循的基本步驟如下:
獲取 Session 物件。
建立 POP3 store 物件並連線到 store。
建立 Folder 物件並在您的郵箱中開啟相應的資料夾。
檢索郵件。
分別關閉 folder 和 store 物件。
建立 Java 類
建立一個名為 **FetchingEmail** 的 Java 類檔案,其內容如下所示:
package com.tutorialspoint;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
public class FetchingEmail {
public static void fetch(String pop3Host, String storeType, String user,
String password) {
try {
// create properties field
Properties properties = new Properties();
properties.put("mail.store.protocol", "pop3");
properties.put("mail.pop3.host", pop3Host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
// emailSession.setDebug(true);
// create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("pop3s");
store.connect(pop3Host, user, password);
// create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
writePart(message);
String line = reader.readLine();
if ("YES".equals(line)) {
message.writeTo(System.out);
} else if ("QUIT".equals(line)) {
break;
}
}
// close the store and folder objects
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String host = "pop.gmail.com";// change accordingly
String mailStoreType = "pop3";
String username =
"abc@gmail.com";// change accordingly
String password = "*****";// change accordingly
//Call method fetch
fetch(host, mailStoreType, username, password);
}
/*
* This method checks for content-type
* based on which, it processes and
* fetches the content of the message
*/
public static void writePart(Part p) throws Exception {
if (p instanceof Message)
//Call methos writeEnvelope
writeEnvelope((Message) p);
System.out.println("----------------------------");
System.out.println("CONTENT-TYPE: " + p.getContentType());
//check if the content is plain text
if (p.isMimeType("text/plain")) {
System.out.println("This is plain text");
System.out.println("---------------------------");
System.out.println((String) p.getContent());
}
//check if the content has attachment
else if (p.isMimeType("multipart/*")) {
System.out.println("This is a Multipart");
System.out.println("---------------------------");
Multipart mp = (Multipart) p.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++)
writePart(mp.getBodyPart(i));
}
//check if the content is a nested message
else if (p.isMimeType("message/rfc822")) {
System.out.println("This is a Nested Message");
System.out.println("---------------------------");
writePart((Part) p.getContent());
}
//check if the content is an inline image
else if (p.isMimeType("image/jpeg")) {
System.out.println("--------> image/jpeg");
Object o = p.getContent();
InputStream x = (InputStream) o;
// Construct the required byte array
System.out.println("x.length = " + x.available());
while ((i = (int) ((InputStream) x).available()) > 0) {
int result = (int) (((InputStream) x).read(bArray));
if (result == -1)
int i = 0;
byte[] bArray = new byte[x.available()];
break;
}
FileOutputStream f2 = new FileOutputStream("/tmp/image.jpg");
f2.write(bArray);
}
else if (p.getContentType().contains("image/")) {
System.out.println("content type" + p.getContentType());
File f = new File("image" + new Date().getTime() + ".jpg");
DataOutputStream output = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(f)));
com.sun.mail.util.BASE64DecoderStream test =
(com.sun.mail.util.BASE64DecoderStream) p
.getContent();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = test.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
else {
Object o = p.getContent();
if (o instanceof String) {
System.out.println("This is a string");
System.out.println("---------------------------");
System.out.println((String) o);
}
else if (o instanceof InputStream) {
System.out.println("This is just an input stream");
System.out.println("---------------------------");
InputStream is = (InputStream) o;
is = (InputStream) o;
int c;
while ((c = is.read()) != -1)
System.out.write(c);
}
else {
System.out.println("This is an unknown type");
System.out.println("---------------------------");
System.out.println(o.toString());
}
}
}
/*
* This method would print FROM,TO and SUBJECT of the message
*/
public static void writeEnvelope(Message m) throws Exception {
System.out.println("This is the message envelope");
System.out.println("---------------------------");
Address[] a;
// FROM
if ((a = m.getFrom()) != null) {
for (int j = 0; j < a.length; j++)
System.out.println("FROM: " + a[j].toString());
}
// TO
if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < a.length; j++)
System.out.println("TO: " + a[j].toString());
}
// SUBJECT
if (m.getSubject() != null)
System.out.println("SUBJECT: " + m.getSubject());
}
}
您可以透過取消註釋語句 `emailSession.setDebug(true);` 來開啟除錯。
編譯和執行
現在我們的類已經準備好了,讓我們編譯上面的類。我已經將 FetchingEmail.java 類儲存到目錄:**/home/manisha/JavaMailAPIExercise**。我們需要將 `javax.mail.jar` 和 `activation.jar` 加入到類路徑中。從命令提示符執行以下命令來編譯類(兩個 jar 包都放在 `/home/manisha/` 目錄中):
javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: FetchingEmail.java
現在類已經編譯好了,執行以下命令來執行:
java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: FetchingEmail
驗證輸出
您應該在命令控制檯中看到以下訊息:
messages.length---3 --------------------------------- This is the message envelope --------------------------- FROM: XYZ <xyz@gmail.com> TO: ABC <abc@gmail.com> SUBJECT: Simple Message ---------------------------- CONTENT-TYPE: multipart/alternative; boundary=047d7b343d6ad3e4ea04e8ec6579 This is a Multipart --------------------------- ---------------------------- CONTENT-TYPE: text/plain; charset=ISO-8859-1 This is plain text --------------------------- Hi am a simple message string.... -- Regards xyz This is the message envelope --------------------------- FROM: XYZ <xyz@gmail.com> TO: ABC <abc@gmail.com> SUBJECT: Attachement ---------------------------- CONTENT-TYPE: multipart/mixed; boundary=047d7b343d6a99180904e8ec6751 This is a Multipart --------------------------- ---------------------------- CONTENT-TYPE: text/plain; charset=ISO-8859-1 This is plain text --------------------------- Hi I've an attachment.Please check -- Regards XYZ ---------------------------- CONTENT-TYPE: application/octet-stream; name=sample_attachement This is just an input stream --------------------------- Submit your Tutorials, White Papers and Articles into our Tutorials Directory. This is a tutorials database where we are keeping all the tutorials shared by the internet community for the benefit of others. This is the message envelope --------------------------- FROM: XYZ <xyz@gmail.com> TO: ABC <abc@gmail.com> SUBJECT: Inline Image ---------------------------- CONTENT-TYPE: multipart/related; boundary=f46d04182582be803504e8ece94b This is a Multipart --------------------------- ---------------------------- CONTENT-TYPE: text/plain; charset=ISO-8859-1 This is plain text --------------------------- Hi I've an inline image [image: Inline image 3] -- Regards XYZ ---------------------------- CONTENT-TYPE: image/png; name="javamail-mini-logo.png" content typeimage/png; name="javamail-mini-logo.png"
在這裡您可以看到我們的郵箱中有三封郵件。第一封是一封簡單的郵件,郵件內容為“Hi am a simple message string....”。第二封郵件帶有一個附件。如上所示,附件的內容也會被打印出來。第三封郵件帶有一張內嵌影像。
廣告