英文:
JavaxMail - Message get only mail from getFrom()
问题
Address[] from = message.getFrom();
System.out.println(from[0]);
这段代码会输出:AuthorName <name@domain>
或者 name@domain
- 这取决于邮件的内容。
我怎样才能始终只获取到 name@domain
,而不带上 AuthorName
呢?
<details>
<summary>英文:</summary>
I have this code
Address[] from = message.getFrom();
System.out.println(from[0]);
Which prints: `AuthorName <name@domain>` or `name@domain` - depends by the mail.
How I can get just `name@domain` all the time, without `AuthorName`?
</details>
# 答案1
**得分**: 1
地址是抽象的,[Javadoc][1] 指向了两个派生类,一个用于新闻,另一个带有名称不太有帮助的 `InternetAddress`(猜想那时新闻还没有在互联网上)。在这种情况下,您可能会得到一个 `InternetAddress`,它有一个 [getAddress][2] 方法,似乎可以满足您的需求。因此,将返回的地址转换为 `InternetAddress` 并获取电子邮件地址:
```java
Address[] from = message.getFrom();
InternetAddress ia = (InternetAddress) from[0];
System.out.println(ia.getAddress());
英文:
Address is abstract, and the Javadoc points to two derived classes, one for news and the other with the not too helpful name InternetAddress
(guess news wasn't on the internet back then).
In this case you probably get an InternetAddress
, which has getAddress method which seems to do what you want. So cast the returned address to InternetAddress
and get the email address:
Address[] from = message.getFrom();
InternetAddress ia = (InternetAddress) from[0];
System.out.println(ia.getAddress());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论