2014-01-30 4 views
0

Я использую javamail api для настройки получателя, но это исключение. Я не знаю, как его решить. Я просто новичок в javamail. я просто не понимаю, что именно он хочет от меня. пожалуйста, дайте мне подходящее решение. мой код:Получение почты с использованием javamail API

  package com.message; 
      import javax.mail.*; 
      import java.util.*; 
      import java.io.*; 
      public class Receiver 
      { 
      public static void main(String[] args) 
      { 
      Properties props = new Properties(); 
      String host = "pop3.gmail.com";  
      String username = "emailid";  
      String password = "pasword";  
      String provider = "pop3"; 
      try 
      {  
     // Connect to the POP3 server  
     Session session = Session.getInstance(props);  
     Store store = session.getStore(provider);  
     store.connect(host,username, password); 
     // Open the folder  
     Folder inbox = store.getFolder("INBOX");  
      if (inbox == null) 
      {   
      System.out.println("No INBOX"); 
      System.exit(1);  
      }  
       inbox.open(Folder.READ_ONLY); 
     // Get the messages from the server  
      Message[] messages = inbox.getMessages();  
       for (int i = 0; i < messages.length; i++) 
       {   
       System.out.println("Message"+(i+1));      
       messages[i].writeTo(System.out);  
       } 
       // Close the connection  
        // but don't remove the messages from the server  
       inbox.close(false);  
       store.close();  
        } 
        catch (MessagingException ex) 
        {  
       ex.printStackTrace();  
        } 
        catch(IOException ex) 
        { 
       ex.printStackTrace(); 
        } 
       } 
        } 

и исключение:

  javax.mail.MessagingException: Connect failed; 
      nested exception is: 
     java.net.UnknownHostException: pop3.gmail.com 
     at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:160) 
     at javax.mail.Service.connect(Service.java:291) 
     at javax.mail.Service.connect(Service.java:172) 
     at com.message.Receiver.main(Receiver.java:20) 
      Caused by: java.net.UnknownHostException: pop3.gmail.com 
     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:177) 
     at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:367) 
     at java.net.Socket.connect(Socket.java:524) 
     at java.net.Socket.connect(Socket.java:474) 
     at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:267) 
     at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:227) 
     at com.sun.mail.pop3.Protocol.<init>(Protocol.java:91) 
     at com.sun.mail.pop3.POP3Store.getPort(POP3Store.java:213) 
     at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:156) 
     ... 3 more 

кто-нибудь, пожалуйста, решить эту проблему.

+0

Пожалуйста, правильно отформатируйте свой код, его действительно трудно прочитать. Спасибо ;-) –

+0

Можете ли вы изменить хост как pop.gmail.com и запустите .. – Kick

ответ

0

Это:

java.net.UnknownHostException: pop3.gmail.com 

говорит вам, что ваша система не может разрешить IP-адрес для pop3.gmail.com. См. the doc для получения дополнительной информации.

Выведено, чтобы указать, что IP-адрес хоста не может быть установлен .

Правильно ли настроен DNS? Можете ли вы прослушать этот хост? Это правильно имя хоста?

+0

да .... пожалуйста, скажите, почему это показывает мне pop3.gmail.com как неизвестный хост? – user3202225

+0

Почему это вниз? –

+0

Я не знаю ... – user3202225

1

Попробуйте pop.gmail.com, это, по-видимому, правильный адрес.

+0

извините dude, .... его показывая мне другое исключение, то есть javax.mail.MessagingException: Connect failed; вложенное исключение: \t java.io.IOException: Сбой подключения \t на com.sun.mail.pop3.POP3Store.protocolConnect (POP3Store.java:160) \t в javax.mail.Service.connect (Service.java : 291) \t на javax.mail.Service.connect (Service.java:172) \t на com.message.Receiver.main (Receiver.java:20) Вызванный: java.io.IOException: Сбой подключения – user3202225

+3

@ пользователь3202225 другой исключая = другой проблема. Обновите свой вопрос/разместите новый. – zapl

+0

Попробуйте указать порт 995. Gmail использует нестандартный порт, как кажется. –

0

Вы не определили порт - для GMAIL pop3 995 в главном классе

String protocol = "pop3"; 
String host = "pop.gmail.com"; 
String port = "995"; 

свойства установки:

private Properties getServerProperties(String protocol, String host, String port) { 
    Properties properties = new Properties(); 

    // server setting 
    properties.put(String.format("mail.%s.host", protocol), host); 
    properties.put(String.format("mail.%s.port", protocol), port); 

    // SSL setting 
    properties.setProperty(
      String.format("mail.%s.socketFactory.class", protocol), 
      "javax.net.ssl.SSLSocketFactory"); 
    properties.setProperty(
      String.format("mail.%s.socketFactory.fallback", protocol), 
      "false"); 
    properties.setProperty(
      String.format("mail.%s.socketFactory.port", protocol), 
      String.valueOf(port)); 

    return properties; 
} 

получить электронную почту:

public void downloadEmails(String protocol, String host, String port, 
     String userName, String password) { 
    Properties properties = getServerProperties(protocol, host, port); 
    Session session = Session.getDefaultInstance(properties); 

    try { 
     // connects to the message store 
     Store store = session.getStore(protocol); 
     store.connect(userName, password); 

     // opens the inbox folder 
     Folder folderInbox = store.getFolder("INBOX"); 
     folderInbox.open(Folder.READ_ONLY); 

     // fetches new messages from server 
     Message[] messages = folderInbox.getMessages(); 

     for (int i = 0; i < messages.length; i++) { 
      Message msg = messages[i]; 
      Address[] fromAddress = msg.getFrom(); 
      String from = fromAddress[0].toString(); 
      String subject = msg.getSubject(); 
      String toList = parseAddresses(msg 
        .getRecipients(RecipientType.TO)); 
      String ccList = parseAddresses(msg 
        .getRecipients(RecipientType.CC)); 
      String sentDate = msg.getSentDate().toString(); 

      String contentType = msg.getContentType(); 
      String messageContent = ""; 

      if (contentType.contains("text/plain") 
        || contentType.contains("text/html")) { 
       try { 
        Object content = msg.getContent(); 
        if (content != null) { 
         messageContent = content.toString(); 
        } 
       } catch (Exception ex) { 
        messageContent = "[Error downloading content]"; 
        ex.printStackTrace(); 
       } 
      } 

      // print out details of each message 
      System.out.println("Message #" + (i + 1) + ":"); 
      System.out.println("\t From: " + from); 
      System.out.println("\t To: " + toList); 
      System.out.println("\t CC: " + ccList); 
      System.out.println("\t Subject: " + subject); 
      System.out.println("\t Sent Date: " + sentDate); 
      System.out.println("\t Message: " + messageContent); 
     } 

     // disconnect 
     folderInbox.close(false); 
     store.close(); 
    } catch (NoSuchProviderException ex) { 
     System.out.println("No provider for protocol: " + protocol); 
     ex.printStackTrace(); 
    } catch (MessagingException ex) { 
     System.out.println("Could not connect to the message store"); 
     ex.printStackTrace(); 
    } 
} 

наконец:

public static void main(String[] args) { 
     // for POP3 
     String protocol = "pop3"; 
     String host = "pop.gmail.com"; 
     String port = "995"; 


     String userName = "your_email_address"; 
     String password = "your_email_password"; 

     EmailReceiver receiver = new EmailReceiver(); 
     receiver.downloadEmails(protocol, host, port, userName, password); 
    } 
Смежные вопросы