简体   繁体   中英

Condition gets false even if it contains specified data

I am trying to process mails using JAVA MAIL API. I want to check emails which comes from particular email id , So I am checking like :

   for(int i=0;i<messages.length;i++)
   {
       if(messages[i].getFrom().toString().equalsIgnoreCase("seller-notification@amazon.com"))
       {
           System.out.println(messages[i].getContent());

           Multipart mp = (Multipart)messages[i].getContent();  
           Object Body = mp.getBodyPart(i).getContent();
           String Content = Body.toString();
       }

}

Debug Mode Screen , I can see in debug that values is there in from :

在此处输入图片说明

Above condition is not getting true.

This is because it's not a string, and you are trying to compare an Object 's toString() method and a String . Since this toString won't return what you want, you have to cast it to Address and fetch email from there.

Try:

Address[] froms = messages[i].getFrom();
String email = froms == null ? null : ((InternetAddress) froms[0]).getAddress();
if("seller-notification@amazon.com".equalsIgnoreCase(email))
{//Your work}

The problem is that the toString generates "[Seller Notification ]", and this is not equals to "seller-notification@amazon.com".

You should cast to InternetAddress (check before just in case), extract the email and check the email.

.getFrom() method returns an array of Address datatype object. So first you have to select one of the array elements and cast it to InternetAddress datatype. See the code below

if(((InternetAddress)(messages[i].getFrom()[0])).getAddress().equalsIgnoreCase("seller-notification@amazon.com"))
{
    //your remaining code
}

Please mark this as answer if it solves your problem

messages [i] .getFrom()。toString()**仅提供字节值..)-您需要使用此行转换为字符串

        InternetAddress.toString(messages[i].getFrom());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM