IMAP 서버에 연결

다음은 ImapClient 클래스는 애플리케이션이 IMAP 프로토콜을 사용하여 IMAP 메일함을 관리하도록 허용합니다. ImapClient 클래스는 IMAP 메일 서버에 연결하고 IMAP 이메일 폴더에서 이메일을 관리하는 데 사용됩니다. IMAP 서버에 연결하려면

  1. 다음의 인스턴스를 생성합니다. ImapClient 클래스.
  2. 호스트 이름, 사용자 이름 및 비밀번호를 지정합니다 ImapClient constructor.

일단 ImapClient 인스턴스가 초기화되면, 이 인스턴스를 사용한 다음 호출은 서버에 연결됩니다. 다음 코드 스니펫은 위 단계들을 사용하여 IMAP 서버에 연결하는 방법을 보여줍니다.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create an imapclient with host, user and password
ImapClient client = new ImapClient("localhost", "user", "password");

SSL이 활성화된 IMAP 서버와 연결

IMAP 서버와 연결 IMAP 서버에 연결하는 네 단계에 대해 설명했습니다:

  1. 다음의 인스턴스를 생성합니다. ImapClient 클래스.
  2. 호스트 이름, 사용자 이름 및 비밀번호를 지정합니다.
  3. 포트를 지정합니다.
  4. 지정하세요 보안 옵션.

SSL이 활성화된 IMAP 서버에 연결하는 과정은 유사하지만 몇 개의 추가 속성을 설정해야 합니다:

다음 코드 스니펫은 방법을 보여줍니다

  1. 사용자 이름, 비밀번호 및 포트를 설정합니다.
  2. 보안 옵션 설정.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create an instance of the ImapClient class
ImapClient client = new ImapClient("imap.domain.com", 993, "user@domain.com", "pwd");

// Set the security mode to implicit
client.setSecurityOptions(SecurityOptions.SSLImplicit);

프록시를 통해 서버에 연결

프록시 서버는 외부와 통신할 때 일반적으로 사용됩니다. 이러한 경우 메일 클라이언트는 프록시 주소를 지정하지 않으면 인터넷에 접속할 수 없습니다. Aspose.Email은 SOCKS 프록시 프로토콜 버전 4, 4a 및 5를 지원합니다. 이 문서는 프록시 메일 서버를 사용하여 메일함에 접근하는 작동 예제를 제공합니다. 프록시 서버를 통해 메일함에 접근하려면:

  1. 초기화 SocksProxy 필수 정보인 프록시 주소, 포트 및 SOCKS 버전을 지정합니다.
  2. 초기화 ImapClient 호스트 주소, 사용자 이름, 비밀번호 및 기타 설정과 함께.
  3. 클라이언트를 설정합니다 SocksProxy 속성을 SocksProxy 위에서 생성된 객체.

다음 코드 스니펫은 프록시 서버를 통해 메일함을 검색하는 방법을 보여줍니다.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Connect and log in to IMAP and set SecurityOptions
ImapClient client = new ImapClient("imap.domain.com", "username", "password");
client.setSecurityOptions(SecurityOptions.Auto);

String proxyAddress = "192.168.203.142"; // proxy address
int proxyPort = 1080; // proxy port
SocksProxy proxy = new SocksProxy(proxyAddress, proxyPort, SocksVersion.SocksV5);

// Set the proxy
client.setProxy(proxy);

try {
    client.selectFolder("Inbox");
} catch (java.lang.RuntimeException ex) {
    System.out.println(ex.getMessage());
}

HTTP 프록시를 통한 서버 연결

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
HttpProxy proxy = new HttpProxy("18.222.124.59", 8080);
final ImapClient client = new ImapClient("imap.domain.com", "username", "password");
try {
    client.setProxy(proxy);
    client.selectFolder("Inbox");
} finally {
    if (client != null)
        client.dispose();
}

인증 메커니즘 맞춤 설정

IMAP 서버가 지원하는 인증 메커니즘 목록을 를 사용하여 검색합니다 getSupportedAuthentication 메서드 ImapClient 클래스. 이 메서드는 클라이언트가 서버와 보안 연결을 수립하는 데 사용할 수 있는 인증 방법을 확인하도록 허용합니다. 그런 다음, setAllowedAuthentication 사용자가 허용한 인증 유형 열거형을 가져오거나(또는 설정하는) 메서드로, 클라이언트-서버 통신에 가장 적합한 인증 메커니즘을 선택합니다. 이를 통해 메일 클라이언트의 인증 방법을 명시적으로 설정할 수 있습니다.

다음 코드 샘플은 이메일 클라이언트 인증을 커스터마이즈하는 방법을 보여줍니다:

imapClient.setAllowedAuthentication(ImapKnownAuthenticationType.Plain);

읽기 전용 모드로 서버에 연결

다음은 ImapClient 클래스는 ReadOnly 속성으로, true 로 설정하면 메일함의 영구 상태에 변경이 없어야 함을 나타냅니다. 다음 코드 샘플은 사용법을 보여줍니다 ImapClient.ReadOnly 속성입니다. 읽지 않은 메시지 수를 가져온 다음 하나의 메시지를 가져오고, 읽기 전용 모드에서 다시 읽지 않은 메시지 수를 가져옵니다. 읽지 않은 메시지 수가 동일하게 유지되어 메일함의 영구 상태가 변경되지 않았음을 나타냅니다.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
ImapClient imapClient = new ImapClient();
imapClient.setHost("<HOST>");
imapClient.setPort(993);
imapClient.setUsername("<USERNAME>");
imapClient.setPassword("<PASSWORD>");
imapClient.setSupportedEncryption(EncryptionProtocols.Tls);
imapClient.setSecurityOptions(SecurityOptions.SSLImplicit);

ImapQueryBuilder imapQueryBuilder = new ImapQueryBuilder();
imapQueryBuilder.hasNoFlags(ImapMessageFlags.isRead()); /* get unread messages. */
MailQuery query = imapQueryBuilder.getQuery();

imapClient.setReadOnly(true);
imapClient.selectFolder("Inbox");
ImapMessageInfoCollection messageInfoCol = imapClient.listMessages(query);
System.out.println("Initial Unread Count: " + messageInfoCol.size());
if (messageInfoCol.size() > 0) {
    imapClient.fetchMessage(messageInfoCol.get_Item(0).getSequenceNumber());

    messageInfoCol = imapClient.listMessages(query);
    // This count will be equal to the initial count
    System.out.println("Updated Unread Count: " + messageInfoCol.size());
} else {
    System.out.println("No unread messages found");
}

서버에 연결하기 위해 CRAM-MD5 인증 사용

IMAP 서버와의 안전한 인증 및 통신을 보장하기 위해, IMAP 클라이언트에 허용되는 인증 방법으로 CRAM-MD5 사용을 지정하고 적용할 수 있습니다. 다음 코드 스니펫은 허용된 인증 유형을 구성하는 방법을 보여줍니다. ImapClient:

imapClient.setAllowedAuthentication(ImapKnownAuthenticationType.CramMD5);

이메일 전송 없이 메일 서버 자격 증명 검증

때때로 이메일을 보내지 않고 자격 증명을 확인해야 할 필요가 있습니다. Aspose.Email은 이를 제공합니다 validateCredentials() method를 사용해 이 작업을 수행합니다. 검증이 성공하면 if 문 내부의 코드가 실행되며, 일반적으로 추가 작업을 수행하거나 IMAP 서버에서 데이터를 가져오는 데 사용됩니다. 다음 코드 스니펫은 이메일을 보내지 않고 자격 증명을 검증하는 예시를 보여줍니다.

try (ImapClient imapClient = new ImapClient(
        server.ImapUrl, server.ImapPort, "username", "password", SecurityOptions.Auto)) {
    imapClient.setTimeout(4000);

    if (imapClient.validateCredentials()) {
        // to do something
    }
}

메일 작업에 대한 시간 제한 설정 방법

각 메일 작업은 네트워크 지연, 데이터 크기, 서버 성능 등 여러 요인에 따라 시간이 소요됩니다. 모든 메일 작업에 대한 시간 제한을 설정할 수 있습니다. 아래 코드 예제는 이를 …을 사용해 설정하는 방법을 보여줍니다. 시간 제한 속성. 참고: 애플리케이션에서 긴 대기 시간을 피하려면 큰 값을 설정하지 않아야 합니다.

try (ImapClient imapClient = new ImapClient("host", 993, "username", "password", SecurityOptions.SSLImplicit))
{
    imapClient.setTimeout(60000); // 60 seconds

    // some code...
}

Greeting Timeout 제한 방법

IMAP 클라이언트는 자동 모드를 사용하여 연결을 설정할 수 있습니다. 이 모드에서는 IMAP 클라이언트가 연결이 설정될 때까지 모든 가능한 연결 매개변수를 시도합니다. 올바른 연결이 이루어지면 IMAP 서버는 클라이언트에 인사 문자열을 보냅니다. 서버는 암시적 또는 명시적(START TLS) SSL/TLS 연결을 시작할 수 있습니다. 연결 모드가 일치하지 않을 경우(예: 서버가 암시적 SSL 연결을 기다리는데 클라이언트가 비보안 또는 명시적 SSL 연결을 시도하는 경우) 서버는 인사 문자열을 보내지 않으며, 사용자는 제한 시간이 초과될 때까지 오랫동안 대기하게 됩니다. 이 문제를 피하기 위해 GreetingTimeout이 도입되었습니다. 이 속성을 사용하면 인사 문자열에 대한 시간 제한을 설정하고 자동 연결 설정 시간을 줄일 수 있습니다.

ImapClient imapClient = new ImapClient();
imapClient.setGreetingTimeout(4000);