MessagingException while trying to read emails from Gmail using java

旧城冷巷雨未停 提交于 2019-12-25 02:38:07

问题


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)


回答1:


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.



来源:https://stackoverflow.com/questions/22667657/messagingexception-while-trying-to-read-emails-from-gmail-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!