一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

use javamail to send attachments(转)

时间:2008-01-12 编辑:简简单单 来源:一聚教程网

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

热门栏目