21.What is Transport in JavaMail api?This is final part of sending Email, it is an abstract class. Default version of this class can be used by calling static send() method. message.saveChanges();
Transport transport = session.getTransport("smtp"); transport.connect(host, username, password); transport.sendMessage(message, message.getAllRecipients()); transport.close(); 22.What is Store and Folder in JavaMail api?After getting the session you connect to javax.mail.Store class with Authenticator or host, port, user and password information. Store object that implements the specified protocol can be created by by passing the protocol information to the getStore() method of the session object. Store store = session.getStore("pop3");
After connecting to store you need to get a folder that holds messages. For POP3, the only folder available is the INBOX but with IMAP, you can have other folders available. For this you can use javax.mail.Folder class.
store.connect(host, username, password); Folder folder = store.getFolder("INBOX");
Once you have read messages, you need to close Store and Folder.
folder.open(Folder.READ_ONLY); Message message[] = folder.getMessages(); folder.close(booleanValue);
store.close(); 23.Sample code for Reading message using Java Mail?The Folder class declares methods that fetch, append, copy and delete messages. These are some of the methods used in the program. import java.io.*;
import java.util.*; import javax.mail.*; public class ReadMail { public static void main(String args[]) throws Exception { String host = "192.168.10.110"; String user = "test"; String password = "test"; // 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[] message = folder.getMessages(); // Display message. for (int i = 0; i < message.length; i++) { System.out.println("------------ Message " + (i + 1) + " ------------"); System.out.println("SentDate : " + message[i].getSentDate()); System.out.println("From : " + message[i].getFrom()[0]); System.out.println("Subject : " + message[i].getSubject()); System.out.print("Message : "); InputStream stream = message[i].getInputStream(); while (stream.available() != 0) { System.out.print((char) stream.read()); } System.out.println(); } folder.close(true); store.close(); } } 24.Sample code for sending multipart mail using JavaMail?Multipart is like a container that holds one or more body parts. When u send a multipart mail firstly create a Multipart class object and then create BodyPart class object, set text in BodyPart class object and add all BodyPart class object in Multipart class object and send the message. Class Multipart that we will use in this code is an abstract class. Method used in this program of Multipart class is: void addBodyPart(BodyPart part);
This method is used to add parts in multipart. package com.withoutbook.common; import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class SendMultipartMail { public static void main(String args[]) throws Exception { String host = "192.168.10.110"; String from = "test@localhost"; String to = "arindam@localhost"; Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); Session session = Session.getDefaultInstance(properties); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); msg.setSubject("MultiPart Mail"); Multipart multipart = new MimeMultipart(); BodyPart part1 = new MimeBodyPart(); part1.setText("This is multipart mail and you read part1......"); BodyPart part2 = new MimeBodyPart(); part2.setText("This is multipart mail and you read part2......"); multipart.addBodyPart(part1); multipart.addBodyPart(part2); msg.setContent(multipart); Transport.send(msg); System.out.println("Message send...."); } } 25.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. 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(); } } 26.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(); } } 27.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 \t\tSubject \t\tDate"); 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("Thanks\n\n"); 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("\r\n"); } } // 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...."); } } } 28.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.
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:\n\n"); // 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 ...."); } } 29.Sample code for deleting messages using JavaMail?If you want to delete any message then set the message flag delete. There are different types of flags, some system-defined and some user-defined.
folder.close(true);
package com.withoutbook.common; import com.sun.mail.imap.protocol.FLAGS; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Date; import java.util.Properties; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Session; import javax.mail.Store; import javax.mail.internet.InternetAddress; public class DeleteMail { public static void main(String args[]) throws Exception { Properties properties = System.getProperties(); 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_WRITE); Message[] msg = folder.getMessages(); //System.out.println((messages.length+1)+" message found"); for (int i = 0; i < msg.length; i++) { System.out.println("--------- " + (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("Message : "); System.out.println(msg[i].getContent()); } System.out.println("Enter message no to delete :"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String no = br.readLine(); msg[Integer.parseInt(no) - 1].setFlag(FLAGS.Flag.DELETED, true); System.out.println("Msg Delete ....."); folder.close(true); store.close(); } } 30.Sample code to send HTML mail with images using JavaMail?A client create new message by using Message subclass. It sets attributes like recipient address and the subject, and inserts the content into the Message object, and inserts the content into the Message object. Finally, it sends the Message by invoking the Transport.send() method. package com.withoutbook.common;
import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class HTMLMail { public static void main(String args[]) throws Exception { String host = "192.168.10.110"; String from = "arindam@localhost"; String to = "arindam@localhost"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set the RFC 822 "From" header field using the // value of the InternetAddress.getLocalAddress method. message.setFrom(new InternetAddress(from)); // Add the given addresses to the specified recipient type. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set the "Subject" header field. message.setSubject("hi..!"); String htmlText = " Hello // Sets the given String as this part's content, // with a MIME type of "text/plain". message.setContent(htmlText, "text/html"); // Send message Transport.send(message); System.out.println("Message Send....."); } } 31.?
32.?
33.?
34.?
35.?
36.?
37.?
38.?
39.?
40.?
|