JavaxMail – 仅从 getFrom() 中获取邮件

huangapple go评论65阅读模式
英文:

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 &lt;name@domain&gt;` 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());

huangapple
  • 本文由 发表于 2020年10月13日 22:20:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/64337063.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定