如何使用Java Gmail API将电子邮件正文写入文本文件



我正在尝试使用Java Gmail API访问我的Gmail帐户,然后访问第一封电子邮件的正文,然后使用计算机D:Email中的此路径将其保存到文本文件中,有什么建议吗?我试过很多例子,比如使用saveFile,但都不适用!

注意:我只想保存电子邮件的正文

 package ReadingEmail;
import java.util.*;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
//===================================================================================
public class ReadingEmail {
      public static Scanner input = new Scanner(System.in);    
public static void main(String[] args) {
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imaps");
        try {
            Session session = Session.getInstance(props, null);
            Store store = session.getStore();
             System.out.println("enter your email");
             String email= input.nextLine();
              System.out.println("enter your password");
             String pass= input.nextLine();
            store.connect("imap.gmail.com", email, pass); //connect to email
            Folder inbox = store.getFolder("INBOX");// go to index 

            inbox.open(Folder.READ_ONLY); // open index 
//==============================================================================================
            int messageCount = inbox.getMessageCount();// line 20,21 show the number of emails
        System.out.println("Total Messages" + messageCount);
         int Message1 = messageCount;
       int Message2 = Message1 -1 ;

        Message msg1= inbox.getMessage(messageCount);
        Message msg2= inbox.getMessage(Message2);

         Address[] in1 = msg1.getFrom();
            for (Address address1 : in1) {}
//================================================================================
            Message msg = inbox.getMessage(inbox.getMessageCount());
            Address[] in = msg.getFrom();
            for (Address address : in) {
            }
            Multipart mp = (Multipart) msg.getContent();
            BodyPart bp = mp.getBodyPart(0);

            System.out.println("CONTENT:" + bp.getContent());
        } 
        catch (Exception ex) // wrong password
     { System.out.println("the email or password is wrong ");  }

    }
}

您有任何错误吗?现在我看不到任何要保存到文件中的代码。

此外,当您使用System.out.println("CONTENT:" + bp.getContent());时,您是否能够将文本打印到控制台?

相关内容

  • 没有找到相关文章

最新更新