Descargar archivos adjuntos usando Java Mail


Ahora que he descargado todos los mensajes, y almacenarlos en

Message[] temp;

¿Cómo obtengo la lista de archivos adjuntos para cada uno de esos mensajes a

List<File> attachments;

Nota: no hay libs de terceros, por favor, solo JavaMail.

Author: folone, 2009-11-17

5 answers

Sin manejo de excepción, pero aquí va:

List<File> attachments = new ArrayList<File>();
for (Message message : temp) {
    Multipart multipart = (Multipart) message.getContent();

    for (int i = 0; i < multipart.getCount(); i++) {
        BodyPart bodyPart = multipart.getBodyPart(i);
        if(!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) &&
               StringUtils.isBlank(bodyPart.getFileName())) {
            continue; // dealing with attachments only
        } 
        InputStream is = bodyPart.getInputStream();
        File f = new File("/tmp/" + bodyPart.getFileName());
        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();
        attachments.add(f);
    }
}
 94
Author: David Rabinowitz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-08 07:34:54

La pregunta es muy antigua, pero tal vez ayude a alguien. Me gustaría ampliar la respuesta de David Rabinowitz.

if(!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))

No debe devolver todos los atachments como usted espera, porque usted puede tener correo donde la parte mezclada está sin disposición definida.

   ----boundary_328630_1e15ac03-e817-4763-af99-d4b23cfdb600
Content-Type: application/octet-stream;
    name="00000000009661222736_236225959_20130731-7.txt"
Content-Transfer-Encoding: base64

Así que en este caso, también puede comprobar el nombre del archivo. Así:

if (!Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()) && StringUtils.isBlank(part.getFileName())) {...}

EDITAR

Hay código de trabajo completo usando la condición descrita anteriormente.. Porque cada parte puede encapsular otras partes y el accesorio debe anidarse, la recursión se usa para atravesar todas las partes

public List<InputStream> getAttachments(Message message) throws Exception {
    Object content = message.getContent();
    if (content instanceof String)
        return null;        

    if (content instanceof Multipart) {
        Multipart multipart = (Multipart) content;
        List<InputStream> result = new ArrayList<InputStream>();

        for (int i = 0; i < multipart.getCount(); i++) {
            result.addAll(getAttachments(multipart.getBodyPart(i)));
        }
        return result;

    }
    return null;
}

private List<InputStream> getAttachments(BodyPart part) throws Exception {
    List<InputStream> result = new ArrayList<InputStream>();
    Object content = part.getContent();
    if (content instanceof InputStream || content instanceof String) {
        if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()) || StringUtils.isNotBlank(part.getFileName())) {
            result.add(part.getInputStream());
            return result;
        } else {
            return new ArrayList<InputStream>();
        }
    }

    if (content instanceof Multipart) {
            Multipart multipart = (Multipart) content;
            for (int i = 0; i < multipart.getCount(); i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                result.addAll(getAttachments(bodyPart));
            }
    }
    return result;
}
 27
Author: mefi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-01 20:57:08

Un ahorro de tiempo para el código donde guarda el archivo adjunto :

Con la versión de correo javax 1.4 y después , se puede decir

bodyPart.saveFile("/tmp/" + bodyPart.getFileName());

En lugar de

    InputStream is = bodyPart.getInputStream();
    File f = new File("/tmp/" + bodyPart.getFileName());
    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();
 9
Author: kommradHomer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-04 14:16:08

Simplemente puede usar Apache Commons Mail API MimeMessageParser - getAttachmentList() junto con Commons IO y Commons Lang.

MimeMessageParser parser = ....
parser.parse();
for(DataSource dataSource : parser.getAttachmentList()) {

    if (StringUtils.isNotBlank(dataSource.getName())) {}

        //use apache commons IOUtils to save attachments
        IOUtils.copy(dataSource.getInputStream(), ..dataSource.getName()...)
    } else {
        //handle how you would want attachments without file names
        //ex. mails within emails have no file name
    }
}
 3
Author: Stackee007,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-02 19:57:12

Aquí está mi interpretación de la solución de mefi.

private static void attachments(
    final BodyPart body, final BiConsumer<String, InputStream> consumer)
    throws MessagingException, IOException {
    final Multipart content;
    try {
        content = (Multipart) body.getContent();
        for (int i = 0; i < content.getCount(); i++) {
            attachments(content.getBodyPart(i), consumer);
        }
        return;
    } catch (final ClassCastException cce) {
    }
    if (!Part.ATTACHMENT.equalsIgnoreCase(body.getDisposition())) {
        return;
    }
    final String name = body.getFileName();
    if (name == null || name.trim().isEmpty()) {
        return;
    }
    try (final InputStream stream = body.getInputStream()) {
        consumer.accept(name, stream);
    }
}

public static void attachments(
    final Message message, final BiConsumer<String, InputStream> consumer)
    throws IOException, MessagingException {
    final Multipart content;
    try {
        content = (Multipart) message.getContent();
    } catch (final ClassCastException cce) {
        return;
    }
    for (int i = 0; i < content.getCount(); i++) {
        attachments(content.getBodyPart(i), consumer);
    }
}
 0
Author: Jin Kwon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:07