Leggere l'email con Java

Stampa

Vogliamo leggere l'ultima email arrivata, stampare a video delle informazioni (per esempio: data di spedizione, oggetto e contenuto) e di salvarci l'allegato. Supponiamo che l'indirizzo email da cui vogliamo leggere è "Questo indirizzo email è protetto dagli spambots. È necessario abilitare JavaScript per vederlo.", mentre la password della casella è "password123". Utilizzeremo il protocollo Imap.

Ecco qua il codice:

package com.ventus85.test.mail;

import java.io.*;
import java.util.*;
import javax.mail.*;
import org.testng.annotations.Test;

/**
 * @author ventus85
 */
public class MailTest {

    public MailTest() {
    }

    @Test
    public void readEmail() {
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imaps");
        try {
            Session session = Session.getInstance(props, null);
            Store store = session.getStore();
            store.connect("imap.gmail.com", "Questo indirizzo email è protetto dagli spambots. È necessario abilitare JavaScript per vederlo.", "password123");
            Folder inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);
            int messageCount = inbox.getMessageCount();
            Message msg = inbox.getMessage(messageCount);
            Address[] in = msg.getFrom();
            for (Address address : in) {
                System.out.println("From:" + address.toString());
            }
            Multipart mp = (Multipart) msg.getContent();
            int count = mp.getCount();
            for (int j = 0; j < count; j++) {
                BodyPart bp = mp.getBodyPart(j);
                if (j == 0) {
                    System.out.println("Sent date:" + msg.getSentDate());
                    System.out.println("Subject:" + msg.getSubject());
                    System.out.println("Content:" + bp.getContent());
                }
                if (Part.ATTACHMENT.equalsIgnoreCase(bp.getDisposition())
                    || StringUtils.isNotBlank(bp.getFileName())) {
                    String fileName = bp.getFileName());
                    System.out.println("Attachments: " + fileName);
                    InputStream is = bp.getInputStream();
                    File f = new File("/home/ventus85/" + fileName );
                    FileOutputStream fos = new FileOutputStream(f);
                    byte[] buf = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = is.read(buf)) != -1) {
                        fos.write(buf, 0, bytesRead);
                    }
                    fos.close();
                }
            }
        } catch (Exception mex) {
        }
    }