簡體   English   中英

條件即使包含指定的數據也將為假

[英]Condition gets false even if it contains specified data

我正在嘗試使用JAVA MAIL API處理郵件。 我想檢查來自特定電子郵件ID的電子郵件,所以我要像這樣檢查:

   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();
       }

}

調試模式屏幕,我可以在調試中看到來自的值:

在此處輸入圖片說明

以上條件並沒有成立。

這是因為它不是字符串,並且您正在嘗試比較ObjecttoString()方法和String 由於此toString不會返回您想要的內容,因此您必須將其轉換為Address並從那里獲取電子郵件。

嘗試:

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

問題是toString生成“ [Seller Notification]”,這不等於“ seller-notification@amazon.com”。

您應該投射到InternetAddress(以防萬一,請先檢查),提取電子郵件並檢查電子郵件。

.getFrom()方法返回Address數據類型對象的數組。 因此,首先您必須選擇一個數組元素並將其轉換為InternetAddress數據類型。 見下面的代碼

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

如果可以解決您的問題,請標記為答案

messages [i] .getFrom()。toString()**僅提供字節值..)-您需要使用此行轉換為字符串

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM