JavaMail – Quota Management

JavaMail API – Quota Management ”; Previous Next A quota in JavaMail is a limited or fixed number or amount of messages in a email store. Each Mail service request counts toward the JavaMail API Calls quota. An email service can apply following quota criterion: Maximum size of outgoing mail messages, including attachments. Maximum size of incoming mail messages, including attachments. Maximum size of message when an administrator is a recipient For Quota management JavaMail has following classes: Class Description public class Quota This class represents a set of quotas for a given quota root. Each quota root has a set of resources, represented by the Quota.Resource class. Each resource has a name (for example, “STORAGE”), a current usage, and a usage limit. This has only one method setResourceLimit(String name, long limit). public static class Quota.Resource Represents an individual resource in a quota root. public interface QuotaAwareStore An interface implemented by Stores that support quotas. The getQuota and setQuota methods support the quota model defined by the IMAP QUOTA extension. GmailSSLStore, GmailStore, IMAPSSLStore, IMAPStore are the known implementing classes of this interface. Let us see and example in the following sections which checks for mail storage name, limit and its usage. Create Java Class Create a java class file QuotaExample, the contents of which are as follows: package com.tutorialspoint; import java.util.Properties; import javax.mail.Quota; import javax.mail.Session; import javax.mail.Store; import com.sun.mail.imap.IMAPStore; public class QuotaExample { public static void main(String[] args) { try { Properties properties = new Properties(); properties.put(“mail.store.protocol”, “imaps”); properties.put(“mail.imaps.port”, “993”); properties.put(“mail.imaps.starttls.enable”, “true”); Session emailSession = Session.getDefaultInstance(properties); // emailSession.setDebug(true); // create the IMAP3 store object and connect with the pop server Store store = emailSession.getStore(“imaps”); //change the user and password accordingly store.connect(“imap.gmail.com”, “[email protected]”, “*****”); IMAPStore imapStore = (IMAPStore) store; System.out.println(“imapStore —” + imapStore); //get quota Quota[] quotas = imapStore.getQuota(“INBOX”); //Iterate through the Quotas for (Quota quota : quotas) { System.out.println(String.format(“quotaRoot:”%s””, quota.quotaRoot)); //Iterate through the Quota Resource for (Quota.Resource resource : quota.resources) { System.out.println(String.format( “name:”%s”, limit:”%s”, usage:”%s””, resource.name, resource.limit, resource.usage)); } } } catch (Exception e) { e.printStackTrace(); } } } Here are connection to the gmail service via IMAP (imap.gmail.com) server, as IMAPStore implements the QuotaAwareStore. Once you get the Store object, fetch the Quota array and iterate through it and print the relevant information. Compile and Run Now that our class is ready, let us compile the above class. I”ve saved the class QuotaExample.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt: javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: QuotaExample.java Now that the class is compiled, execute the below command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: QuotaExample Verify Output You should see a similar message on the command console: imapStore —imaps://abc%[email protected] quotaRoot:”” name:”STORAGE”, limit:”15728640”, usage:”513” Print Page Previous Next Advertisements ”;

JavaMail – Bounced Messages

JavaMail API – Bounced Messages ”; Previous Next A message can be bounced for several reasons. This problem is discussed in depth at rfc1211. Only a server can determine the existence of a particular mailbox or user name. When the server detects an error, it will return a message indicating the reason for the failure to the sender of the original message. There are many Internet standards covering Delivery Status Notifications but a large number of servers don”t support these new standards, instead using ad hoc techniques for returning such failure messages. Hence it get very difficult to correlate the bounced message with the original message that caused the problem. JavaMail includes support for parsing Delivery Status Notifications. There are a number of techniques and heuristics for dealing with this problem. One of the techniques being Variable Envelope Return Paths. You can set the return path in the enveloper as shown in the example below. This is the address where bounce mails are sent to. You may want to set this to a generic address, different than the From: header, so you can process remote bounces. This done by setting mail.smtp.from property in JavaMail. Create Java Class Create a java class file SendEmail, the contents of which are as follows: import java.util.Properties; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendEmail { public static void main(String[] args) throws Exception { String smtpServer = “smtp.gmail.com”; int port = 587; final String userid = “youraddress”;//change accordingly final String password = “*****”;//change accordingly String contentType = “text/html”; String subject = “test: bounce an email to a different address ” + “from the sender”; String from = “[email protected]”; String to = “[email protected]”;//some invalid address String bounceAddr = “[email protected]”;//change accordingly String body = “Test: get message to bounce to a separate email address”; Properties props = new Properties(); props.put(“mail.smtp.auth”, “true”); props.put(“mail.smtp.starttls.enable”, “true”); props.put(“mail.smtp.host”, smtpServer); props.put(“mail.smtp.port”, “587”); props.put(“mail.transport.protocol”, “smtp”); props.put(“mail.smtp.from”, bounceAddr); Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userid, password); } }); MimeMessage message = new MimeMessage(mailSession); message.addFrom(InternetAddress.parse(from)); message.setRecipients(Message.RecipientType.TO, to); message.setSubject(subject); message.setContent(body, contentType); Transport transport = mailSession.getTransport(); try { System.out.println(“Sending ….”); transport.connect(smtpServer, port, userid, password); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); System.out.println(“Sending done …”); } catch (Exception e) { System.err.println(“Error Sending: “); e.printStackTrace(); } transport.close(); }// end function main() } Here we can see that the property mail.smtp.from is set different from the from address. Compile and Run Now that our class is ready, let us compile the above class. I”ve saved the class SendEmail.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt: javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmail.java Now that the class is compiled, execute the below command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmail Verify Output You should see the following message on the command console: Sending …. Sending done … Print Page Previous Next Advertisements ”;

JavaMail – Core Classes

JavaMail API – Core Classes ”; Previous Next The JavaMail API consists of some interfaces and classes used to send, read, and delete e-mail messages. Though there are many packages in the JavaMail API, will cover the main two packages that are used in Java Mail API frequently: javax.mail and javax.mail.internet package. These packages contain all the JavaMail core classes. They are: Class Description javax.mail.Session The key class of the API. A multithreaded object represents the connection factory. javax.mail.Message An abstract class that models an e-mail message. Subclasses provide the actual implementations. javax.mail.Address An abstract class that models the addresses (from and to addresses) in a message. Subclasses provide the specific implementations. javax.mail.Authenticator An abstract class used to protect mail resources on the mail server. javax.mail.Transport An abstract class that models a message transport mechanism for sending an e-mail message. javax.mail.Store An abstract class that models a message store and its access protocol, for storing and retrieving messages. A Store is divided into Folders. javax.mail.Folder An abstract class that represents a folder of mail messages. It can contain subfolders. javax.mail.internet.MimeMessage Message is an abstract class, hence must work with a subclass; in most cases, you’ll use a MimeMessage. A MimeMessage is an e-mail message that understands MIME types and headers. javax.mail.internet.InternetAddress This class represents an Internet email address using the syntax of RFC822. Typical address syntax is of the form [email protected] or Personal Name <[email protected]>. Let us study each of these classes in detail and in the subsequent chapters we shall study examples using each of these. Session Class The Session class is the primary class of the JavaMail API and it is not subclassed. The Session object acts as the connection factory for the JavaMail API, which handles both configuration setting and authentication. Session object can be created in the following ways: By looking up the administered object stored in the JNDI service InitialContext ctx = new InitialContext(); Session session = (Session) ctx.lookup(“usersMailSession”); usersMailSession is the JNDI name object used as the administered object for the Session object. usersMailSession can be created and configured with the required parameters as name/value pairs, including information such as the mail server hostname, the user account sending the mail, and the protocols supported by the Session object. Another method of creating the Session object is based on the programmatic approach in which you can use a java.util.Properties object to override some of the default information, such as the mail server name, username, password, and other information that can be shared across your entire application. The constructor for Session class is private. Hence the Session class provides two methods (listed below) which get the Session object. getDefaultInstance(): There are two methods to get the session object by using the getDefaultInstance() method. It returns the default session. public static Session getDefaultInstance(Properties props) public static Session getDefaultInstance(Properties props,Authenticator auth) getInstance(): There are two methods to get the session object by using the getInstance() method. It returns the new session. public static Session getInstance(Properties props) public static Session getInstance(Properties props,Authenticator auth) Message Class With Session object created we now move on to creating a message that will be sent. The message type will be javax.mail.Message. Message is an abstract class. Hence its subclass javax.mail.internet.MimeMessage class is mostly used. To create the message, you need to pass session object in MimeMessage class constructor. For example: MimeMessage message=new MimeMessage(session); Once the message object is created we need to store information in it. Message class implements the javax.mail.Part interface while javax.mail.internet. MimeMessage implements javax.mail.internet.MimePart. You can either use message.setContent() or mimeMessage.setText() to store the content. Commonly used methods of MimeMessage class are Method Description public void setFrom(Address address) used to set the from header field. public void addRecipients(Message.RecipientType type, String addresses) used to add the given address to the recipient type. public void setSubject(String subject) used to set the subject header field. public void setText(String textmessage) used to set the text as the message content using text/plain MIME type. Address Class Now that we have a Session and Message (with content stored in it) objects, we need to address the letter by using Address object. Address is an abstract class. Hence its subclass javax.mail.internet.InternetAddress class is mostly used. Address can be created by just passing email address: Address address = new InternetAddress(“[email protected]”); Another way of creating Address is by passing name alogwith the email address: Address address = new InternetAddress(“[email protected]”, Manisha); You can also set the To, From, CC, BCC fields as below message.setFrom(address) message.addRecipient(type, address) Three predefined address types are objects with one of these values: Message.RecipientType.TO Message.RecipientType.CC Message.RecipientType.BCC Authenticator Class The class Authenticator represents an object that knows how to obtain authentication for a network connection. Usually, it will do this by prompting the user for information. Authenticator is an abstract class. You create a subclass PasswordAuthentication, passing a username and password to its constructor. You must register the Authenticator with the Session when you create session object. Following is an example of Authenticator use: Properties props = new Properties(); //Override props with any customized data PasswordAuthentication auth = new PasswordAuthentication(“manisha”, “pswrd”) Session session = Session.getDefaultInstance(props, auth); Transport Class Transport class is used as a message transport mechanism. This class normally uses the SMTP protocol to send a message. It is an abstract class. You can use the default version of the class by just calling the static send() method: Transport.send(message); The other way to send message is by getting a specific instance from the session for your protocol, pass along the username and password (blank if unnecessary), send the message, and close the connection: message.saveChanges(); // implicit with send() //Get transport for session Transport transport = session.getTransport(“smtp”); //Connect transport.connect(host, username, password); //repeat if necessary transport.sendMessage(message, message.getAllRecipients()); //Done, close the connection transport.close(); Store Class An abstract class that models a message store and its access protocol, for storing and retrieving messages. Subclasses provide actual implementations. Store extends the Service class, which provides many common methods for naming stores, connecting to stores, and listening to

JavaMail – Environment Setup

JavaMail API – Environment Setup ”; Previous Next To send an e-mail using your Java Application is simple enough but to start with you should have JavaMail API and Java Activation Framework (JAF) installed on your machine. You will need the JavaBeans Activation Framework (JAF) extension that provides the javax.activation package only when you”re not using Java SE 6 or newer. You can download latest version of JavaMail (Version 1.5.0) from Java”s standard website. You can download latest version of JAF (Version 1.1.1) from Java”s standard website. Download and unzip these files, in the newly created top level directories you will find a number of jar files for both the applications. You need to add mail.jar and activation.jar files in your CLASSPATH. SMTP server To send emails, you must have SMTP server that is responsible to send mails. You can use one of the following techniques to get the SMTP server: Install and use any SMTP server such as Postfix server (for Ubuntu), Apache James server (Java Apache Mail Enterprise Server)etc. (or) Use the SMTP server provided by the host provider for eg: free SMTP provide by JangoSMTP site is relay.jangosmtp.net (or) Use the SMTP Server provided by companies e.g. gmail, yahoo, etc. The examples in the subsequent chapters, we”ve used the free JangoSMTP server to send email. You can create an account by visiting this site and configure your email adress. Print Page Previous Next Advertisements ”;

JavaMail – Useful Resources

JavaMail API – Useful Resources ”; Previous Next If you want to list down your website, book or any other resource on this page, then please contact at [email protected] Useful Websites on JavaMail API Download JavaMail – Download JavaMail API and associated documentation. Download JavaBeans Activation Framework (JAF) – Download JavaMail API and associated documentation Java 2 SDK, Standard Edition – Official site for Java 2 SDK, Standard Edition. Free Java Download – Download Java for your desktop computer now! Print Page Previous Next Advertisements ”;

JavaMail – Quick Guide

JavaMail API – Quick Guide ”; Previous Next The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. The JavaMail API provides a set of abstract classes defining objects that comprise a mail system. It is an optional package (standard extension) for reading, composing, and sending electronic messages. JavaMail provides elements that are used to construct an interface to a messaging system, including system components and interfaces. While this specification does not define any specific implementation, JavaMail does include several classes that implement RFC822 and MIME Internet messaging standards. These classes are delivered as part of the JavaMail class package. Following are some of the protocols supported in JavaMail API: SMTP: Acronym for Simple Mail Transfer Protocol. It provides a mechanism to deliver email. POP: Acronym for Post Office Protocol. POP is the mechanism most people on the Internet use to get their mail. It defines support for a single mailbox for each user. RFC 1939 defines this protocol. IMAP: Acronym for Internet Message Access Protocol. It is an advanced protocol for receiving messages. It provides support for multiple mailbox for each user, in addition to, mailbox can be shared by multiple users. It is defined in RFC 2060. MIME: Acronym for Multipurpose Internet Mail Extensions. . It is not a mail transfer protocol. Instead, it defines the content of what is transferred: the format of the messages, attachments, and so on. There are many different documents that take effect here: RFC 822, RFC 2045, RFC 2046, and RFC 2047. As a user of the JavaMail API, you usually don”t need to worry about these formats. However, these formats do exist and are used by your programs. NNTP and Others:There are many protocols that are provided by third-party providers. Some of them are Network News Transfer Protocol (NNTP), Secure Multipurpose Internet Mail Extensions (S/MIME) etc. Details of these will be covered in the subsequent chapters. Architecture As said above the java application uses JavaMail API to compose, send and receive emails.The following figure illustrates the architecture of JavaMail: The abstract mechanism of JavaMail API is similar to other J2EE APIs, such as JDBC, JNDI, and JMS. As seen the architecture diagram above, JavaMail API is divided into two main parts: An application-independent part: An application-programming interface (API) is used by the application components to send and receive mail messages, independent of the underlying provider or protocol used. A service-dependent part: A service provider interface (SPI) speaks the protocol-specific languages, such as SMTP, POP, IMAP, and Network News Transfer Protocol (NNTP). It is used to plug in a provider of an e-mail service to the J2EE platform. Environment Setup To send an e-mail using your Java Application is simple enough but to start with you should have JavaMail API and Java Activation Framework (JAF) installed on your machine. You will need the JavaBeans Activation Framework (JAF) extension that provides the javax.activation package only when you”re not using Java SE 6 or newer. You can download latest version of JavaMail (Version 1.5.0) from Java”s standard website. You can download latest version of JAF (Version 1.1.1) from Java”s standard website. Download and unzip these files, in the newly created top level directories you will find a number of jar files for both the applications. You need to add mail.jar and activation.jar files in your CLASSPATH. SMTP server To send emails, you must have SMTP server that is responsible to send mails. You can use one of the following techniques to get the SMTP server: Install and use any SMTP server such as Postfix server (for Ubuntu), Apache James server (Java Apache Mail Enterprise Server)etc. (or) Use the SMTP server provided by the host provider for eg: free SMTP provide by JangoSMTP site is relay.jangosmtp.net (or) Use the SMTP Server provided by companies e.g. gmail, yahoo, etc. The examples in the subsequent chapters, we”ve used the free JangoSMTP server to send email. You can create an account by visiting this site and configure your email adress. Core Classes The JavaMail API consists of some interfaces and classes used to send, read, and delete e-mail messages. Though there are many packages in the JavaMail API, will cover the main two packages that are used in Java Mail API frequently: javax.mail and javax.mail.internet package. These packages contain all the JavaMail core classes. They are: Class Description javax.mail.Session The key class of the API. A multithreaded object represents the connection factory. javax.mail.Message An abstract class that models an e-mail message. Subclasses provide the actual implementations. javax.mail.Address An abstract class that models the addresses (from and to addresses) in a message. Subclasses provide the specific implementations. javax.mail.Authenticator An abstract class used to protect mail resources on the mail server. javax.mail.Transport An abstract class that models a message transport mechanism for sending an e-mail message. javax.mail.Store An abstract class that models a message store and its access protocol, for storing and retrieving messages. A Store is divided into Folders. javax.mail.Folder An abstract class that represents a folder of mail messages. It can contain subfolders. javax.mail.internet.MimeMessage Message is an abstract class, hence must work with a subclass; in most cases, you’ll use a MimeMessage. A MimeMessage is an e-mail message that understands MIME types and headers. javax.mail.internet.InternetAddress This class represents an Internet email address using the syntax of RFC822. Typical address syntax is of the form [email protected] or Personal Name <[email protected]>. Sending Simple Emails Here is an example to send a simple email. Here we have used JangoSMTP server via which emails are sent to our destination email address. The setup is explained in the Environment Setup chapter. To send a simple email steps followed are: Get a Session Create a default MimeMessage object and set From, To, Subject in the message. Set the actual message as: message.setText(“your text goes here”); Send the message using the Transport object. Create Java Class Create a java class file SendEmail, the contents of which are as follows: package com.tutorialspoint; import java.util.Properties; import javax.mail.Message; import

JavaMail – Deleting Emails

JavaMail API – Deleting Emails ”; Previous Next In this chapter we will see how to delete an email using JavaMail API. Deleting messages involves working with the Flags associated with the messages. There are different flags for different states, some system-defined and some user-defined. The predefined flags are defined in the inner class Flags.Flag and are listed below: Flags.Flag.ANSWERED Flags.Flag.DELETED Flags.Flag.DRAFT Flags.Flag.FLAGGED Flags.Flag.RECENT Flags.Flag.SEEN Flags.Flag.USER POP protocol supports only deleting of the messages. Basic steps followed in the delete program are: Get the Session object with POP and SMPT server details in the properties. We would need POP details to retrieve messages and SMPT details to send messages. Create POP3 store object and connect to the store. Create Folder object and open the appropriate folder in your mailbox in READ_WRITE mode. Retrieves messages from inbox folder. Iterate through the messages and type “Y” or “y” if you want to delete the message by invoking the method setFlag(Flags.Flag.DELETED, true) on the Message object. The messages marked DELETED are not actually deleted, until we call the expunge() method on the Folder object, or close the folder with expunge set to true. Close the store object. Create Java Class Create a java class file ForwardEmail, the contents of which are as follows: package com.tutorialspoint; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Properties; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.NoSuchProviderException; import javax.mail.Session; import javax.mail.Store; public class DeleteEmail { public static void delete(String pop3Host, String storeType, String user, String password) { try { // get the session object Properties properties = new Properties(); properties.put(“mail.store.protocol”, “pop3”); properties.put(“mail.pop3s.host”, pop3Host); properties.put(“mail.pop3s.port”, “995”); properties.put(“mail.pop3.starttls.enable”, “true”); Session emailSession = Session.getDefaultInstance(properties); // emailSession.setDebug(true); // create the POP3 store object and connect with the pop server Store store = emailSession.getStore(“pop3s”); store.connect(pop3Host, user, password); // create the folder object and open it Folder emailFolder = store.getFolder(“INBOX”); emailFolder.open(Folder.READ_WRITE); BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); // retrieve the messages from the folder in an array and print it Message[] messages = emailFolder.getMessages(); System.out.println(“messages.length—” + messages.length); for (int i = 0; i < messages.length; i++) { Message message = messages[i]; System.out.println(“———————————“); System.out.println(“Email Number ” + (i + 1)); System.out.println(“Subject: ” + message.getSubject()); System.out.println(“From: ” + message.getFrom()[0]); String subject = message.getSubject(); System.out.print(“Do you want to delete this message [y/n] ? “); String ans = reader.readLine(); if (“Y”.equals(ans) || “y”.equals(ans)) { // set the DELETE flag to true message.setFlag(Flags.Flag.DELETED, true); System.out.println(“Marked DELETE for message: ” + subject); } else if (“n”.equals(ans)) { break; } } // expunges the folder to remove messages which are marked deleted emailFolder.close(true); store.close(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } catch (IOException io) { io.printStackTrace(); } } public static void main(String[] args) { String host = “pop.gmail.com”;// change accordingly String mailStoreType = “pop3”; String username = “[email protected]”;// change accordingly String password = “*****”;// change accordingly delete(host, mailStoreType, username, password); } } You can set the debug on by uncommenting the statement emailSession.setDebug(true); Compile and Run Now that our class is ready, let us compile the above class. I”ve saved the class DeleteEmail.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt: javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: DeleteEmail.java Now that the class is compiled, execute the following command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: DeleteEmail Verify Output You should see the following message on the command console: messages.length—1 ——————————— Email Number 1 Subject: Testing From: ABC <[email protected]> Do you want to delete this message [y/n] ? y Marked DELETE for message: Testing Print Page Previous Next Advertisements ”;

JavaMail – Gmail SMTP server

JavaMail API – Gmail SMPT Server ”; Previous Next In all previous chapters we used JangoSMPT server to send emails. In this chapter we will learn about SMPT server provided by Gmail. Gmail (among others) offers use of their public SMTP server free of charge. Gmail SMTP server details can be found here. As you can see in the details, we can use either TLS or SSL connection to send email via Gmail SMTP server. The procedure to send email using Gmail SMTP server is similar as explained in chapter Sending Emails, except that we would change the host server. As a pre-requisite the sender email address should be an active gmail account. Let us try an example. Create Java Class Create a Java file SendEmailUsingGMailSMTP, contents of which are as below: package com.tutorialspoint; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendEmailUsingGMailSMTP { public static void main(String[] args) { // Recipient”s email ID needs to be mentioned. String to = “[email protected]”;//change accordingly // Sender”s email ID needs to be mentioned String from = “[email protected]”;//change accordingly final String username = “abc”;//change accordingly final String password = “*****”;//change accordingly // Assuming you are sending email through relay.jangosmtp.net String host = “smtp.gmail.com”; Properties props = new Properties(); props.put(“mail.smtp.auth”, “true”); props.put(“mail.smtp.starttls.enable”, “true”); props.put(“mail.smtp.host”, host); props.put(“mail.smtp.port”, “587”); // Get the Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. Message message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set Subject: header field message.setSubject(“Testing Subject”); // Now set the actual message message.setText(“Hello, this is sample for to check send ” + “email using JavaMailAPI “); // Send message Transport.send(message); System.out.println(“Sent message successfully….”); } catch (MessagingException e) { throw new RuntimeException(e); } } } Here the host is set as smtp.gmail.com and port is set as 587. Here we have enabled TLS connection. Compile and Run Now that our class is ready, let us compile the above class. I”ve saved the class SendEmailUsingGMailSMTP.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt: javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmailUsingGMailSMTP.java Now that the class is compiled, execute the below command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmailUsingGMailSMTP Verify Output You should see the following message on the command console: Sent message successfully…. Print Page Previous Next Advertisements ”;

JavaMail – Folder Management

JavaMail API – Folder Management ”; Previous Next So far, we’ve worked in our previous chapters mostly with the INBOX folder. This is the default folder in which most mail resides. Some systems might call it as INBOX and some other might call it by some other name. But,you can always access it from the JavaMail API using the name INBOX. The JavaMail API represents folders as instances of the abstract Folder class: public abstract class Folder extends Object This class declares methods for requesting named folders from servers, deleting messages from folders, searching for particular messages in folders, listing the messages in a folder, and so forth. Opening a Folder We can”t create a folder directly as the only constructor in the Folder class is protected. We can get a Folder from: a Session a Store or another Folder All the above classes have a similar getFolder() method with similar signature: public abstract Folder getFolder(String name) throws MessagingException Some of the methods which help in getting the Folder object are: Method Description boolean exists() Checks if the folder really exists. Use this method before getting the Folder object. abstract void open(int mode) When you get a Folder, its closed. Use this method to open it. mode can be Folder.READ_ONLY or Folder.READ_WRITE. abstract boolean isOpen() This method returns true if the folder is open, false if it’s closed abstract void close(boolean expunge) Closes the folder. If the expunge argument is true, any deleted messages in the folder are deleted from the actual file on the server. Otherwise, they’re simply marked as deleted, but the messages can still be undeleted. Basic Folder Info Following are some of the methods in Folder class which return basic information about a folder: Method Description abstract String getName() Returns the name of the folder, such as “TutorialsPoint Mail” abstract String getFullName() Returns the complete hierarchical name from the root such as “books/Manisha/TutorialsPoint Mail”. URLName getURLName() Return a URLName representing this folder. abstract Folder getParent() Returns the name of the folder that contains this folder i.e the parent folder. E.g “Manisha” from the previous “TutorialsPoint Mail” example. abstract int getType() Returns an int indicating whether the folder can contain messages and/or other folders. int getMode() It returns one of the two named constants Folder.READ_ONLY or Folder.READ_WRITE or -1 when the mode is unknown. Store getStore() Returns the Store object from which this folder was retrieved. abstract char getSeparator() Return the delimiter character that separates this Folder”s pathname from the names of immediate subfolders. Managing Folder Following are some of the methods which help manage the Folder: Method Description abstract boolean create(int type) This creates a new folder in this folder’s Store. Where type would be:Folder.HOLDS_MESSAGES or Folder.HOLDS_FOLDERS. Returns true if folder is successfully created else returns false. abstract boolean delete(boolean recurse) This deletes the folder only if the folder is closed. Otherwise, it throws an IllegalStateException. If recurse is true, then subfolders are deleted. abstract boolean renameTo(Folder f) This changes the name of this folder. A folder must be closed to be renamed. Otherwise, an IllegalStateException is thrown. Managing Messages in Folders Following are some of the methods that help manage the messages in Folder: Method Description abstract void appendMessages(Message[] messages) As the name implies, the messages in the array are placed at the end of this folder. void copyMessages(Message[] messages, Folder destination) This copies messages from this folder into a specified folder given as an argument. abstract Message[] expunge() To delete a message from a folder, set its Flags.Flag.DELETED flag to true. To physically remove deleted messages from a folder, you have to call this method. Listing the Contents of a Folder There are four methods to list the folders that a folder contains: Method Description Folder[] list() This returns an array listing the folders that this folder contains. Folder[] listSubscribed() This returns an array listing all the subscribed folders that this folder contains. abstract Folder[] list(String pattern) This is similar to the list() method except that it allows you to specify a pattern. The pattern is a string giving the name of the folders that match. Folder[] listSubscribed(String pattern) This is similar to the listSubscribed() method except that it allows you to specify a pattern. The pattern is a string giving the name of the folders that match. Checking for Mail Method Description abstract int getMessageCount() This method can be invoked on an open or closed folder. However, in the case of a closed folder, this method may (or may not) return -1 to indicate that the exact number of messages isn’t easily available. abstract boolean hasNewMessages() This returns true if new messages have been added to the folder since it was last opened. int getNewMessageCount() It returns the new message count by checking messages in the folder whose RECENT flag is set. int getUnreadMessageCount() This can be invoked on either an open or a closed folder. However, in the case of a closed folder, it may return -1 to indicate that the real answer would be too expensive to obtain. Getting Messages from Folders The Folder class provides four methods for retrieving messages from open folders: Method Description abstract Message getMessage(int messageNumber) This returns the nth message in the folder. The first message in the folder is number 1. Message[] getMessages() This returns an array of Message objects representing all the messages in this folder. Message[] getMessages(int start, int end) This returns an array of Message objects from the folder, beginning with start and finishing with end, inclusive. Message[] getMessages(int[] messageNumbers) This returns an array containing only those messages specifically identified by number in the messageNumbers array. void fetch(Message[] messages, FetchProfile fp) Prefetch the items specified in the FetchProfile for the given Messages. The FetchProfile argument specifies which headers in the messages to prefetch. Searching Folders If the server supports searching (as many IMAP servers do and most POP servers don’t), it’s easy to search a folder for the messages meeting certain criteria. The criteria are encoded in SearchTerm

JavaMail – Forwarding Emails

JavaMail API – Forwarding Emails ”; Previous Next In this chapter we will see how to forward an email using JavaMail API. Basic steps followed in the program below are: Get the Session object with POP and SMPT server details in the properties. We would need POP details to retrieve messages and SMPT details to send messages. Create POP3 store object and connect to the store. Create Folder object and open the appropriate folder in your mailbox. Retrieve messages. Iterate through the messages and type “Y” or “y” if you want to forward. Get all information (To,From,Subject, Content) of the message. Build the forward message by working with the parts that make up a message. First part would be the text of the message and a second part would be the message to forward. Combine the two into a multipart. Then you add the multipart to a properly addressed message and send it. Close the Transport, folder and store objects respectively. Here we have used JangoSMPT server via which emails are sent to our destination email address. The setup is explained in the Environment Setup chapter. Create Java Class Create a java class file ForwardEmail, the contents of which are as follows: package com.tutorialspoint; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Date; import java.util.Properties; import javax.mail.BodyPart; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Store; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class ForwardEmail { public static void main(String[] args) { Properties properties = new Properties(); properties.put(“mail.store.protocol”, “pop3”); properties.put(“mail.pop3s.host”, “pop.gmail.com”); properties.put(“mail.pop3s.port”, “995”); properties.put(“mail.pop3.starttls.enable”, “true”); properties.put(“mail.smtp.auth”, “true”); properties.put(“mail.smtp.host”, “relay.jangosmtp.net”); properties.put(“mail.smtp.port”, “25”); Session session = Session.getDefaultInstance(properties); try { // session.setDebug(true); // Get a Store object and connect to the current host Store store = session.getStore(“pop3s”); store.connect(“pop.gmail.com”, “[email protected]”, “*****”);//change the user and password accordingly // Create a Folder object and open the folder Folder folder = store.getFolder(“inbox”); folder.open(Folder.READ_ONLY); BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); Message[] messages = folder.getMessages(); if (messages.length != 0) { for (int i = 0, n = messages.length; i < n; i++) { Message message = messages[i]; // Get all the information from the message 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.print(“Do you want to reply [y/n] : “); String ans = reader.readLine(); if (“Y”.equals(ans) || “y”.equals(ans)) { Message forward = new MimeMessage(session); // Fill in header forward.setRecipients(Message.RecipientType.TO, InternetAddress.parse(from)); forward.setSubject(“Fwd: ” + message.getSubject()); forward.setFrom(new InternetAddress(to)); // Create the message part MimeBodyPart messageBodyPart = new MimeBodyPart(); // Create a multipart message Multipart multipart = new MimeMultipart(); // set content messageBodyPart.setContent(message, “message/rfc822”); // Add part to multi part multipart.addBodyPart(messageBodyPart); // Associate multi-part with message forward.setContent(multipart); forward.saveChanges(); // Send the message by authenticating the SMTP server // Create a Transport instance and call the sendMessage Transport t = session.getTransport(“smtp”); try { //connect to the smpt server using transport instance //change the user and password accordingly t.connect(“abc”, “*****”); t.sendMessage(forward, forward.getAllRecipients()); } finally { t.close(); } System.out.println(“message forwarded successfully….”); // close the store and folder objects folder.close(false); store.close(); }// end if }// end for }// end if } catch (Exception e) { e.printStackTrace(); } } } You can set the debug on by uncommenting the statement session.setDebug(true); Compile and Run Now that our class is ready, let us compile the above class. I”ve saved the class ForwardEmail.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt: javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: ForwardEmail.java Now that the class is compiled, execute the following command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: ForwardEmail Verify Output You should see the following message on the command console: From: ABC <[email protected]> Reply-to: [email protected] To: XYZ <[email protected]> Subject: Hi today is a nice day Sent: Thu Oct 17 15:58:37 IST 2013 Do you want to reply [y/n] : y message forwarded successfully…. Check the inbox to which the mail was sent. In our case the forwarded message would look as below: Print Page Previous Next Advertisements ”;