서버에서 메시지 작업
사서함 정보 가져오기
메시지 수와 사서함 크기와 같은 사서함 정보를 다음을 사용하여 가져올 수 있습니다. getMailBoxSize 및 getMailBoxInfo 의 메서드 Pop3Client 클래스.
- 다음은 getMailBoxSize 메서드는 사서함의 크기를 바이트 단위로 반환합니다.
- 다음은 getMailBoxInfo 메서드는 타입의 객체를 반환합니다. Pop3MailBoxInfo.
다음 방법을 사용하여 메시지 수를 가져올 수도 있습니다. MessageCount 속성 및 크기를 사용하여 OccupiedSize 속성 Pop3MailBoxInfo 클래스. 다음 샘플 코드는 사서함 정보를 가져오는 방법을 보여줍니다. 다음과 같이:
- 다음을 생성합니다 Pop3Client.
- POP3 서버에 연결합니다.
- 사서함의 크기를 가져옵니다.
- 사서함 정보를 가져옵니다.
- 사서함의 메시지 수를 가져옵니다.
- 사용 중인 크기를 가져옵니다.
// 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);
사서함에서 이메일 수 가져오기
다음 코드 스니펫은 사서함에서 이메일 메시지 수를 계산하는 방법을 보여줍니다.
// 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은 개발자가 이메일을 다양한 방식으로 작업할 수 있도록 합니다. 예를 들어, 이메일을 다운로드할지 여부를 결정하기 전에 헤더 정보를 가져올 수 있습니다. 또는 서버에서 이메일을 가져와 파싱하지 않고 저장(빠르게)하거나 파싱한 후 저장(느리게)할 수 있습니다. 이 문서는 이메일을 검색하고 변환하는 방법을 보여줍니다.
이메일 헤더 정보 검색
이메일 헤더는 전체 이메일을 가져올지 여부를 판단하는 데 사용할 수 있는 이메일 메시지 정보를 제공합니다. 일반적으로 헤더 정보에는 발신자, 제목, 수신 날짜 등이 포함됩니다. (이메일 헤더에 대한 자세한 내용은 이메일 헤더 사용자 정의. 해당 주제는 SMTP를 사용한 이메일 전송에 관한 것이지만, 이메일 헤더 내용 정보는 POP3 이메일에도 유효합니다). 다음 예시는 메시지 순번으로 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 {
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();
}
이메일 메시지 검색
다음은 Pop3Client 클래스 구성 요소는 POP3 서버에서 이메일 메시지를 검색하고, 이를 a 로 파싱하는 기능을 제공합니다 MailMessage 도움을 받아 인스턴스 MailMessage 구성 요소. MailMessage 클래스는 이메일 내용을 조작하기 위한 여러 속성과 메서드를 포함합니다. 사용하면 fetchMessage 메서드 Pop3Client 클래스에서, 다음을 얻을 수 있습니다: MailMessage POP3 서버에서 직접 인스턴스를 가져옵니다. 다음 코드 스니펫은 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();
}
고유 ID를 사용한 메시지 요약 정보 가져오기
API의 POP3 클라이언트는 메시지의 고유 ID를 사용하여 서버에서 메시지 요약 정보를 가져올 수 있습니다. 이를 통해 전체 메시지를 먼저 가져오지 않고도 메시지의 간략 정보를 빠르게 접근할 수 있습니다. 다음 코드 스니펫은 메시지 요약 정보를 가져오는 방법을 보여줍니다.
// 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());
}
멀티 연결을 사용한 메시지 목록
Pop3Client 를 제공합니다. UseMultiConnection 무거운 작업을 위해 다중 연결을 생성하는 데 사용할 수 있는 속성입니다. 멀티연결 모드에서 사용할 연결 수는 다음을 사용하여 설정할 수 있습니다. Pop3Client.ConnectionsQuantity. 다음 코드 스니펫은 메시지 목록 작성을 위한 멀티 연결 모드 사용을 보여주며 단일 연결 모드와 성능을 비교합니다.
// 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);
서버에서 메시지를 가져와 디스크에 저장
파싱 없이 메시지를 디스크에 저장
POP3 서버에서 이메일을 파싱하지 않고 다운로드하려면, Pop3Client 클래스 saveMessage 함수. saveMessage 함수는 이메일을 파싱하지 않으므로 ~보다 빠릅니다. fetchMessage 함수. 다음 코드 스니펫은 시퀀스 번호(예: 1)를 사용해 메시지를 저장하는 방법을 보여줍니다. saveMessage 메서드는 메시지를 파싱하지 않고 원본 EML 형식으로 저장합니다.
// 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 ");
저장하기 전에 메시지 파싱
다음 코드 스니펫은 ~를 사용합니다. Pop3Client fetchMessage 시퀀스 번호로 POP3 서버에서 메시지를 가져와 제목을 파일 이름으로 사용해 디스크에 저장하는 메서드.
// 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();
}
그룹 메시지 가져오기
Pop3Client 를 제공합니다. fetchMessages 시퀀스 번호 또는 고유 ID의 iterable을 받아 리스트를 반환하는 메서드. MailMessage. 다음 코드 스니펫은 ~의 사용을 보여줍니다. fetchMessages 시퀀스 번호와 고유 ID로 메시지를 가져오는 메서드.
// 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());
}
발신자, 수신자 또는 날짜 기반 메시지 필터링
다음은 Pop3Client 클래스, 자세한 내용은 POP3 서버에 연결, 제공하는 listMessages 메서드는 사서함의 모든 메시지를 가져옵니다. 특정 조건에 일치하는 메시지만 얻으려면 오버로드된 메서드를 사용하십시오 listMessages 메서드는 ~를 받아들입니다 MailQuery 을 인수로 사용합니다. MailQuery 클래스는 날짜, 제목, 발신자, 수신자 등과 같은 쿼리 조건을 지정하기 위한 다양한 속성을 제공합니다. MailQueryBuilder 클래스는 검색 식을 구축하는 데 사용됩니다. 먼저 모든 조건과 제약을 설정하고 나서 MailQuery ~에 의해 개발된 쿼리로 채워집니다 MailQueryBuilder. The MailQuery 클래스 객체는 ~에 의해 사용됩니다 Pop3Client 서버에서 필터링된 정보를 추출합니다. 이 문서는 사서함에서 이메일 메시지를 필터링하는 방법을 보여줍니다. 첫 번째 예시는 날짜와 제목을 기준으로 메시지를 필터링하는 방법을 설명합니다. 또한 다른 기준으로 필터링하고 더 복잡한 쿼리를 구축하는 방법을 보여줍니다. 또한 날짜 및 시간 필터를 적용하여 사서함에서 특정 이메일을 검색하는 방법을 보여줍니다. 추가로 대소문자 구분 필터링 적용 방법도 설명합니다.
사서함에서 메시지 필터링
사서함에서 메시지를 필터링하려면:
- POP3 서버에 연결하고 로그인합니다.
- 다음의 인스턴스를 생성합니다 MailQuery 그리고 원하는 속성을 설정합니다.
- 다음을 호출합니다. Pop3Client.listMessages(MailQuery query) method에 전달하고 MailQuery 매개변수에 지정하여 필터링된 메시지만 가져옵니다.
다음 코드 스니펫은 POP3 사서함에 연결하고 오늘 도착한 메시지 중 제목에 "newsletter"가 포함된 메시지를 가져오는 방법을 보여줍니다.
// 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.");
특정 기준에 부합하는 메시지 가져오기
위의 코드 샘플 이메일 제목과 날짜를 기준으로 메시지를 필터링합니다. 다른 속성을 사용해 지원되는 조건을 설정할 수도 있습니다. 아래는 를 사용하여 조건을 설정하는 몇 가지 예시입니다. MailQuery.
다음 코드 스니펫은 다른 기준으로 이메일을 필터링하는 방법을 보여줍니다:
- 오늘 전달된 이메일을 찾습니다.
- 특정 기간 내에 수신된 이메일을 찾습니다.
- 특정 발신자의 이메일을 찾습니다.
- 특정 도메인에서 보낸 이메일을 찾습니다.
- 특정 수신자에게 보낸 이메일을 찾습니다.
오늘 날짜
다음 코드 스니펫은 오늘 전달된 이메일을 찾는 방법을 보여줍니다.
// 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());
날짜 범위
다음 코드 스니펫은 특정 기간 내에 수신된 이메일을 찾는 방법을 보여줍니다.
// 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());
특정 발신자
다음 코드 스니펫은 특정 발신자에게서 온 이메일을 찾는 방법을 보여줍니다.
// 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");
특정 도메인
다음 코드 스니펫은 특정 도메인에서 보낸 이메일을 찾는 방법을 보여줍니다.
// 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");
특정 수신자
다음 코드 스니펫은 특정 수신자에게 보낸 이메일을 찾는 방법을 보여줍니다.
// 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");
복잡한 쿼리 구축
다른 경우 MailQueryBuilder 속성을 별도의 문장으로 설정하면 모든 조건이 일치합니다. 예를 들어, 날짜 범위와 특정 호스트에서 온 메시지를 가져오려면 세 개의 문장을 작성해야 합니다.
AND로 쿼리 결합
다음 코드 스니펫은 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());
OR로 쿼리 결합
MailQueryBuilder 제공합니다 또는 두 개를 받는 메서드 MailQuery 인스턴스를 매개변수로 전달합니다. 지정된 두 조건 중 하나에 일치하는 메시지를 가져옵니다. 다음 코드 스니펫은 제목에 "test"가 있거나 발신자가 "noreply@host.com"인 메시지를 필터링하는 방법을 보여줍니다. 다음 코드 스니펫은 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"));
대소문자 구분 필터 적용
API는 또한 대소문자 구분 기준에 따라 사서함의 이메일을 필터링하는 기능을 제공합니다. 다음 메서드들은 대소문자 구분 플래그를 지정하여 이메일을 검색할 수 있는 기능을 제공합니다.
- 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);