POP3 서버에서 새 이메일 메시지 감지

POP3 계정에서는 다운로드 및 읽을 때 메시지를 서버에 남겨둘 수 있습니다. 서버에 이메일을 남겨두면 여러 장치에서 이메일에 액세스하는 사용자와 같은 다른 애플리케이션 및 개인이 해당 이메일을 사용할 수 있습니다. 또는 특정 조건(예: 특정 제목이 있는 메시지)에 맞는 메시지만 다운로드하려 할 수도 있습니다. 이메일을 관리하려면 다음을 수행할 수 있습니다;

  • Aspose.Email을 사용해 POP3 메일 서버에서 모든 메시지를 읽습니다.
  • 메시지를 로컬 데이터베이스에 다운로드합니다.

메시지는 삭제되지 않고 서버에 남아 있습니다. 처음 실행할 때는 이 프로세스가 정상적으로 작동하여 필요한 모든 메시지가 데이터베이스에 다운로드됩니다. 그러나 두 번째 실행 시에도 동일한 메시지가 여전히 이메일 서버에 남아 있기 때문에 다시 다운로드되어 중복 레코드가 발생합니다. 이 문제를 해결하려면 다음을 사용하십시오. Pop3MessageInfo.UniqueID 이미 다운로드된 메시지인지 확인하는 속성. 메시지의 고유 ID는 데이터베이스에 저장되어야 하며, 이는 새 메시지를 감지하기 위한 검색 키입니다.

새 메시지 감지

POP3 서버의 이메일 목록에서 새 이메일을 식별하려면:

  1. 서버에 연결합니다.
  2. 이메일 목록을 가져옵니다.
  3. 데이터베이스에 연결합니다.
  4. 이메일 목록을 가져옵니다.
  5. 목록을 비교합니다.
  6. 새 이메일을 데이터베이스에 저장합니다.

다음과 같은 경우 프로세스가 더 빠릅니다:

  1. 메시지의 모든 고유 ID를 해시 테이블에 가져옵니다.
  2. for(…) 루프에서 각 이메일 메시지에 대해 데이터베이스 대신 해시 테이블을 검색합니다.

각 메시지마다 데이터베이스를 조회하여 여러 번 호출하는 대신, 이 메서드는 한 번의 호출만 필요합니다. 다음 코드 스니펫은 POP3 서버에서 새 이메일 메시지를 감지하는 방법을 보여줍니다.

public static void run() {
    try {
        // Connect to the POP3 mail server and check messages.
        Pop3Client pop3Client = new Pop3Client("pop.domain.com", 993, "username", "password");

        // List all the messages
        Pop3MessageInfoCollection msgList = pop3Client.listMessages();
        for (Pop3MessageInfo msgInfo : msgList) {
            // Get the POP3 message's unique ID
            String strUniqueID = msgInfo.getUniqueId();

            // Search your local database or data store on the unique ID. If a match is found, that means it's already downloaded. Otherwise download and save it.
            if (searchPop3MsgInLocalDB(strUniqueID) == true) {
                // The message is already in the database. Nothing to do with this message. Go to next message.
            } else {
                // Save the message
                savePop3MsgInLocalDB(msgInfo);
            }
        }
    } catch (Exception ex) {
        System.err.println(ex);
    }

}

private static void savePop3MsgInLocalDB(Pop3MessageInfo msgInfo) {
    // Open the database connection according to your database. Use public properties (for example msgInfo.Subject) and store in database,
    // for example, " INSERT INTO POP3Mails (UniqueID, Subject) VALUES ('" + msgInfo.UniqueID + "' , '" + msgInfo.Subject + "') and Run the query to store in database.
}

private static boolean searchPop3MsgInLocalDB(String strUniqueID) {
    // Open the database connection according to your database. Use strUniqueID in the search query to find existing records,
    // for example, " SELECT COUNT(*) FROM POP3Mails WHERE UniqueID = '" + strUniqueID + "' Run the query, return true if count == 1. Return false if count == 0.
    return false;
}