Related differences

Ques 21. Sample code for Reading Multipart mail using JavaMail.

These days Multipart mail is used to compose emails with attachment. In the email you can attach images, zip files, xls, doc etc.. It allows you to create nicely design emails.

Java Mail API also provides classes to create, send and read the Multipart message. If you have given a task to create emails with attachment in Java technologies, then you can use the Java Mail api to accomplish your task.

Using the Multipart Class

Following code snippet shows how you can use the Multipart class. You have to create the object of Multipart class and then you can get the body part and compose or read your email.

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

And then read bodyPart content using getContent() method.


package com.withoutbook.common;

import java.util.*;
import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.*;

public class ReadMultipartMail {

public static void main(String args[]) throws Exception {

String host = "192.168.10.110";
String username = "arindam";
String passwoed = "arindam";

Properties properties = System.getProperties();
Session session = Session.getDefaultInstance(properties);

Store store = session.getStore("pop3");
store.connect(host, username, passwoed);

Folder folder = store.getFolder("inbox");

if (!folder.exists()) {
System.out.println("No INBOX...");
System.exit(0);
}
folder.open(Folder.READ_WRITE);
Message[] msg = folder.getMessages();

for (int i = 0; i < msg.length; i++) {
System.out.println("------------ Message " + (i + 1) + " ------------");
String from = InternetAddress.toString(msg[i].getFrom());
if (from != null) {
System.out.println("From: " + from);
}

String replyTo = InternetAddress.toString(
msg[i].getReplyTo());
if (replyTo != null) {
System.out.println("Reply-to: " + replyTo);
}
String to = InternetAddress.toString(
msg[i].getRecipients(Message.RecipientType.TO));
if (to != null) {
System.out.println("To: " + to);
}

String subject = msg[i].getSubject();
if (subject != null) {
System.out.println("Subject: " + subject);
}
Date sent = msg[i].getSentDate();
if (sent != null) {
System.out.println("Sent: " + sent);
}

System.out.println();
System.out.println("Message : ");

Multipart multipart = (Multipart) msg[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();
}
}

Is it helpful? Add Comment View Comments
 

Ques 22. Sample code for reading attachment message using JavaMail.

Java Mail API provides classes to send multiple Mime body part with one Mime Message. MulipltMimeBody parts can be text, file or image. All message are stored in Folder objects. folders can contain folders or messages. The Folder class declares methods that fetch, append, copy and delete messages, and message contain Attachment.


package com.withoutbook.common;

import java.io.*;
import java.util.*;
import javax.mail.*;

public class ReadAttachment {

public static void main(String args[]) throws Exception {
String host = "192.168.10.110";
String user = "arindam";
String password = "arindam";

// Get system properties
Properties properties = System.getProperties();

// Get the default Session object.
Session session = Session.getDefaultInstance(properties);

// Get a Store object that implements the specified protocol.
Store store = session.getStore("pop3");

//Connect to the current host using the specified username and password.
store.connect(host, user, password);

//Create a Folder object corresponding to the given name.
Folder folder = store.getFolder("inbox");

// Open the Folder.
folder.open(Folder.READ_WRITE);

Message[] message = folder.getMessages();


for (int a = 0; a < message.length; a++) {
System.out.println("-------------" + (a + 1) + "-----------");
System.out.println(message[a].getSentDate());

Multipart multipart = (Multipart) message[a].getContent();
//System.out.println(multipart.getCount());

for (int i = 0; i < multipart.getCount(); i++) {
//System.out.println(i);
//System.out.println(multipart.getContentType());
BodyPart bodyPart = multipart.getBodyPart(i);
InputStream stream = bodyPart.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(stream));

while (br.ready()) {
System.out.println(br.readLine());
}
System.out.println();
}
System.out.println();
}
folder.close(true);
store.close();
}
}

Is it helpful? Add Comment View Comments
 

Ques 23. Sample code for replying to messages using JavaMail.

The Message class have a reply() method to configure a new Message with the proper recipient and subject, adding "Re: " if not already there. This does not add any content to the message, reply() method have a boolean parameter indicating whether to reply to only the sender (false) or reply to all (true).

MimeMessage reply = (MimeMessage)message.reply(false);reply.setFrom(new InternetAddress("president@whitehouse.gov"));reply.setText("Thanks");Transport.send(reply);

To configure the reply-to address when sending a message, use the setReplyTo() method.


package com.withoutbook.common;

import java.io.*;
import java.util.*;

import javax.mail.*;
import javax.mail.internet.*;

public class ReplyMail {

public static void main(String args[]) throws Exception {

Date date = null;
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", "192.168.10.110");

Session session = Session.getDefaultInstance(properties);

Store store = session.getStore("pop3");
store.connect("192.168.10.110", "arindam", "arindam");

Folder folder = store.getFolder("inbox");
if (!folder.exists()) {
System.out.println("inbox not found");
System.exit(0);
}
folder.open(Folder.READ_ONLY);

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

Message[] message = folder.getMessages();
if (message.length != 0) {
System.out.println("no. From ttSubject ttDate");
for (int i = 0, n = message.length; i < n; i++) {
date = message[i].getSentDate();

System.out.println(" " + (i + 1) + ": " + message[i].getFrom()[0] + "t" +
message[i].getSubject() + " t" + date.getDate() + "/" +
date.getMonth() + "/" + (date.getYear() + 1900));
System.out.print("Do you want to reply [y/n] : ");
String ans = reader.readLine();
if ("Y".equals(ans) || "y".equals(ans)) {

// Create a reply message
MimeMessage reply = (MimeMessage) message[i].reply(false);

// Set the from field
reply.setFrom(message[i].getFrom()[0]);

// Create the reply content
// Create the reply content, copying over the original if text
MimeMessage orig = (MimeMessage) message[i];
StringBuffer buffer = new StringBuffer("Thanksnn");
if (orig.isMimeType("text/plain")) {
String content = (String) orig.getContent();
StringReader contentReader = new StringReader(content);
BufferedReader br = new BufferedReader(contentReader);
String contentLine;
while ((contentLine = br.readLine()) != null) {
buffer.append("> ");
buffer.append(contentLine);
buffer.append("rn");
}
}
// Set the content
reply.setText(buffer.toString());

// Send the message
Transport.send(reply);

} else if ("n".equals(ans)) {
break;
}
}

} else {
System.out.println("There is no msg....");
}

}
}

Is it helpful? Add Comment View Comments
 

Ques 24. Sample code for Forwarding Messages using JavaMail.

If u want forward a message to another user firstly get all header field and get message content then send its for another user.
Java code given below gives the functionality to forward same message to the next email address. With this code user can change Subject line and can edit the message content that is going to forward.


package com.withoutbook.common;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class ForwardMail {

public static void main(String args[]) throws Exception {
String host = "192.168.10.110";
String user = "arindam";
String password = "arindam";

// Get system properties
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", "192.168.10.110");

// Get the default Session object.
Session session = Session.getDefaultInstance(properties);

// Get a Store object that implements the specified protocol.
Store store = session.getStore("pop3");

//Connect to the current host using the specified username and password.
store.connect(host, user, password);

//Create a Folder object corresponding to the given name.
Folder folder = store.getFolder("inbox");

// Open the Folder.
folder.open(Folder.READ_ONLY);

Message message = folder.getMessage(1);

// Here's the big change...
String from = InternetAddress.toString(message.getFrom());
if (from != null) {
System.out.println("From: " + from);
}
String replyTo = InternetAddress.toString(
message.getReplyTo());
if (replyTo != null) {
System.out.println("Reply-to: " + replyTo);
}
String to = InternetAddress.toString(
message.getRecipients(Message.RecipientType.TO));
if (to != null) {
System.out.println("To: " + to);
}

String subject = message.getSubject();
if (subject != null) {
System.out.println("Subject: " + subject);
}
Date sent = message.getSentDate();
if (sent != null) {
System.out.println("Sent: " + sent);
}
System.out.println(message.getContent());

// Create the message to forward
Message forward = new MimeMessage(session);

// Fill in header
forward.setSubject("Fwd: " + message.getSubject());
forward.setFrom(new InternetAddress(from));
forward.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));

// Create your new message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Oiginal message:nn");

// Create a multi-part to combine the parts
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);

// Create and fill part for the forwarded content
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(message.getDataHandler());

// Add part to multi part
multipart.addBodyPart(messageBodyPart);

// Associate multi-part with message
forward.setContent(multipart);

// Send message
Transport.send(forward);

System.out.println("msg forward ....");
}
}

Is it helpful? Add Comment View Comments
 

Ques 25. How to show all header information of message using Java Mail api?

We will use method given below to retrieve all header information, this method returns Enumerations type.

public Enumeration getAllHeaders();


package com.withoutbook.common;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class AllHeaderClient {

public static void main(String[] args) throws Exception {
String host = "192.168.10.110";
String user = "arindam";
String password = "arindam";

// Get system properties
Properties properties = System.getProperties();

// Get the default Session object.
Session session = Session.getDefaultInstance(properties);

// Get a Store object that implements the specified protocol.
Store store = session.getStore("pop3");

//Connect to the current host using the specified username and password.
store.connect(host, user, password);

//Create a Folder object corresponding to the given name.
Folder folder = store.getFolder("inbox");

// Open the Folder.
folder.open(Folder.READ_ONLY);

Message[] messages = folder.getMessages();
for (int i = 0; i < messages.length; i++) {
System.out.println("------------ Message " + (i + 1) + " ------------");
// Here's the difference...
Enumeration headers = messages[i].getAllHeaders();
while (headers.hasMoreElements()) {
Header h = (Header) headers.nextElement();
System.out.println(h.getName() + ": " + h.getValue());
}
System.out.println();
}
}
}

Is it helpful? Add Comment View Comments
 

Most helpful rated by users: