Java 我可以阅读gmail邮件的内容吗?
以下代码用于从gmail帐户检索电子邮件。此代码对我很有用。我可以获取主题和地址,但无法读取邮件内容。 如果有人有任何解决办法,谢谢Java 我可以阅读gmail邮件的内容吗?,java,email,Java,Email,以下代码用于从gmail帐户检索电子邮件。此代码对我很有用。我可以获取主题和地址,但无法读取邮件内容。 如果有人有任何解决办法,谢谢 import java.util.Properties; import javax.mail.Address; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Session; import javax.mail.Store; /** * Class read
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
/**
* Class reads emails
*
* @author itcuties
*
*/
public class JavaMailReader {
public static void main(String[] args) {
readEmails(true);
}
/**
* Method reads emails from the IMAP or POP3 server.
* @param isImap - if true then we are reading messages from the IMAP server, if no then read from the POP3 server.
*/
private static void readEmails(boolean isImap) {
// Create all the needed properties - empty!
Properties connectionProperties = new Properties();
// Create the session
Session session = Session.getDefaultInstance(connectionProperties,null);
try {
System.out.print("Connecting to the IMAP server...");
// Connecting to the server
// Set the store depending on the parameter flag value
String storeName = isImap ? "imaps" : "pop3";
Store store = session.getStore(storeName);
// Set the server depending on the parameter flag value
String server = isImap ? "imap.gmail.com" : "pop3.gmail.com";
store.connect(server,"coding@gmail.com","P@ssw0rd1");
System.out.println("done!");
// Get the Inbox folder
Folder inbox = store.getFolder("Inbox");
// Set the mode to the read-only mode
inbox.open(Folder.READ_ONLY);
// Get messages
Message messages[] = inbox.getMessages();
System.out.println("Reading messages...");
// Display the messages
for(Message message:messages) {
for (Address a: message.getFrom())
System.out.println("From:" + a);
System.out.println("Title: " + message.getSubject());
System.out.println();
System.out.println(message.getContent());
System.out.println("---");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
这是你的问题:
因此,一旦有了对象,即objectcontent=message.getContent()
,就应该进行实例检查,看看它是字符串还是多部分类。即
Object content = message.getContent()
if ( content instanceof String )
{
String text = (String) content;
// Do things
}
else if ( content instanceof Multipart )
{
Multipart multiPart = (Multipart) content;
// Do things
}
错误是什么,发布你的错误控制台Ussain Akhtar Wahid'Ghouri'我的控制台中没有任何错误。我清楚地了解了发件人和主题,但没有了解我邮件的内容。我们有一个免费的Chrome/Gmail插件,名为。你可以在那里检查代码。Zyn谢谢,但实际上我没有得到它。。你能修改我的代码并给出..实际上,尝试以下方法:而不是System.out.println(message.getContent())代码>尝试message.writeTo(System.out)代码>。我现在无法测试。