在JavaMail中使用message.getFrom()时,只显示电子邮件地址

时间:2022-06-08 00:07:54

Currently when using JavaMail if I use getFrom() to decompose a message into its separate parts the getFrom() will also display the name of the sender. This may be a simple question but how do you make it so only the email address is returned. Sorry if this is a simple question but I cannot seem to find an answer.

当前使用JavaMail时,如果我使用getFrom()将消息分解成单独的部分,getFrom()也将显示发送方的名称。这可能是一个简单的问题,但是如何才能使它只返回电子邮件地址。对不起,如果这是一个简单的问题,但我似乎找不到答案。

1 个解决方案

#1


43  

As it turns out, the address has already been parsed for you. Because of JavaMail's silly extra layer of abstraction, it's returning InternetAddress objects as their Address superclass. Address objects are pretty much useless. You need to cast them back down to InternetAddress and then just get the email part:

事实证明,地址已经为您解析过了。由于JavaMail愚蠢的额外抽象层,它返回InternetAddress对象作为它们的地址超类。地址对象几乎没用。你需要将它们转换回InternetAddress,然后只获取电子邮件部分:

Address[] froms = message.getFrom();
String email = froms == null ? null : ((InternetAddress) froms[0]).getAddress();

#1


43  

As it turns out, the address has already been parsed for you. Because of JavaMail's silly extra layer of abstraction, it's returning InternetAddress objects as their Address superclass. Address objects are pretty much useless. You need to cast them back down to InternetAddress and then just get the email part:

事实证明,地址已经为您解析过了。由于JavaMail愚蠢的额外抽象层,它返回InternetAddress对象作为它们的地址超类。地址对象几乎没用。你需要将它们转换回InternetAddress,然后只获取电子邮件部分:

Address[] froms = message.getFrom();
String email = froms == null ? null : ((InternetAddress) froms[0]).getAddress();