当前位置:编程学习 > JSP >>

use javamail to send attachments(转)

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));
补充:Jsp教程,邮件
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,