0

In android. How to read an attached *.txt file content from emails through pop3/imap protocols ?

THe email provider maybe gmail, yahoo, exchange server..v.v..

user2916684
  • 225
  • 3
  • 16

1 Answers1

2

Take a look at the examples from How to get gmail mails programmatically in android

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();

To receive the .txt attachement from the message[] take a look at 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();
    }
}
Community
  • 1
  • 1
userM1433372
  • 5,345
  • 35
  • 38