i'm trying to access my Gmail account using Java Gmail API then access the body of the first Email and then save it into text file using this path in my computer D:\Email
, so any suggestion ? i have tried so many examples such as using saveFile
but none of them worked for me !
NOTE: i want only to save the body of the Email
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 "); }
}
}