无法使用 Java 连接到我的 Gmail 收件箱

Posted

技术标签:

【中文标题】无法使用 Java 连接到我的 Gmail 收件箱【英文标题】:Could not connect to my Gmail inbox with Java 【发布时间】:2011-11-10 10:41:10 【问题描述】:

我正在尝试使用 google 找到的这段代码,但它没有连接到我的 gmail 收件箱。为什么?

我有这个错误信息:

--------------开始处理邮件------ 获取访问电子邮件的会话。 无法处理邮件阅读。 javax.mail.MessagingException:连接超时:连接; 嵌套异常是: java.net.ConnectException:连接超时:连接 在 com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:618) 在 javax.mail.Service.connect(Service.java:291) 在 javax.mail.Service.connect(Service.java:172) 在 readEmails.processMail(readEmails.java:47) 在 readEmails.(readEmails.java:19) 在 readEmails.main(readEmails.java:165) 引起:java.net.ConnectException:连接超时:连接 在 java.net.PlainSocketImpl.socketConnect(本机方法) 在 java.net.PlainSocketImpl.doConnect(未知来源) 在 java.net.PlainSocketImpl.connectToAddress(未知来源) 在 java.net.PlainSocketImpl.connect(未知来源) 在 java.net.SocksSocketImpl.connect(未知来源) 在 java.net.Socket.connect(未知来源) 在 java.net.Socket.connect(未知来源) 在 com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:284) 在 com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:227) 在 com.sun.mail.iap.Protocol.(Protocol.java:109) 在 com.sun.mail.imap.protocol.IMAPProtocol.(IMAPProtocol.java:104) 在 com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:585)

代码是:

import javax.mail.AuthenticationFailedException;
import javax.mail.Folder;
import javax.mail.FolderClosedException;
import javax.mail.FolderNotFoundException;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.ReadOnlyFolderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.StoreClosedException;
import javax.mail.internet.InternetAddress;

public class readEmails 

//Constructor Call
public readEmails() 
   processMail();


//Responsible for printing Data to Console
private void printData(String data) 
   System.out.println(data);


public void processMail() 
   Session session = null;
   Store store = null;
   Folder folder = null;
   Message message = null;
   Message[] messages = null;
   Object messagecontentObject = null;
   String sender = null;
   String subject = null;
   Multipart multipart = null;
   Part part = null;
   String contentType = null;

   try 
      printData("--------------processing mails started-----------------");
      session = Session.getDefaultInstance(System.getProperties(), null);

      printData("getting the session for accessing email.");
      store = session.getStore("imap");

      store.connect("imap.gmail.com","myemail@gmail.com","mypassword");
      printData("Connection established with IMAP server.");

      // Get a handle on the default folder
      folder = store.getDefaultFolder();

      printData("Getting the Inbox folder.");

      // Retrieve the "Inbox"
      folder = folder.getFolder("inbox");

      //Reading the Email Index in Read / Write Mode
      folder.open(Folder.READ_WRITE);

      // Retrieve the messages
      messages = folder.getMessages();

      // Loop over all of the messages
      for (int messageNumber = 0; messageNumber < messages.length; messageNumber++) 
           // Retrieve the next message to be read
       message = messages[messageNumber];

           // Retrieve the message content
           messagecontentObject = message.getContent();

           // Determine email type
           if (messagecontentObject instanceof Multipart) 
               printData("Found Email with Attachment");
               sender = ((InternetAddress) message.getFrom()[0]).getPersonal();

               // If the "personal" information has no entry, check the address for the sender information
               printData("If the personal information has no entry, check the address for the sender information.");

           if (sender == null) 
           sender = ((InternetAddress) message.getFrom()[0]).getAddress();
           printData("sender in NULL. Printing Address:" + sender);
           
               printData("Sender -." + sender);

               // Get the subject information
               subject = message.getSubject();

               printData("subject=" + subject);

               // Retrieve the Multipart object from the message
               multipart = (Multipart) message.getContent();

               printData("Retrieve the Multipart object from the message");

               // Loop over the parts of the email
               for (int i = 0; i < multipart.getCount(); i++) 
                    // Retrieve the next part
                    part = multipart.getBodyPart(i);

                    // Get the content type
                    contentType = part.getContentType();

                   // Display the content type
           printData("Content: " + contentType);

                   if (contentType.startsWith("text/plain")) 
            printData("---------reading content type text/plain  mail -------------");
            else 
            // Retrieve the file name
            String fileName = part.getFileName();
            printData("retrive the fileName="+ fileName);
           
          
        else 
          printData("Found Mail Without Attachment");
          sender = ((InternetAddress) message.getFrom()[0]).getPersonal();

              // If the "personal" information has no entry, check the address for the sender information
          printData("If the personal information has no entry, check the address for the sender information.");

              if (sender == null) 
        sender = ((InternetAddress) message.getFrom()[0]).getAddress();
        printData("sender in NULL. Printing Address:" + sender);
         

             // Get the subject information
         subject = message.getSubject();
         printData("subject=" + subject);
     
      

      // Close the folder
      folder.close(true);

      // Close the message store
      store.close();
   catch(AuthenticationFailedException e) 
     printData("Not able to process the mail reading.");
     e.printStackTrace();
   catch(FolderClosedException e) 
     printData("Not able to process the mail reading.");
     e.printStackTrace();
   catch(FolderNotFoundException e) 
     printData("Not able to process the mail reading.");
     e.printStackTrace();
    catch(NoSuchProviderException e) 
     printData("Not able to process the mail reading.");
     e.printStackTrace();
   catch(ReadOnlyFolderException e) 
     printData("Not able to process the mail reading.");
     e.printStackTrace();
   catch(StoreClosedException e) 
     printData("Not able to process the mail reading.");
     e.printStackTrace();
   catch (Exception e) 
     printData("Not able to process the mail reading.");
     e.printStackTrace();
  


//Main  Function for The readEmail Class
public static void main(String args[]) 
    //Creating new readEmail Object
    readEmails readMail = new readEmails();

    //Calling processMail Function to read from IMAP Account
    readMail.processMail();



【问题讨论】:

【参考方案1】:

您正在使用 GMail 不支持的协议 imap(不带 SSL 的 IMAP)进行连接。您需要使用imaps(带有 SSL 的 IMAP)。

参见GMail help 和JavaMail FAQ entry on GMail

【讨论】:

以上是关于无法使用 Java 连接到我的 Gmail 收件箱的主要内容,如果未能解决你的问题,请参考以下文章

MailConnectException:无法连接到主机,端口:smtp.gmail.com,465;超时-1

Spring Boot - 无法连接到 SMTP 主机:smtp.gmail.com,端口:25,响应:421

无法连接到 SMTP 主机:smtp.gmail.com,端口:465,响应:-1

PEAR Mail 无法连接到 Gmail SMTP,无法连接到套接字

Java 邮件无法使用 tls 或 ssl 连接到 smtp

无法将SEEN标志设置为从gmail读取的邮件