JavaMail API Sending Attachments
Tasks
1. The skeleton code already includes the code to get the initial mail session.
2. From the session, get a Message and set its header fields: to, from, and subject.
3. Create a BodyPart for the main message cotent and fill its content with the text of the message.
4. Create a Multipart to combine the main content with the attachment. Add the main content to the multipart.
5. Create a second BodyPart for the attachment.
6. Get the attachment as a DataSource.
7. Set the DataHandler for the message part to the data source. Carry the original filename along.
8. Add the second part of the message to the multipart.
9. Set the content of the message to the multipart.
11. Compile and run the program, passing your SMTP server, from address, to address, and filename on the command line. This will send the file as an attachment.
12. Check to make sure you received the message with your normal mail reader (Eudora, Outlook Express, pine, ...).
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class AttachExample {
public static void main (String args[]) throws Exception {
String host = args[0];
String from = args[1];
String to = args[2];
String filename = args[3];
// Get system properties
Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", host);
// Get session
Session session = Session.getInstance(props, null);
// 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("Here's the file");
// Create a Multipart
Multipart multipart = new MimeMultipart();
// Add part one
multipart.addBodyPart(messageBodyPart);
//
// Part two is attachment
//
// Create second body part
messageBodyPart = new MimeBodyPart();
// Get the attachment
DataSource source = new FileDataSource(filename);
// Set the data handler to the attachment
messageBodyPart.setDataHandler(new DataHandler(source));
// Set the filename
messageBodyPart.setFileName(filename);
// Add part two
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(multipart);
// Send the message
Transport.send(message);
}
}
Demonstration
Executing the following command (replacing the mail server, from address, to address, and filename) sends a message with an attachment:
java AttachExample SMTP.Server from@address to@address filename
***********************************************************************
No comments:
Post a Comment