2010-04-24 7 views
1

J'utilise Apache commons File upload API pour Stocker le fichier de JSP dans les servlets du dossier temporaire, mais je ne sais pas comment faire pour envoyer l'email en pièce jointe en utilisant API javamail. Comment puis-je récupérer ces fichiers écrits dans le répertoire temporaire à l'aide de l'API Apache Fileupload pour les envoyer en pièce jointe à Mail Server. Comment l'écriture de ces fichiers en mémoire ou sur disque m'aidera-t-elle?Comment activer la pièce jointe à l'aide du fichier Apache upload

Répondre

1

Voici un exemple:

private static void notify(String subject, String text, 
     File attachment, String from, String to) throws Exception { 
    Context context = new InitialContext(); 
    Session sess = (Session)context.lookup("java:comp/env/mail/session"); 
    MimeMessage message = new MimeMessage(sess); 
    message.setSubject(subject, "UTF-8"); 
    if (attachment == null) { 
     message.setText(text, "UTF-8"); 
    } else { 
     MimeMultipart mp = null; 
     MimeBodyPart part1 = new MimeBodyPart(); 
     part1.setText(text, "UTF-8"); 
     MimeBodyPart part2 = new MimeBodyPart(); 
     part2.setDataHandler(new DataHandler(new FileDataSource(attachement))); 
     part2.setFileName(file.getName()); 
     mp = new MimeMultipart(); 
     mp.addBodyPart(part1); 
     mp.addBodyPart(part2); 
     message.setContent(mp); 
    } 

    message.setFrom(new InternetAddress(from)); 
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); 
    Transport.send(message); 
} 

Dans cet exemple, un FileDataSource est utilisé, ce qui signifie que la pièce jointe doit d'abord être enregistré en tant que fichier. J'utilise parfois un MemoryDataSource fait maison. Voici le code:

package com.lagalerie.mail; 

import java.io.ByteArrayInputStream; 
import java.io.ByteArrayOutputStream; 
import java.io.InputStream; 
import java.io.OutputStream; 

import javax.activation.DataSource; 

public class MemoryDataSource implements DataSource { 
    private String name; 
    private String contentType; 
    private byte content[] = {}; 

    public MemoryDataSource(String name, String contentType) { 
     this.name = name; 
     this.contentType = contentType; 
    } 

    public String getContentType() { 
     return contentType; 
    } 

    public InputStream getInputStream() { 
     return new ByteArrayInputStream(content); 
    } 

    public String getName() { 
     return name; 
    } 

    public OutputStream getOutputStream() { 
     return new ByteArrayOutputStream() { 
      @Override 
      public void close() { 
       content = toByteArray(); 
      } 
     }; 
    } 
}