Làm việc với Tin nhắn từ Máy chủ
Lấy thông tin Hộp thư
Chúng ta có thể lấy thông tin về hộp thư như số lượng tin nhắn và kích thước hộp thư bằng cách sử dụng getMailBoxSize và getMailBoxInfo phương thức của Pop3Client lớp.
- Cái getMailBoxSize phương thức trả về kích thước của hộp thư tính bằng byte.
- Cái getMailBoxInfo phương thức trả về một đối tượng kiểu Pop3MailBoxInfo.
Cũng có thể lấy số lượng tin nhắn bằng cách sử dụng MessageCount thuộc tính và kích thước bằng cách sử dụng OccupiedSize thuộc tính của Pop3MailBoxInfo lớp. Đoạn mã mẫu sau cho thấy cách lấy thông tin về hộp thư. Nó cho thấy cách:
- Tạo một Pop3Client.
- Kết nối đến máy chủ POP3.
- Lấy kích thước của hộp thư.
- Lấy thông tin hộp thư.
- Lấy số lượng tin nhắn trong hộp thư.
- Lấy kích thước đã chiếm.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
Pop3Client client = new Pop3Client();
// Specify host, username, password, Port and SecurityOptions for your client
client.setHost("pop.gmail.com");
client.setUsername("your.username@gmail.com");
client.setPassword("your.password");
client.setPort(995);
client.setSecurityOptions(SecurityOptions.Auto);
// Get the size of the mailbox, Get mailbox info, number of messages in the mailbox
long nSize = client.getMailboxSize();
System.out.println("Mailbox size is " + nSize + " bytes.");
Pop3MailboxInfo info = client.getMailboxInfo();
int nMessageCount = info.getMessageCount();
System.out.println("Number of messages in mailbox are " + nMessageCount);
long nOccupiedSize = info.getOccupiedSize();
System.out.println("Occupied size is " + nOccupiedSize);
Lấy số lượng Email trong Hộp thư
Đoạn mã sau cho bạn thấy cách đếm số tin nhắn email trong hộp thư.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
Pop3Client client = new Pop3Client("pop3.server.com", "username", "password");
try {
client.setSecurityOptions(SecurityOptions.Auto);
int i = client.getMessageCount();
System.out.println("Message count: " + i);
} catch (Pop3Exception ex) {
System.out.println("Error:" + ex.toString());
}
Aspose.Email cho phép các nhà phát triển làm việc với email theo nhiều cách khác nhau. Ví dụ, họ có thể lấy thông tin tiêu đề trước khi quyết định tải xuống một email. Hoặc họ có thể lấy email từ máy chủ và lưu chúng mà không cần phân tích (nhanh hơn) hoặc sau khi phân tích (chậm hơn). Bài viết này cho thấy cách lấy và chuyển đổi email.
Truy xuất thông tin tiêu đề Email
Tiêu đề email có thể cung cấp cho chúng ta thông tin về một tin nhắn email mà chúng ta có thể dùng để quyết định có nên lấy toàn bộ tin nhắn email hay không. Thông thường, thông tin tiêu đề bao gồm người gửi, chủ đề, ngày nhận, v.v. (Tiêu đề email được mô tả chi tiết trong Tùy chỉnh tiêu đề Email. Chủ đề đó cụ thể nói về việc gửi email bằng SMTP, nhưng thông tin nội dung tiêu đề email vẫn áp dụng cho email POP3). Các ví dụ sau cho thấy cách lấy tiêu đề email từ máy chủ POP3 bằng số thứ tự tin nhắn.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create an instance of the Pop3Client class
Pop3Client client = new Pop3Client();
// Specify host, username. password, Port and SecurityOptions for your client
client.setHost("pop.gmail.com");
client.setUsername("your.username@gmail.com");
client.setPassword("your.password");
client.setPort(995);
client.setSecurityOptions(SecurityOptions.Auto);
try {
HeaderCollection headers = client.getMessageHeaders(1);
for (int i = 0; i < headers.size(); i++) {
// Display key and value in the header collection
System.out.print(headers.getKey(i));
System.out.print(" : ");
System.out.println(headers.get(i));
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
client.dispose();
}
Truy xuất tin nhắn Email
Cái Pop3Client thành phần lớp cung cấp khả năng truy xuất các tin nhắn email từ máy chủ POP3 và phân tích chúng thành một MailMessage đối tượng với sự giúp đỡ của MailMessage thành phần. The MailMessage lớp chứa nhiều thuộc tính và phương thức để thao tác nội dung email. Bằng cách sử dụng fetchMessage phương thức của Pop3Client lớp, bạn có thể nhận được một MailMessage được lấy trực tiếp từ máy chủ POP3. Đoạn mã dưới đây cho bạn thấy cách lấy một email đầy đủ từ máy chủ POP3.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create an instance of the Pop3Client class
Pop3Client client = new Pop3Client();
// Specify host, username, password, Port and SecurityOptions for your client
client.setHost("pop.gmail.com");
client.setUsername("your.username@gmail.com");
client.setPassword("your.password");
client.setPort(995);
client.setSecurityOptions(SecurityOptions.Auto);
try {
int messageCount = client.getMessageCount();
// Create an instance of the MailMessage class and Retrieve message
MailMessage message;
for (int i = 1; i <= messageCount; i++) {
message = client.fetchMessage(i);
System.out.println("From:" + message.getFrom());
System.out.println("Subject:" + message.getSubject());
System.out.println(message.getHtmlBody());
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
client.dispose();
}
Lấy Thông tin Tóm tắt Tin nhắn bằng Id duy nhất
Client POP3 của API có thể lấy thông tin tóm tắt tin nhắn từ máy chủ bằng cách sử dụng ID duy nhất của tin nhắn. Điều này cung cấp truy cập nhanh tới thông tin ngắn gọn của tin nhắn mà không cần phải lấy toàn bộ tin nhắn từ máy chủ. Đoạn mã dưới đây cho bạn thấy cách lấy thông tin tóm tắt tin nhắn.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String uniqueId = "unique id of a message from server";
Pop3Client client = new Pop3Client("host.domain.com", 456, "username", "password");
client.setSecurityOptions(SecurityOptions.Auto);
Pop3MessageInfo messageInfo = client.getMessageInfo(uniqueId);
if (messageInfo != null) {
System.out.println(messageInfo.getSubject());
System.out.println(messageInfo.getDate());
}
Liệt kê Tin nhắn với MultiConnection
Pop3Client cung cấp một UseMultiConnection thuộc tính có thể được sử dụng để tạo nhiều kết nối cho các thao tác nặng. Bạn cũng có thể đặt số lượng kết nối sẽ được sử dụng trong chế độ đa kết nối bằng cách sử dụng Pop3Client.ConnectionsQuantity. Đoạn mã dưới đây minh họa việc sử dụng chế độ đa kết nối để liệt kê tin nhắn và so sánh hiệu năng với chế độ kết nối đơn.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create an instance of the Pop3Client class
Pop3Client pop3Client = new Pop3Client();
pop3Client.setHost("<HOST>");
pop3Client.setPort(995);
pop3Client.setUsername("<USERNAME>");
pop3Client.setPassword("<PASSWORD>");
pop3Client.setConnectionsQuantity(5);
pop3Client.setUseMultiConnection(MultiConnectionMode.Enable);
long multiConnectionModeStartTime = System.currentTimeMillis();
Pop3MessageInfoCollection messageInfoCol1 = pop3Client.listMessages();
long multiConnectionModeTimeSpan = System.currentTimeMillis() - multiConnectionModeStartTime;
pop3Client.setUseMultiConnection(MultiConnectionMode.Disable);
long singleConnectionModeStartTime = System.currentTimeMillis();
Pop3MessageInfoCollection messageInfoCol2 = pop3Client.listMessages();
long singleConnectionModeTimeSpan = System.currentTimeMillis() - singleConnectionModeStartTime;
System.out.println("multyConnectionModeTimeSpan: " + multiConnectionModeTimeSpan);
System.out.println("singleConnectionModeTimeSpan: " + singleConnectionModeTimeSpan);
double performanceRelation = singleConnectionModeTimeSpan / multiConnectionModeTimeSpan;
System.out.println("Performance Relation: " + performanceRelation);
Lấy tin nhắn từ máy chủ và lưu vào đĩa
Lưu tin nhắn vào đĩa mà không phân tích
Nếu bạn muốn tải xuống các tin nhắn email từ máy chủ POP3 mà không phân tích chúng, hãy sử dụng Pop3Client lớp saveMessage hàm. Các saveMessage hàm không phân tích tin nhắn email nên nhanh hơn so với fetchMessage hàm. Đoạn mã sau cho thấy cách lưu một tin nhắn theo số thứ tự của nó, trong trường hợp này là số 1. Các saveMessage phương thức lưu tin nhắn ở định dạng EML nguyên gốc mà không phân tích.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the File directory.
String dataDir = "pop3/";
String dstEmail = dataDir + "InsertHeaders.eml";
// Create an instance of the Pop3Client class
Pop3Client client = new Pop3Client();
// Specify host, username, password, Port and SecurityOptions for your client
client.setHost("pop.gmail.com");
client.setUsername("your.username@gmail.com");
client.setPassword("your.password");
client.setPort(995);
client.setSecurityOptions(SecurityOptions.Auto);
try {
// Save message to disk by message sequence number
client.saveMessage(1, dstEmail);
client.dispose();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
System.out.println("Retrieved email messages using POP3 ");
Phân tích tin nhắn trước khi lưu
Đoạn mã sau sử dụng Pop3Client fetchMessage phương thức để lấy một tin nhắn từ máy chủ POP3 bằng số thứ tự của nó, sau đó lưu tin nhắn vào đĩa sử dụng tiêu đề làm tên tệp.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the File directory.
String dataDir = "pop3/";
// Create an instance of the Pop3Client class
Pop3Client client = new Pop3Client();
// Specify host, username and password, Port and SecurityOptions for your client
client.setHost("pop.gmail.com");
client.setUsername("your.username@gmail.com");
client.setPassword("your.password");
client.setPort(995);
client.setSecurityOptions(SecurityOptions.Auto);
try {
// Fetch the message by its sequence number and Save the message using its subject as the file name
MailMessage msg = client.fetchMessage(1);
msg.save(dataDir + "first-message_out.eml", SaveOptions.getDefaultEml());
client.dispose();
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
client.dispose();
}
Lấy nhiều tin nhắn nhóm
Pop3Client cung cấp một fetchMessages phương thức nhận một iterable của Số thứ tự hoặc ID duy nhất và trả về một danh sách của MailMessage. Đoạn mã sau minh họa việc sử dụng fetchMessages phương thức để lấy tin nhắn bằng Số thứ tự và ID duy nhất.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create an instance of the Pop3Client class
Pop3Client pop3Client = new Pop3Client();
pop3Client.setHost("<HOST>");
pop3Client.setPort(995);
pop3Client.setUsername("<USERNAME>");
pop3Client.setPassword("<PASSWORD>");
Pop3MessageInfoCollection messageInfoCol = pop3Client.listMessages();
System.out.println("ListMessages Count: " + messageInfoCol.size());
List<Integer> sequenceNumberAr = new ArrayList<Integer>();
List<String> uniqueIdAr = new ArrayList<String>();
for (Pop3MessageInfo mi : messageInfoCol) {
sequenceNumberAr.add(mi.getSequenceNumber());
uniqueIdAr.add(mi.getUniqueId());
}
for (MailMessage m : pop3Client.fetchMessagesBySequences(sequenceNumberAr)) {
System.out.println("FetchMessages-sequenceNumberAr : " + m.getSubject());
}
for (MailMessage m : pop3Client.fetchMessagesByUids(uniqueIdAr)) {
System.out.println("FetchMessages-uniqueIdAr : " + m.getSubject());
}
Lọc tin nhắn theo Người gửi, Người nhận hoặc Ngày
Cái Pop3Client lớp, được mô tả trong Kết nối tới Máy chủ POP3, cung cấp listMessages phương thức lấy tất cả các tin nhắn từ một hộp thư. Để chỉ lấy các tin nhắn phù hợp với một số điều kiện, sử dụng phiên bản quá tải của listMessages phương thức nhận MailQuery được truyền làm đối số. Các MailQuery lớp cung cấp nhiều thuộc tính để chỉ định các điều kiện truy vấn, ví dụ: ngày, tiêu đề, người gửi, người nhận, v.v. Các MailQueryBuilder lớp được sử dụng để xây dựng biểu thức tìm kiếm. Đầu tiên, tất cả các điều kiện và ràng buộc được đặt và sau đó MailQuery được điền bằng truy vấn được phát triển bởi MailQueryBuilder. Thuộc tính MailQuery đối tượng lớp được sử dụng bởi Pop3Client để trích xuất thông tin đã lọc từ máy chủ. Bài viết này cho thấy cách lọc các tin nhắn email từ một hộp thư. Ví dụ đầu tiên minh họa cách lọc tin nhắn dựa trên ngày và tiêu đề. Chúng tôi cũng cho thấy cách lọc theo các tiêu chí khác và cách xây dựng các truy vấn phức tạp hơn. Nó cũng trình bày việc áp dụng bộ lọc ngày và thời gian để lấy các email cụ thể từ hộp thư. Ngoài ra, nó còn chỉ cách áp dụng bộ lọc phân biệt chữ hoa chữ thường.
Lọc tin nhắn từ Hộp thư
Để lọc tin nhắn từ hộp thư:
- Kết nối và đăng nhập vào máy chủ POP3.
- Tạo một thể hiện của MailQuery và đặt các thuộc tính mong muốn.
- Gọi Pop3Client.listMessages(MailQuery query) phương thức và truyền vào MailQuery trong các tham số để chỉ lấy các tin nhắn đã lọc.
Đoạn mã sau cho bạn thấy cách kết nối tới hộp thư POP3 và lấy các tin nhắn đã đến hôm nay và có từ "newsletter" trong tiêu đề.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Connect and log in to POP3
String host = "host";
int port = 110;
String username = "user@host.com";
String password = "password";
Pop3Client client = new Pop3Client(host, port, username, password);
// Set conditions, Subject contains "Newsletter", Emails that arrived today
MailQueryBuilder builder = new MailQueryBuilder();
builder.getSubject().contains("Newsletter");
builder.getInternalDate().on(new Date());
// Build the query and Get list of messages
MailQuery query = builder.getQuery();
Pop3MessageInfoCollection messages = client.listMessages(query);
System.out.println("Pop3: " + messages.size() + " message(s) found.");
Lấy các tin nhắn đáp ứng tiêu chí cụ thể
Các mẫu mã ở trên lọc tin nhắn dựa trên tiêu đề email và ngày. Chúng ta cũng có thể sử dụng các thuộc tính khác để đặt các điều kiện hỗ trợ khác. Dưới đây là một số ví dụ về việc thiết lập các điều kiện bằng cách sử dụng MailQuery.
Các đoạn mã sau cho thấy cách lọc email theo các tiêu chí khác:
- Tìm email được gửi hôm nay.
- Tìm email nhận được trong một khoảng thời gian.
- Tìm email từ người gửi cụ thể.
- Tìm email được gửi từ miền cụ thể.
- Tìm email được gửi tới người nhận cụ thể.
Ngày hôm nay
Đoạn mã sau cho bạn thấy cách tìm email được gửi hôm nay.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Emails that arrived today
MailQueryBuilder builder = new MailQueryBuilder();
builder.getInternalDate().on(new Date());
Khoảng ngày
Đoạn mã sau cho bạn thấy cách tìm email nhận được trong một khoảng thời gian.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Emails that arrived in last 7 days
Calendar calendar = Calendar.getInstance();
builder.getInternalDate().before(calendar.getTime());
calendar.add(Calendar.DATE, -7);
builder.getInternalDate().since(calendar.getTime());
Người gửi cụ thể
Đoạn mã sau cho bạn thấy cách tìm email từ người gửi cụ thể.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Get emails from specific sender
builder.getFrom().contains("saqib.razzaq@127.0.0.1");
Miền cụ thể
Đoạn mã sau cho bạn thấy cách tìm email được gửi từ một miền cụ thể.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Get emails from specific domain
builder.getFrom().contains("SpecificHost.com");
Người nhận cụ thể
Đoạn mã sau cho bạn thấy cách tìm email được gửi đến người nhận cụ thể.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Get emails sent to specific recipient
builder.getTo().contains("recipient");
Xây Dựng Truy Vấn Phức Tạp
Nếu khác MailQueryBuilder các thuộc tính được đặt trong các câu lệnh riêng biệt, sau đó mọi điều kiện sẽ được khớp. Ví dụ, nếu chúng ta muốn lấy tin nhắn trong một khoảng thời gian và từ một máy chủ cụ thể, chúng ta cần viết ba câu lệnh.
Kết Hợp Truy Vấn với AND
Đoạn mã sau cho bạn thấy cách kết hợp các truy vấn bằng AND.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Emails from specific host, get all emails that arrived before today and all emails that arrived since 7 days ago
builder.getFrom().contains("SpecificHost.com");
Calendar calendar = Calendar.getInstance();
builder.getInternalDate().before(calendar.getTime());
calendar.add(Calendar.DATE, -7);
builder.getInternalDate().since(calendar.getTime());
Kết Hợp Truy Vấn với OR
MailQueryBuilder cung cấp hoặc phương thức nhận hai MailQuery các thể hiện làm tham số. Nó lấy những tin nhắn phù hợp với bất kỳ một trong hai điều kiện đã chỉ định. Đoạn mã sau cho thấy cách lọc tin nhắn mà trong tiêu đề có "test" hoặc người gửi là "noreply@host.com". Đoạn mã sau cho bạn thấy cách kết hợp các truy vấn bằng OR.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Specify OR condition
builder.or(builder.getSubject().contains("test"), builder.getFrom().contains("noreply@host.com"));
Áp dụng bộ lọc phân biệt chữ hoa chữ thường
API cũng cung cấp khả năng lọc email từ hộp thư dựa trên tiêu chí phân biệt chữ hoa chữ thường. Các phương thức sau cung cấp khả năng tìm kiếm email bằng cách chỉ định cờ phân biệt chữ hoa chữ thường.
- Method StringComparisonField.contains(String value, boolean ignoreCase)
- Method StringComparisonField.equals(String value, boolean ignoreCase)
- Method StringComparisonField.notContains(String boolean, bool ignoreCase)
- Method StringComparisonField.notEquals(String boolean, bool ignoreCase)
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// IgnoreCase is True
MailQueryBuilder builder1 = new MailQueryBuilder();
builder1.getFrom().contains("tesT", true);
MailQuery query1 = builder1.getQuery();
Pop3MessageInfoCollection messageInfoCol1 = client.listMessages(query1);