Printing out the email address of sender from InternetAddress

╄→尐↘猪︶ㄣ 提交于 2019-12-10 10:22:38

问题


This is the code that fetches up the sender and the subject of email.With this code i see the correct subject getting displayed but i see the address of the sender in different format.

Properties props = new Properties();
    props.put("mail.imap.host" , "imap.gmail.com" );
    props.put("mail.imap.user" , "username");
    // User SSL
    props.put("mail.imap.socketFactory" , 993);
    props.put("mail.imap.socketFactory.class" , "javax.net.ssl.SSLSocketFactory" );
    props.put("mail.imap.port" , 993 );
    Session session = Session.getDefaultInstance(props , new Authenticator() {
        @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("username" , "password");
        }
    });

    try {
      Store store = session.getStore("imap");
      store.connect("imap.gmail.com" , "username" , "password");
      Folder fldr = store.getFolder("Inbox");
      fldr.open(Folder.READ_ONLY);
      Message msgs[] = fldr.getMessages();
        for(int i = 0 ; i < msgs.length ; i++) {
            System.out.println(msgs[i].getFrom() + "<-- FROM" + " " + msgs[i].getSubject() + "<---Subject");
        }
    } catch(Exception exc) {

    }
}

The output is :

[Ljavax.mail.internet.InternetAddress;@1462851<-- FROMGet Gmail on your mobile phone<---Subject
[Ljavax.mail.internet.InternetAddress;@bdab91<-- FROMImport your contacts and old email<---Subject
[Ljavax.mail.internet.InternetAddress;@4ac00c<-- FROMCustomize Gmail with colors and themes<---Subject
[Ljavax.mail.internet.InternetAddress;@1865b28<-- FROMtester<---Subject

What form it is?(@1462851) I want the email address of sender to appear instead of @1462851.How can i do this ?


回答1:


The getForm() returns an object. To have it printed as a plain string, please try InternetAddress.toString(msgs[i].getFrom()) in your System.out.




回答2:


You should use msgs[i].getFrom().getAddress(). What you see is the toString result of InternetAddress object (class name + hashcode)




回答3:


I've spent some hard minutes before I found out this simple code:

System.out.println("received from "+((InternetAddress)((Address)(message.getFrom()[0]))).getAddress());




回答4:


The reason for this is because you just print out the InternetAddress instance, which does not have a toString() method. Then it defaults to the Object.toString() which is primarily useful to see if objects are different.

Consider explicitly picking out the field you want to see in your print statement.



来源:https://stackoverflow.com/questions/6806449/printing-out-the-email-address-of-sender-from-internetaddress

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