我可以使用Java Api获取邮件主题和正文内容。
但是在我的应用程序中,我收到了一封电子邮件中的模板,其中包含图像背后的网址。我需要获取该网址,当我手动查看该电子邮件的来源时,我发现该网址已显示。
请记住,我没有下载电子邮件,而是连接到邮件服务器,然后读取任何特定用户的邮件数据
有没有办法可以查看电子邮件来源,就像我收到邮件主题一样。
以下是代码:
import org.jsoup.Jsoup;
import javax.mail.*;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Properties;
public class VerifyEmails {
public Message message;
public int i, n;
public String result;
public void check(String host, String user, String password) throws IOException, MessagingException {
Properties properties = new Properties();
properties.put("mail.imap.host", host);
properties.put("mail.imap.user", user);
properties.put("mail.imap.port", "143");
properties.put("mail.imap.starttls.enable", "false");
Session emailSession = Session.getDefaultInstance(properties);
Store store = emailSession.getStore("imap");
System.out.println("test1 " + store);
store.connect(host, user, password);
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (i = 0, n = messages.length; i < n; i++) {
message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Email contents are :" + message.getContentType());
System.out.println("Email headers are :" + message.getContent());
}
if (message instanceof MimeMessage) {
MimeMessage m = (MimeMessage) message;
Object contentObject = message.getContent();
if (contentObject instanceof Multipart) {
BodyPart clearTextPart = null;
BodyPart htmlTextPart = null;
Multipart content = (Multipart) contentObject;
int count = content.getCount();
for (int i = 0; i < count; i++) {
BodyPart part = content.getBodyPart(i);
if (part.isMimeType("text/plain")) {
clearTextPart = part;
String test = String.valueOf(clearTextPart.getAllHeaders());
System.out.println("check1" + test);
break;
} else if (part.isMimeType("text/html")) {
htmlTextPart = part;
}
}
if (clearTextPart != null) {
result = (String) clearTextPart.getContent();
String test = String.valueOf(clearTextPart.getAllHeaders());
System.out.println("check2" + test);
System.out.println("plain text: " + result);
} else if (htmlTextPart != null) {
String html = (String) htmlTextPart.getContent();
result = Jsoup.parse(html).text();
System.out.println("html text: " + result);
}
} else if (contentObject instanceof String) // a simple text message
{
result = (String) contentObject;
System.out.println("String text: " + result);
} else // not a mime message
{
result = null;
System.out.println("null : " + result);
}
emailFolder.close(false);
store.close();
}
}
}