2014-06-09 2 views
1

Java 코드를 통해 전자 메일을 보내고 싶습니다. 내 라이브러리에 다음을 추가했습니다 .JARs : log4j.jar, smtp.jar, mailapi.jar, ctivation.jar. 그리고 내 자바 클래스는 다음과 같습니다Java를 사용하여 전자 메일을 보내면 gmail 호스트에 연결하면 응답이 없습니다.

import java.util.Properties; 
import javax.mail.*; 
import javax.mail.internet.*; 

public class SendEmail 
{ 
public static void main(String [] args) 
{  
    String to = "[email protected]"; 
    String from = "[email protected]"; 
    String host = "smtp.gmail.com"; 
    Properties properties = System.getProperties(); 


    properties.setProperty("mail.smtp.host", host); 
    properties.setProperty("mail.smtp.starttls.enable", "true"); 
    properties.setProperty("mail.smtp.auth", "true"); 

    SmtpAuthenticator authentication = new SmtpAuthenticator(); 
    javax.mail.Message msg = new MimeMessage(Session 
         .getInstance(properties, authentication)); 

    try { 
     msg.setFrom(new InternetAddress(from)); 
     msg.setRecipient(Message.RecipientType.TO, 
      new InternetAddress(to)); 
     msg.setSubject("Subject"); 
     msg.setText("Working fine..!"); 
     System.out.println("fine1 !!"); 
     Transport transport = Session.getDefaultInstance(properties , null).getTransport("smtp"); 
     System.out.println("fine2 !!"); 
     transport.connect("smtp.gmail.com" , 465 , "username", "password"); 
     System.out.println("fine3 !!"); 
     Transport.send(msg); 
     System.out.println("fine!!"); 
    } 
    catch(Exception exc) { 
     System.out.println(exc); 
    } 
} 
} 

내 SmtpAuthenticator 클래스 : 난 내 Java 응용 프로그램 클래스를 실행하면

import javax.mail.Authenticator; 
import javax.mail.PasswordAuthentication; 

public class SmtpAuthenticator extends Authenticator { 
    public SmtpAuthenticator() { 

     super(); 
    } 

    @Override 
    public PasswordAuthentication getPasswordAuthentication() { 
     String username = "user"; 
     String password = "password"; 
     if ((username != null) && (username.length() > 0) && (password != null) 
       && (password.length() > 0)) { 

      return new PasswordAuthentication(username, password); 
     } 

     return null; 
    } 
} 

그것이 인쇄 : fine1! fine2 !!

그리고 응답하지 않습니다. 이 문제를 어떻게 해결할 수 있습니까?

+0

pc/server와 외부 smtp 서버 간의 통신을 차단하는 방화벽이 없는지 확인하십시오. –

+0

Windows 방화벽이 가정 및 공용 네트워크에서 새 프로그램을 차단할 때 방화벽에서 사용자에게 알림을 보내도록 설정됩니다. – Tot

답변

4

문제는이 라인이다

transport.connect("smtp.gmail.com" , 465 , "username", "password"); 

465 SSL (SMTPS) 위에 SMTP의 포트이므로, 포트 (25) 사용 중 하나

transport.connect("smtp.gmail.com" , 25 , "username", "password"); 

또는 SMTPS

를 사용하도록 변경
Transport transport = Session.getDefaultInstance(properties , null).getTransport("smtps"); 

transport.connect("smtp.gmail.com" , 465, "username", "password"); 
+0

문제가 다시 발생하여 두 가지 제안을 모두 시도했습니다. 결과 : fine1 \t !! fine2 \t !! javax.mail.AuthenticationFailedException : 454 4.7.0 로그인 시도가 너무 많습니다. 나중에 다시 시도하십시오. z5sm47598012eee.31 - gsmtp – Tot

+0

Gmail 계정에 대해 2 단계 인증을 사용하도록 설정 했습니까? 당신이하는 경우에 작동하지 않을 것이다 –

+0

나는 나가 배치 한 것만있다. – Tot

관련 문제