JAVA MAIL API

JavaMail Projects

JavaMail Project 1

Read MultiPart Mail Using JavaMail API
Previous Home Next
adplus-dvertising

In this example showing to read multipart mails using JavaMail API. when you want to read multi part messages, then firstly create multi part class object, then in this Multi part mail use to compose emails with attachment, In this mail you can attach images, zip files, xls, doc etc. The Multi Part messages are read ,send ,create to classes are providing by JavaMail API. If you have given the task to creating emails or messages with attachment in java technology. then you can use JavaMail API.

Multipart multipart = (Multipart)message[i].getContent();
After that create BodyPart object BodyPart bodyPart = multipart.getBodyPart(x);

package R4R;
import java.util.*;
import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.*;
public class Multipartmailread {
  public static void main(String args[]) throws Exception {
  String host = "192.168.10.205";
  String username = "r4r@localhost";
  String password = "r4rrajesh";
  Properties properties = System.getProperties();
  Session session = Session.getDefaultInstance(properties);
  Store store = session.getStore("pop3");
  store.connect(host, username, password);
  Folder folder = store.getFolder("inbox");
  if (!folder.exists()) {
  System.out.println("Don't inbuilt INBOX...");
  System.exit(0);
  }
  folder.open(Folder.READ_WRITE);
  Message[] message = folder.getMessages();
  for (int i = 0; i < message.length; i++) {
  System.out.println("------------ Message " + (i + 1) + " ------------");
  String from = InternetAddress.toString(message[i].getFrom());
  if (from != null) {
  System.out.println("From: " + from);
  }
  String replyTo = InternetAddress.toString(
		  message[i].getReplyTo());
  if (replyTo != null) {
  System.out.println("Reply-to: " + replyTo);
  }
  String to = InternetAddress.toString(
		  message[i].getRecipients(Message.RecipientType.TO));
  if (to != null) {
  System.out.println("To: " + to);
  }
  String subject =message[i].getSubject();
  if (subject != null) {
  System.out.println("Subject: " + subject);
  }
  Date sent = message[i].getSentDate();
  if (sent != null) {
  System.out.println("Sent: " + sent);
  }
System.out.println(); System.out.println("Message : "); Multipart multipart = (Multipart) message[i].getContent(); for (int x = 0; x < multipart.getCount(); x++) { BodyPart bodyPart = multipart.getBodyPart(x); String disposition = bodyPart.getDisposition(); if (disposition != null && (disposition.equals(BodyPart.ATTACHMENT))) { System.out.println("Mail have some attachment : "); DataHandler handler = bodyPart.getDataHandler(); System.out.println("file name : " + handler.getName()); } else { System.out.println(bodyPart.getContent()); } } System.out.println(); } folder.close(true); store.close(); } }
Previous Home Next