Java Reference
In-Depth Information
e-mail message and an attachment. Messages that contain different parts are referred to
as Multipurpose Internet Mail Extensions (MIME) messages. They are represented in
the
javax.mail API
by the
MimeMessage
class. The following code creates such
a message:
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipient(Message.RecipientType.TO, new
InternetAddress(to));
message.setSubject("Subject");
// Create Mime "Message" part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent("This is a test message",
"text/plain");
// Create Mime "File" part
MimeBodyPart fileBodyPart = new MimeBodyPart();
fileBodyPart.attachFile("<path-to-attachment>/
attach.txt");
MimeBodyPart fileBodyPart2 = new MimeBodyPart();
fileBodyPart2.attachFile("<path-to-attachment>/
attach2.txt");
// Piece the body parts together
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(fileBodyPart);
//add another body part to supply another attachment
multipart.addBodyPart(fileBodyPart2);
// Set the content of the message to be the MultiPart
message.setContent(multipart);
Transport.send(message);
How It Works