SMTP 서버에 연결하기
SSL을 지원하는 SMTP 서버에 연결할 때 다음 속성을 설정해야 합니다.
아래 예제에서는 다음과 같은 방법을 보여줍니다:
- 사용자 이름 설정.
- 비밀번호 설정.
- 포트 설정.
- 보안 옵션 설정.
다음 코드 스니펫은 SSL이 활성화된 SMTP 서버에 연결하는 방법을 보여줍니다.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
SmtpClient client = new SmtpClient("smtp.gmail.com");
// Set username, password, port, and security options
client.setUsername("your.email@gmail.com");
client.setPassword("your.password");
client.setPort(587);
client.setSecurityOptions(SecurityOptions.SSLExplicit);
SOCKS 프록시 서버를 통한 서버 연결
때때로 외부와 통신하기 위해 프록시 서버를 사용합니다. 이 경우, 프록시 주소를 지정하지 않으면 메일 클라이언트가 인터넷에 연결할 수 없습니다. Aspose.Email는 SOCKS 프록시 프로토콜의 버전 4, 4a, 5를 지원합니다. 이 문서는 프록시 메일 서버를 사용하여 이메일을 보내는 작동 예제를 제공합니다. 프록시 서버를 통해 이메일을 보내려면:
- 프록시 주소, 포트 및 SOCKS 버전 등 필요한 정보를 사용하여 프록시를 초기화합니다.
- 초기화 SmtpClient 호스트 주소, 사용자 이름 및 비밀번호, 그리고 기타 설정과 함께.
- 클라이언트 Proxy 속성을 다음으로 설정합니다: Proxy 이전에 생성된 객체.
다음 코드 스니펫은 프록시 서버를 통해 서버에 연결하는 방법을 보여줍니다.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
SmtpClient client = new SmtpClient("smtp.domain.com", "username", "password");
client.setSecurityOptions(SecurityOptions.SSLImplicit);
String proxyAddress = "192.168.203.142"; // proxy address
int proxyPort = 1080; // proxy port
SocksProxy proxy = new SocksProxy(proxyAddress, proxyPort, SocksVersion.SocksV5);
client.setProxy(proxy);
client.send(new MailMessage("sender@domain.com", "receiver@domain.com", "Sending Email via proxy",
"Implement socks proxy protocol for versions 4, 4a, 5 (only Username/Password authentication)"));
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);
try (SmtpClient client = new SmtpClient("host", 587, "username", "password")) {
client.setProxy(proxy);
client.send(new MailMessage("sender@domain.com", "receiver@domain.com", "Sending Email via proxy",
"Implement socks proxy protocol for versions 4, 4a, 5 (only Username/Password authentication)"));
}
인증 메커니즘 맞춤 설정
SMTP 서버가 지원하는 인증 메커니즘 목록을 다음을 사용하여 검색합니다: getSupportedAuthentication 메서드 SmtpClient 클래스. 이 메서드는 클라이언트가 서버와 보안 연결을 수립하는 데 사용할 수 있는 인증 방법을 확인하도록 허용합니다. 그런 다음, setAllowedAuthentication 사용자가 허용한 인증 유형 열거형을 가져오거나(또는 설정하는) 메서드로, 클라이언트-서버 통신에 가장 적합한 인증 메커니즘을 선택합니다. 이를 통해 메일 클라이언트의 인증 방법을 명시적으로 설정할 수 있습니다.
다음 코드 샘플은 이메일 클라이언트 인증을 커스터마이즈하는 방법을 보여줍니다:
smtpClient.setAllowedAuthentication(SmtpKnownAuthenticationType.Login);
서버에 연결하기 위해 CRAM-MD5 인증 사용
SMTP 서버와의 보안 인증 및 통신을 보장하기 위해, SMTP 클라이언트에 허용되는 인증 방법으로 CRAM-MD5 사용을 지정하고 강제할 수 있습니다. 다음 코드 스니펫은 허용된 인증 유형을 구성하는 방법을 보여줍니다. SmtpClient:
smtpClient.setAllowedAuthentication(SmtpKnownAuthenticationType.CramMD5);
호스트의 특정 IP 주소에 SMTP 클라이언트 바인딩
호스트에 이메일 전송을 위한 여러 포트가 존재할 가능성을 배제할 수 없습니다. 이러한 경우, 이메일 전송 클라이언트를 호스트의 특정 포트에 바인딩해야 할 필요가 생길 수 있습니다. 이는 Aspose.Email API를 사용하여도 구현할 수 있습니다. SmtpClient bindIPEndPoint 속성. API SmtpClient 특정 IP 엔드포인트를 지정하여 호스트에서 특정 IP 주소를 사용하도록 설정할 수 있습니다. 다음 코드 스니펫은 SMTP 클라이언트를 호스트의 특정 IP 주소에 바인딩하는 방법을 보여줍니다.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
SmtpClient client = new SmtpClient("smtp.domain.com", // host
587, // port
"username", // username
"password", // password
SecurityOptions.Auto // Security Options
);
try {
client.bindIPEndPoint(new BindIPEndPointHandler() {
public InetSocketAddress invoke(InetSocketAddress remoteEndPoint) {
return new InetSocketAddress(0);
}
});
client.noop();
} finally {
client.dispose();
}
이메일 전송 없이 메일 서버 자격 증명 검증
때때로 이메일을 보내지 않고 자격 증명을 확인해야 할 필요가 있습니다. Aspose.Email은 이를 제공합니다 validateCredentials() method를 사용해 이 작업을 수행합니다. 검증이 성공하면 if 문 내부의 코드가 실행되며, 일반적으로 추가 작업을 수행하거나 IMAP 서버에서 데이터를 가져오는 데 사용됩니다. 다음 코드 스니펫은 이메일을 보내지 않고 자격 증명을 검증하는 예시를 보여줍니다.
try (SmtpClient smtpClient = new SmtpClient(
server.SmtpUrl, server.SmtpPort, "username", "password", SecurityOptions.Auto)) {
smtpClient.setTimeout(4000);
if (smtpClient.validateCredentials()) {
// to do something
}
}
메일 작업에 대한 시간 제한 설정 방법
각 메일 작업은 네트워크 지연, 데이터 크기, 서버 성능 등 여러 요인에 따라 시간이 소요됩니다. 모든 메일 작업에 대한 시간 제한을 설정할 수 있습니다. 아래 코드 예제는 이를 …을 사용해 설정하는 방법을 보여줍니다. 시간 제한 속성. 참고: 애플리케이션에서 긴 대기 시간을 피하려면 큰 값을 설정하지 않아야 합니다.
try (SmtpClient smtpClient = new SmtpClient("host", 587, "username", "password", SecurityOptions.SSLExplicit))
{
smtpClient.setTimeout(60000); // 60 seconds
// some code...
}
SMTP에서 암호화 프로토콜 사용
Aspose.Email은 SSL(구식) 및 TLS 암호화 프로토콜을 지원하여 통신 보안을 제공합니다. 애플리케이션과 메일 서버 간 데이터 교환을 보호하려면 암호화 암호화를 활성화할 수 있습니다.
지원되는 값은 다음에 나열되어 있습니다: EncryptionProtocols 열거형: Ssl2, Ssl3, Tls, Tls11, Tls12 및 Tls13. 값은 비트 OR 연산자로 결합할 수 있습니다.
{% alert color="primary" %} JRE에서 지원하는 프로토콜 버전만 설정하십시오. 지원되지 않는 버전은 무시되고 건너뛰며 예외가 발생하지 않습니다. 다음을 사용하십시오 setSupportedEncryptionUnsafe 호환성 검사를 수행하지 않고 프로토콜을 설정하려면 다음 메서드를 사용하십시오: setSupportedEncryption 지원되는 수준으로 암호화 프로토콜을 다운그레이드하면서 setSupportedEncryptionUnsafe 예외를 발생시킵니다. {% /alert %}
아래 코드 예제는 TLS 1.3을 설정하는 방법을 보여줍니다. SmtpClient 인스턴스.
try (SmtpClient smtpClient = new SmtpClient("host", 587, "username", "password", SecurityOptions.SSLExplicit)) {
smtpClient.setSupportedEncryption(EncryptionProtocols.Tls13);
// some code...
}
여러 프로토콜 버전을 허용하려면 플래그를 결합하십시오:
try (SmtpClient smtpClient = new SmtpClient("host", 587, "username", "password", SecurityOptions.SSLExplicit)) {
smtpClient.setSupportedEncryption(EncryptionProtocols.Tls12 | EncryptionProtocols.Tls13);
// some code...
}
활동 로깅 활성화
활동 로깅은 디버깅은 물론 SMTP 클라이언트의 작동 정보를 수집하고 분석하는 데 사용됩니다. Aspose.Email for Java에서는 로깅을 상위 클래스에서 상속된 속성을 통해 코드에서 구성합니다. EmailClient 클래스:
setEnableLogger(boolean)- 로깅을 켜고 끕니다.setLogFileName(String)- 로그 파일에 대한 상대 경로나 절대 경로를 지정합니다. 오버로드setLogFileName(String, boolean)또한 기존 파일을 덮어쓰는 대신 추가하게 할 수 있습니다.setUseDateInLogFileName(boolean)- 현재 날짜를 로그 파일 이름에 추가하여 매일 별도의 파일이 작성되도록 합니다.resetLogSettings()- 기본 로깅 설정을 복원합니다.EmailClient.setShowCredentialsInLog(boolean)- 로그에 자격 증명이 표시되는지 제어하는 정적 스위치입니다. 운영 환경에서는 비활성화 상태를 유지하십시오.
try (SmtpClient smtpClient = new SmtpClient("host", 587, "username", "password", SecurityOptions.SSLExplicit)) {
// Never write credentials into the log file
EmailClient.setShowCredentialsInLog(false);
smtpClient.setEnableLogger(true);
smtpClient.setUseDateInLogFileName(true);
smtpClient.setLogFileName("logs/smtp.log");
// some code...
}
{% alert color="primary" %} The appsettings.json 및 App.config Aspose.Email for .NET 문서에 설명된 구성 옵션은 Java에 적용되지 않으며, 위와 같이 코드에서 로깅을 활성화하십시오. {% /alert %}