Question

I am trying to receive emails from my gmail account using Javamail but I am getting an error during execution....This is my code

package sendemail;
import javax.mail.*;
import java.net.*;
import java.util.*;

public class Test {
    public static void main(String args[])
    {
        Properties prop=new Properties();
        prop.setProperty("mail.store.protocol", "imap");
        prop.setProperty("mail.imap.port", "993");
        try
        {
        Session session=Session.getInstance(prop,null);
        Store store=session.getStore();
        store.connect("imap.gmail.com", "Username", "Password");
        Folder folder=store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);
            Message msg=folder.getMessage(folder.getMessageCount());
            Address[] add=msg.getFrom();
            for(Address address:add)
            {
                System.out.println("FROM:"+address.toString());
            }
            Multipart mp=(Multipart)msg.getContent();
            BodyPart bp=mp.getBodyPart(0);
            System.out.println("SENT DATE:"+msg.getSentDate());
            System.out.println("SUBJECT:"+msg.getSubject());
            System.out.println("CONTENT:"+msg.getContent());

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

    }
}

Error:

javax.mail.MessagingException;
  nested exception is:
    java.io.IOException
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:298)
    at javax.mail.Service.connect(Service.java:275)
    at javax.mail.Service.connect(Service.java:156)
    at sendemail.Test.main(Test.java:25)
Caused by: java.io.IOException
    at com.sun.mail.iap.ResponseInputStream.read0(ResponseInputStream.java:78)
    at com.sun.mail.iap.ResponseInputStream.readResponse(ResponseInputStream.java:48)
    at com.sun.mail.iap.Response.<init>(Response.java:64)
    at com.sun.mail.imap.protocol.IMAPResponse.<init>(IMAPResponse.java:31)
    at com.sun.mail.imap.protocol.IMAPResponse.readResponse(IMAPResponse.java:105)
    at com.sun.mail.imap.protocol.IMAPProtocol.readResponse(IMAPProtocol.java:153)
    at com.sun.mail.iap.Protocol.<init>(Protocol.java:72)
    at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:61)
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:273)
    ... 3 more
BUILD SUCCESSFUL (total time: 11 seconds)

I want to receive mails from my account and display ii as output. (I am using netbeans to run this program)

Was it helpful?

Solution

You don't need to specify the port number, but you do need to tell it to use the IMAP-over-SSL protocol. See the example in the JavaMail FAQ.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top