Android -阅读*.txt附件在电子邮件通过imap/pop3编程



如何通过pop3/imap协议从邮件中读取附加的*.txt文件内容?

电子邮件提供商可能是gmail, yahoo, exchange server. v.v..

看一下如何在android中编程获取gmail邮件的示例

Properties props = new Properties();
//IMAPS protocol
props.setProperty(“mail.store.protocol”, “imaps”);
//Set host address
props.setProperty(“mail.imaps.host”, imaps.gmail.com);
//Set specified port
props.setProperty(“mail.imaps.port”, “993″);
//Using SSL
props.setProperty(“mail.imaps.socketFactory.class”, “javax.net.ssl.SSLSocketFactory”);
props.setProperty(“mail.imaps.socketFactory.fallback”, “false”);
//Setting IMAP session
Session imapSession = Session.getInstance(props);
Store store = imapSession.getStore(“imaps”);
//Connect to server by sending username and password.
//Example mailServer = imap.gmail.com, username = abc, password = abc
store.connect(mailServer, account.username, account.password);
//Get all mails in Inbox Forlder
inbox = store.getFolder(“Inbox”);
inbox.open(Folder.READ_ONLY);
//Return result to array of message
Message[] result = inbox.getMessages();

要从消息[]中接收.txt附件,请查看http://www.codejava.net/java-ee/javamail/download-attachments-in-e-mail-messages-using-javamail

String contentType = message.getContentType();
String messageContent = "";
if (contentType.contains("multipart")) {
    // content may contain attachments
    Multipart multiPart = (Multipart) message.getContent();
    int numberOfParts = multiPart.getCount();
    for (int partCount = 0; partCount < numberOfParts; partCount++) {
        MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
        if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
            // this part is attachment
            String fileName = part.getFileName();
            attachFiles += fileName + ", ";
            part.saveFile(saveDirectory + File.separator + fileName);
        } else {
            // this part may be the message content
            messageContent = part.getContent().toString();
        }
    }
    if (attachFiles.length() > 1) {
        attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
    }
} else if (contentType.contains("text/plain")
        || contentType.contains("text/html")) {
    Object content = message.getContent();
    if (content != null) {
        messageContent = content.toString();
    }
}

最新更新