使用 IMAP(javamail API)从 gmail 访问电子邮件

发布于 2025-01-05 06:02:49 字数 2881 浏览 0 评论 0原文

我正在尝试在 JavaMail API 的帮助下通过 IMAP 访问 Gmail 帐户的电子邮件。我想知道为什么该代码适用于一个电子邮件帐户,但不适用于另一个电子邮件帐户。

我可以访问两个电子邮件帐户的 Inbox 文件夹。但对于其中一个电子邮件帐户,无法访问其他文件夹(例如 SPAM([Gmail]/Spam)),并且会引发 FolderNotFoundException 异常。有人可以解释一下出了什么问题吗?

先感谢您。

这是代码:

import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.Flags.Flag;
import javax.mail.internet.*;

import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPMessage;


public class FolderFetchIMAP {


    public static void main(String[] args) throws MessagingException, IOException {
        IMAPFolder folder = null;
        Store store = null;
        String subject = null;
        Flag flag = null;
        try 
        {
          Properties props = System.getProperties();
          props.setProperty("mail.store.protocol", "imaps");

          Session session = Session.getDefaultInstance(props, null);

          store = session.getStore("imaps");
          store.connect("imap.googlemail.com","[email protected]", "password");

          folder = (IMAPFolder) store.getFolder("[Gmail]/Spam"); // This doesn't work for other email account
          //folder = (IMAPFolder) store.getFolder("inbox"); This works for both email account


          if(!folder.isOpen())
          folder.open(Folder.READ_WRITE);
          Message[] messages = folder.getMessages();
          System.out.println("No of Messages : " + folder.getMessageCount());
          System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
          System.out.println(messages.length);
          for (int i=0; i < messages.length;i++) 
          {

            System.out.println("*****************************************************************************");
            System.out.println("MESSAGE " + (i + 1) + ":");
            Message msg =  messages[i];
            //System.out.println(msg.getMessageNumber());
            //Object String;
            //System.out.println(folder.getUID(msg)

            subject = msg.getSubject();

            System.out.println("Subject: " + subject);
            System.out.println("From: " + msg.getFrom()[0]);
           System.out.println("To: "+msg.getAllRecipients()[0]);
            System.out.println("Date: "+msg.getReceivedDate());
            System.out.println("Size: "+msg.getSize());
            System.out.println(msg.getFlags());
            System.out.println("Body: \n"+ msg.getContent());
            System.out.println(msg.getContentType());

          }
        }
        finally 
        {
          if (folder != null && folder.isOpen()) { folder.close(true); }
          if (store != null) { store.close(); }
        }

    }



}

I am trying to access emails from Gmail accounts through IMAP with the help of the JavaMail API. I was wondering why the code works for one email account but doesn't work for another.

I am able to access the Inbox folder of both email accounts. But for one of the email accounts, other folders like SPAM([Gmail]/Spam) are not able to be accessed and it throws a FolderNotFoundException exception. Could anybody please explain what is going wrong?

Thank you in advance.

Here is the code:

import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.Flags.Flag;
import javax.mail.internet.*;

import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPMessage;


public class FolderFetchIMAP {


    public static void main(String[] args) throws MessagingException, IOException {
        IMAPFolder folder = null;
        Store store = null;
        String subject = null;
        Flag flag = null;
        try 
        {
          Properties props = System.getProperties();
          props.setProperty("mail.store.protocol", "imaps");

          Session session = Session.getDefaultInstance(props, null);

          store = session.getStore("imaps");
          store.connect("imap.googlemail.com","[email protected]", "password");

          folder = (IMAPFolder) store.getFolder("[Gmail]/Spam"); // This doesn't work for other email account
          //folder = (IMAPFolder) store.getFolder("inbox"); This works for both email account


          if(!folder.isOpen())
          folder.open(Folder.READ_WRITE);
          Message[] messages = folder.getMessages();
          System.out.println("No of Messages : " + folder.getMessageCount());
          System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
          System.out.println(messages.length);
          for (int i=0; i < messages.length;i++) 
          {

            System.out.println("*****************************************************************************");
            System.out.println("MESSAGE " + (i + 1) + ":");
            Message msg =  messages[i];
            //System.out.println(msg.getMessageNumber());
            //Object String;
            //System.out.println(folder.getUID(msg)

            subject = msg.getSubject();

            System.out.println("Subject: " + subject);
            System.out.println("From: " + msg.getFrom()[0]);
           System.out.println("To: "+msg.getAllRecipients()[0]);
            System.out.println("Date: "+msg.getReceivedDate());
            System.out.println("Size: "+msg.getSize());
            System.out.println(msg.getFlags());
            System.out.println("Body: \n"+ msg.getContent());
            System.out.println(msg.getContentType());

          }
        }
        finally 
        {
          if (folder != null && folder.isOpen()) { folder.close(true); }
          if (store != null) { store.close(); }
        }

    }



}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

俏︾媚 2025-01-12 06:02:49

是否有一个帐户使用非英语用户界面?

Gmail 文件夹名称根据用户本地化设置进行本地化。

目前获取本地化文件夹名称的唯一方法是使用 XLIST 命令。

Is one of the accounts using non-english UI by any chance?

Gmail folder names are localized with respect to the user localization settings.

Currently the only way to get the name of the localized folder is by using XLIST command.

不交电费瞎发啥光 2025-01-12 06:02:49
package com.technicalkeeda;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;

public class GmailInbox {

 public static void main(String[] args) {
  GmailInbox gmail = new GmailInbox();
  gmail.read();
 }

 public void read() {
  Properties props = new Properties();
  try {
   props.load(new FileInputStream(new File("C:\\smtp.properties")));
   Session session = Session.getDefaultInstance(props, null);

   Store store = session.getStore("imaps");
   store.connect("smtp.gmail.com", "*************@gmail.com","your_password");

   Folder inbox = store.getFolder("inbox");
   inbox.open(Folder.READ_ONLY);
   int messageCount = inbox.getMessageCount();

   System.out.println("Total Messages:- " + messageCount);

   Message[] messages = inbox.getMessages();
   System.out.println("------------------------------");
   for (int i = 0; i < 10; i++) {
      System.out.println("Mail Subject:- " + messages[i].getSubject());      
   }
   inbox.close(true);
   store.close();

  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}
package com.technicalkeeda;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;

public class GmailInbox {

 public static void main(String[] args) {
  GmailInbox gmail = new GmailInbox();
  gmail.read();
 }

 public void read() {
  Properties props = new Properties();
  try {
   props.load(new FileInputStream(new File("C:\\smtp.properties")));
   Session session = Session.getDefaultInstance(props, null);

   Store store = session.getStore("imaps");
   store.connect("smtp.gmail.com", "*************@gmail.com","your_password");

   Folder inbox = store.getFolder("inbox");
   inbox.open(Folder.READ_ONLY);
   int messageCount = inbox.getMessageCount();

   System.out.println("Total Messages:- " + messageCount);

   Message[] messages = inbox.getMessages();
   System.out.println("------------------------------");
   for (int i = 0; i < 10; i++) {
      System.out.println("Mail Subject:- " + messages[i].getSubject());      
   }
   inbox.close(true);
   store.close();

  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}
意犹 2025-01-12 06:02:49

您可以尝试以下代码:

private List<String> getResult1(){
  try {
    Properties props = new Properties();
    props.put("mail.store.protocol","imaps");
    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imaps");
    store.connect("imap.gmail.com", "Email Id", "App Password");

    //if you want mail from specified folder, just change change folder name
    //Folder inbox = store.getFolder("[Gmail]/Drafts");
    Folder inbox = store.getFolder("inbox");

    inbox.open(Folder.READ_ONLY);
    int messageCount = inbox.getMessageCount();
    Log.e("getFolder ", "getResult1: " + store.getDefaultFolder().list("*"));
    javax.mail.Folder[] folders = store.getDefaultFolder().list("*");

    for (javax.mail.Folder folder : folders) {
      if ((folder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0){
        Log.e("getFolder ", "getResult1: " + folder.getName() );
      }
    }

    Log.e("Mail Subject:", "Total Messages:-: " + messageCount );
    javax.mail.Message[] messages = inbox.getMessages();

    System.out.println("------------------------------");
    Log.e("Mail Subject:", "messages: " + messages.toString());
    for (int i = 0; i < messages.length; i++) {
      Log.e("Mail Subject:", "getResult1: " + messages[i].getSubject());
    }
    inbox.close(true);
    store.close();
  } catch (Exception e) {
    e.printStackTrace();
  }
  return null;
}

You can try the following code:

private List<String> getResult1(){
  try {
    Properties props = new Properties();
    props.put("mail.store.protocol","imaps");
    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imaps");
    store.connect("imap.gmail.com", "Email Id", "App Password");

    //if you want mail from specified folder, just change change folder name
    //Folder inbox = store.getFolder("[Gmail]/Drafts");
    Folder inbox = store.getFolder("inbox");

    inbox.open(Folder.READ_ONLY);
    int messageCount = inbox.getMessageCount();
    Log.e("getFolder ", "getResult1: " + store.getDefaultFolder().list("*"));
    javax.mail.Folder[] folders = store.getDefaultFolder().list("*");

    for (javax.mail.Folder folder : folders) {
      if ((folder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0){
        Log.e("getFolder ", "getResult1: " + folder.getName() );
      }
    }

    Log.e("Mail Subject:", "Total Messages:-: " + messageCount );
    javax.mail.Message[] messages = inbox.getMessages();

    System.out.println("------------------------------");
    Log.e("Mail Subject:", "messages: " + messages.toString());
    for (int i = 0; i < messages.length; i++) {
      Log.e("Mail Subject:", "getResult1: " + messages[i].getSubject());
    }
    inbox.close(true);
    store.close();
  } catch (Exception e) {
    e.printStackTrace();
  }
  return null;
}
打小就很酷 2025-01-12 06:02:49

我不确定这是否有帮助,但我见过 Gmail 帐户具有不同邮箱的实例,即...

Gmail 帐户 1 :-

[[Google Mail]]
[[Google Mail]/All Mail]
[[Google Mail]/Bin]
[[Google Mail]/Drafts]
[[Google Mail]/Important]
[[Google Mail]/Sent Mail]
[[Google Mail]/Spam]
[[Google Mail]/Starred]

Gmail 帐户 2 :-

[[Gmail]]
[[Gmail]/All Mail]
[[Gmail]/Bin]
[[Gmail]/Drafts]
[[Gmail]/Important]
[[Gmail]/Sent Mail]
[[Gmail]/Spam]
[[Gmail]/Starred]

Im unsure if this helps, but I've seen instances where gmail accounts have different mailboxes ie..

Gmail Account 1 :-

[[Google Mail]]
[[Google Mail]/All Mail]
[[Google Mail]/Bin]
[[Google Mail]/Drafts]
[[Google Mail]/Important]
[[Google Mail]/Sent Mail]
[[Google Mail]/Spam]
[[Google Mail]/Starred]

Gmail Account 2 :-

[[Gmail]]
[[Gmail]/All Mail]
[[Gmail]/Bin]
[[Gmail]/Drafts]
[[Gmail]/Important]
[[Gmail]/Sent Mail]
[[Gmail]/Spam]
[[Gmail]/Starred]
丿*梦醉红颜 2025-01-12 06:02:49

它的工作方式是这样的(看起来它不适用于 POP3,但它适用于 IMAP):

     Properties props = new Properties();
     props.put("mail.store.protocol", "imaps");
     Session session = Session.getDefaultInstance(props, null);
     Store store = session.getStore("imaps");
     store.connect("imap.gmail.com", [[email protected]], [thePasswordOrAppPassword]);

     // You possibly will have to use [Google Mail]/All Mail instead
     Folder inbox = store.getFolder("[Gmail]/All Mail");

It works this way (It looks like it doesn't work with POP3, but it works with IMAP):

     Properties props = new Properties();
     props.put("mail.store.protocol", "imaps");
     Session session = Session.getDefaultInstance(props, null);
     Store store = session.getStore("imaps");
     store.connect("imap.gmail.com", [[email protected]], [thePasswordOrAppPassword]);

     // You possibly will have to use [Google Mail]/All Mail instead
     Folder inbox = store.getFolder("[Gmail]/All Mail");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文