use javamail to send attachments(转)

发表于:2007-07-04来源:作者:点击数: 标签:
Attachments are resources associated with a mail message, usually kept outside of the message like a text file, spreadsheet, or image. As with common mail programs like Eudora and pine, you can attach resources to your mail message with the
Attachments are resources associated with a mail message, usually kept outside of the message like a text file, spreadsheet, or image. As with common mail programs like Eudora and pine, you can attach resources to your mail message with the JavaMail API and get those attachments when you receive the message.

Sending attachments:
Sending attachments is quite like forwarding messages. You build up the parts to make the complete message. After the first part, your message text, you add other parts where the DataHandler for each is your attachment, instead of the shared handler in the case of a forwarded message. If you are reading the attachment from a file, your attachment data source is a FileDataSource. Reading from a URL, it is a URLDataSource. Once you have your DataSource, just pass it on to the DataHandler constructor, before finally attaching it to the BodyPart with setDataHandler(). Assuming you want to retain the original filename for the attachment, the last thing to do is to set the filename associated with the attachment with the setFileName() method of BodyPart. All this is shown here:


  // Define message
  Message message = new MimeMessage(session);
  message.setFrom(new Inte.netAddress(from));
  message.addRecipient(Message.RecipientType.TO,
    new InternetAddress(to));
  message.setSubject("Hello JavaMail Attachment");
  
  // Create the message part
  BodyPart messageBodyPart = new MimeBodyPart();
  
  // Fill the message
  messageBodyPart.setText("Pardon Ideas");
  
  Multipart multipart = new MimeMultipart();
  multipart.addBodyPart(messageBodyPart);
  
  // Part two is attachment
  messageBodyPart = new MimeBodyPart();
  DataSource source = new FileDataSource(filename);
  messageBodyPart.setDataHandler(new DataHandler(source));
  messageBodyPart.setFileName(filename);
  multipart.addBodyPart(messageBodyPart);
  
  // Put parts in message
  message.setContent(multipart);
  
  // Send the message
  Transport.send(message);
  
When including attachments with your messages, if your program is a servlet, your users must upload the attachment besides telling you where to send the message. Uploading each file can be handled with a form encoding type of multipart/form-data.


<FORM ENCTYPE="multipart/form-data"
    method=post action="/myservlet">
  <INPUT TYPE="file" NAME="thefile">
  <INPUT TYPE="submit" VALUE="Upload">
</FORM>

Note: Message size is limited by your SMTP server, not the JavaMail API. If you run into problems, consider increasing the Java heap size by setting the ms and mx parameters.

Exercise:
Exercise 5. How to send attachments

Getting attachments:
Getting attachments out of your messages is a little more involved then sending them because MIME has no simple notion of attachments. The content of your message is a Multipart object when it has attachments. You then need to process each Part, to get the main content and the attachment(s). Parts marked with a disposition of Part.ATTACHMENT from part.getDisposition() are clearly attachments. However, attachments can also come across with no disposition (and a non-text MIME type) or a disposition of Part.INLINE. When the disposition is either Part.ATTACHMENT or Part.INLINE, you can save off the content for that message part. Just get the original filename with getFileName() and the input stream with getInputStream().


Multipart mp = (Multipart)message.getContent();

for (int i=0, n=multipart.getCount(); i<n; i++) {
  Part part = multipart.getBodyPart(i));
  
  String disposition = part.getDisposition();
    
  if ((disposition != null) &&
       ((disposition.equals(Part.ATTACHMENT) ||
          (disposition.equals(Part.INLINE))) {
    saveFile(part.getFileName(), part.getInputStream());
  }
}

The saveFile() method just creates a File from the filename, reads the bytes from the input stream, and writes them off to the file. In case the file already exists, a number is added to the end of the filename until one is found that doesn''t exist.


// from saveFile()
File file = new File(filename);
for (int i=0; file.exists(); i++) {
  file = new File(filename+i);
}

The code above covers the simplest case where message parts are flagged appropriately. To cover all cases, handle when the disposition is null and get the MIME type of the part to handle aclearcase/" target="_blank" >ccordingly.


if (disposition == null) {
  // Check if plain
  MimeBodyPart mbp = (MimeBodyPart)part;
  if (mbp.isMimeType("text/plain")) {
     // Handle plain
  } else {
     // Special non-attachment cases here of image/gif, text/html, ...
  }
  ...
}

原文转自:http://www.ltesting.net