JavaMail API – Overview

JavaMail API – Overview ”; 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. Print Page Previous Next Advertisements ”;

JavaMail – Home

JavaMail API Tutorial PDF Version Quick Guide Resources Job Search Discussion 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. Audience This tutorial has been prepared for the beginners to help them understand basic JavaMail programming. After completing this tutorial you will find yourself at a moderate level of expertise in JavaMail programming from where you can take yourself to next levels. Prerequisites JavaMail programming is based on Java programming language so if you have basic understanding on Java programming then it will be a fun to learn using JavaMail in application development. Print Page Previous Next Advertisements ”;

JavaMail – POP3 Servers

JavaMail API – POP3 Servers ”; Previous Next Post Office Protocol (POP) is an application-layer Internet standard protocol used by local e-mail clients to retrieve e-mail from a remote server over a TCP/IP connection. POP supports simple download-and-delete requirements for access to remote mailboxes. A POP3 server listens on well-known port 110. Package com.sun.mail.pop3 is a POP3 protocol provider for the JavaMail API that provides access to a POP3 message store. The table below lists the classes in this package: Name Description POP3Folder A POP3 Folder (can only be “INBOX”). POP3Message A POP3 Message. POP3SSLStore A POP3 Message Store using SSL. POP3Store A POP3 Message Store. Some points to be noted above this provider: POP3 provider supports only a single folder named INBOX. Due to the limitations of the POP3 protocol, many of the JavaMail API capabilities like event notification, folder management, flag management, etc. are not allowed. The POP3 provider is accessed through the JavaMail APIs by using the protocol name pop3 or a URL of the form pop3://user:password@host:port/INBOX”. POP3 supports no permanent flags. For example the Flags.Flag.RECENT flag will never be set for POP3 messages. It”s up to the application to determine which messages in a POP3 mailbox are new. POP3 does not support the Folder.expunge() method. To delete and expunge messages, set the Flags.Flag.DELETED flag on the messages and close the folder using the Folder.close(true) method. POP3 does not provide a received date, so the getReceivedDate method will return null. When the headers of a POP3 message are accessed, the POP3 provider uses the TOP command to fetch all headers, which are then cached. When the content of a POP3 message is accessed, the POP3 provider uses the RETR command to fetch the entire message. The POP3Message.invalidate method can be used to invalidate cached data without closing the folder. The POP3 protocol provider supports the following properties, which may be set in the JavaMail Session object. The properties are always set as strings; the Type column describes how the string is interpreted. Name Type Description mail.pop3.user String Default user name for POP3. mail.pop3.host String The POP3 server to connect to. mail.pop3.port int The POP3 server port to connect to, if the connect() method doesn”t explicitly specify one. Defaults to 110. mail.pop3.connectiontimeout int Socket connection timeout value in milliseconds. Default is infinite timeout. mail.pop3.timeout int Socket I/O timeout value in milliseconds. Default is infinite timeout. mail.pop3.rsetbeforequit boolean Send a POP3 RSET command when closing the folder, before sending the QUIT command. Default is false. mail.pop3.message.class String Class name of a subclass of com.sun.mail.pop3.POP3Message. The subclass can be used to handle (for example) non-standard Content-Type headers. The subclass must have a public constructor of the form MyPOP3Message(Folder f, int msgno) throws MessagingException. mail.pop3.localaddress String Local address (host name) to bind to when creating the POP3 socket. Defaults to the address picked by the Socket class. mail.pop3.localport int Local port number to bind to when creating the POP3 socket. Defaults to the port number picked by the Socket class. mail.pop3.apop.enable boolean If set to true, use APOP instead of USER/PASS to login to the POP3 server, if the POP3 server supports APOP. APOP sends a digest of the password rather than the clear text password. Defaults to false. mail.pop3.socketFactory Socket Factory If set to a class that implements the javax.net.SocketFactory interface, this class will be used to create POP3 sockets. mail.pop3.socketFactory.class String If set, specifies the name of a class that implements the javax.net.SocketFactory interface. This class will be used to create POP3 sockets. mail.pop3.socketFactory.fallback boolean If set to true, failure to create a socket using the specified socket factory class will cause the socket to be created using the java.net.Socket class. Defaults to true. mail.pop3.socketFactory.port int Specifies the port to connect to when using the specified socket factory. If not set, the default port will be used. mail.pop3.ssl.enable boolean If set to true, use SSL to connect and use the SSL port by default. Defaults to false for the “pop3” protocol and true for the “pop3s” protocol. mail.pop3.ssl.checkserveridentity boolean If set to true, check the server identity as specified by RFC 2595. Defaults to false. mail.pop3.ssl.trust String If set, and a socket factory hasn”t been specified, enables use of a MailSSLSocketFactory. If set to “*”, all hosts are trusted. If set to a whitespace separated list of hosts, those hosts are trusted. Otherwise, trust depends on the certificate the server presents. mail.pop3.ssl.socketFactory SSL Socket Factory If set to a class that extends the javax.net.ssl.SSLSocketFactory class, this class will be used to create POP3 SSL sockets. mail.pop3.ssl.socketFactory.class String If set, specifies the name of a class that extends the javax.net.ssl.SSLSocketFactory class. This class will be used to create POP3 SSL sockets. mail.pop3.ssl.socketFactory.port int Specifies the port to connect to when using the specified socket factory. If not set, the default port will be used. mail.pop3.ssl.protocols string Specifies the SSL protocols that will be enabled for SSL connections. The property value is a whitespace separated list of tokens acceptable to the javax.net.ssl.SSLSocket.setEnabledProtocols method. mail.pop3.starttls.enable boolean If true, enables the use of the STLS command (if supported by the server) to switch the connection to a TLS-protected connection before issuing any login commands. Defaults to false. mail.pop3.starttls.required boolean If true, requires the use of the STLS command. If the server doesn”t support the STLS command, or the command fails, the connect method will fail. Defaults to false. mail.pop3.socks.host string Specifies the host name of a SOCKS5 proxy server that will be used for connections to the mail server. mail.pop3.socks.port string Specifies the port number for the SOCKS5 proxy server. mail.pop3.disabletop boolean If set to true, the POP3 TOP command will not be used to fetch message headers. Defaults to false. mail.pop3.forgettopheaders boolean If set to true, the headers that might have been retrieved using the POP3 TOP command will be forgotten and replaced by headers retrieved as part of the POP3 RETR command. Defaults to false. mail.pop3.filecache.enable boolean If set to true, the POP3 provider will cache message

JavaMail – Discussion

Discuss JavaMail API ”; 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. Print Page Previous Next Advertisements ”;

JavaMail – IMAP Servers

JavaMail API – IMAP Servers ”; Previous Next IMAP is Acronym for Internet Message Access Protocol. It is an Application Layer Internet protocol that allows an e-mail client to access e-mail on a remote mail server. An IMAP server typically listens on well-known port 143. IMAP over SSL (IMAPS) is assigned to port number 993. IMAP supports both on-line and off-line modes of operation. E-mail clients using IMAP generally leave messages on the server until the user explicitly deletes them. Package com.sun.mail.imap is an IMAP protocol provider for the JavaMail API that provides access to an IMAP message store. The table below lists the interface and classes of this provider: Class/Interface Description IMAPFolder.ProtocolCommand This a simple interface for user-defined IMAP protocol commands. ACL This is a class. An access control list entry for a particular authentication identifier (user or group). IMAPFolder This class implements an IMAP folder. IMAPFolder.FetchProfileItem This a class for fetching headers. IMAPMessage This class implements an ReadableMime object. IMAPMessage.FetchProfileCondition This class implements the test to be done on each message in the folder. IMAPSSLStore This class provides access to an IMAP message store over SSL. IMAPStore This class provides access to an IMAP message store. Rights This class represents the set of rights for an authentication identifier (for instance, a user or a group). Rights.Right This inner class represents an individual right. SortTerm A particular sort criteria, as defined by RFC 5256. Some points to be noted above this provider: This provider supports both the IMAP4 and IMAP4rev1 protocols. A connected IMAPStore maintains a pool of IMAP protocol objects for use in communicating with the IMAP server. As folders are opened and new IMAP protocol objects are needed, the IMAPStore will provide them from the connection pool, or create them if none are available. When a folder is closed, its IMAP protocol object is returned to the connection pool if the pool . The connected IMAPStore object may or may not maintain a separate IMAP protocol object that provides the store a dedicated connection to the IMAP server. The IMAP protocol provider supports the following properties, which may be set in the JavaMail Session object. The properties are always set as strings; the Type column describes how the string is interpreted. Name Type Description mail.imap.user String Default user name for IMAP. mail.imap.host String The IMAP server to connect to. mail.imap.port int The IMAP server port to connect to, if the connect() method doesn”t explicitly specify one. Defaults to 143. mail.imap.partialfetch boolean Controls whether the IMAP partial-fetch capability should be used. Defaults to true. mail.imap.fetchsize int Partial fetch size in bytes. Defaults to 16K. mail.imap.ignorebodystructuresize boolean The IMAP BODYSTRUCTURE response includes the exact size of each body part. Normally, this size is used to determine how much data to fetch for each body part. Defaults to false. mail.imap.connectiontimeout int Socket connection timeout value in milliseconds. Default is infinite timeout. mail.imap.timeout int Socket I/O timeout value in milliseconds. Default is infinite timeout. mail.imap.statuscachetimeout int Timeout value in milliseconds for cache of STATUS command response. Default is 1000 (1 second). Zero disables cache. mail.imap.appendbuffersize int Maximum size of a message to buffer in memory when appending to an IMAP folder. mail.imap.connectionpoolsize int Maximum number of available connections in the connection pool. Default is 1. mail.imap.connectionpooltimeout int Timeout value in milliseconds for connection pool connections. Default is 45000 (45 seconds). mail.imap.separatestoreconnection boolean Flag to indicate whether to use a dedicated store connection for store commands. Default is false. mail.imap.auth.login.disable boolean If true, prevents use of the non-standard AUTHENTICATE LOGIN command, instead using the plain LOGIN command. Default is false. mail.imap.auth.plain.disable boolean If true, prevents use of the AUTHENTICATE PLAIN command. Default is false. mail.imap.auth.ntlm.disable boolean If true, prevents use of the AUTHENTICATE NTLM command. Default is false. mail.imap.proxyauth.user String If the server supports the PROXYAUTH extension, this property specifies the name of the user to act as. Authenticate to the server using the administrator”s credentials. After authentication, the IMAP provider will issue the PROXYAUTH command with the user name specified in this property. mail.imap.localaddress String Local address (host name) to bind to when creating the IMAP socket. Defaults to the address picked by the Socket class. mail.imap.localport int Local port number to bind to when creating the IMAP socket. Defaults to the port number picked by the Socket class. mail.imap.sasl.enable boolean If set to true, attempt to use the javax.security.sasl package to choose an authentication mechanism for login. Defaults to false. mail.imap.sasl.mechanisms String A space or comma separated list of SASL mechanism names to try to use. mail.imap.sasl.authorizationid String The authorization ID to use in the SASL authentication. If not set, the authentication ID (user name) is used. mail.imap.sasl.realm String The realm to use with SASL authentication mechanisms that require a realm, such as DIGEST-MD5. mail.imap.auth.ntlm.domain String The NTLM authentication domain. mail.imap.auth.ntlm.flags int NTLM protocol-specific flags. mail.imap.socketFactory Socket Factory If set to a class that implements the javax.net.SocketFactory interface, this class will be used to create IMAP sockets. mail.imap.socketFactory.class String If set, specifies the name of a class that implements the javax.net.SocketFactory interface. This class will be used to create IMAP sockets. mail.imap.socketFactory.fallback boolean If set to true, failure to create a socket using the specified socket factory class will cause the socket to be created using the java.net.Socket class. Defaults to true. mail.imap.socketFactory.port int Specifies the port to connect to when using the specified socket factory. Default port is used when not set. mail.imap.ssl.enable boolean If set to true, use SSL to connect and use the SSL port by default. Defaults to false for the “imap” protocol and true for the “imaps” protocol. mail.imap.ssl.checkserveridentity boolean If set to true, check the server identity as specified by RFC 2595. Defaults to false. mail.imap.ssl.trust String If set, and a socket factory hasn”t been specified, enables use of a MailSSLSocketFactory. If set to “*”, all hosts are trusted. If set to a whitespace separated list of hosts, those hosts are trusted. Otherwise, trust depends on the certificate the server

JavaMail – SMTP Servers

JavaMail API – SMTP Servers ”; Previous Next SMTP is an acronym for Simple Mail Transfer Protocol. It is an Internet standard for electronic mail (e-mail) transmission across Internet Protocol (IP) networks. SMTP uses TCP port 25. SMTP connections secured by SSL are known by the shorthand SMTPS, though SMTPS is not a protocol in its own right. JavaMail API has package com.sun.mail.smtp which act as SMTP protocol provider to access an SMTP server. Following table lists the classes included in this package: Class Description SMTPMessage This class is a specialization of the MimeMessage class that allows you to specify various SMTP options and parameters that will be used when this message is sent over SMTP. SMTPSSLTransport This class implements the Transport abstract class using SMTP over SSL for message submission and transport. SMTPTransport This class implements the Transport abstract class using SMTP for message submission and transport. The following table lists the exceptions thrown: Exception Description SMTPAddressFailedException This exception is thrown when the message cannot be sent. SMTPAddressSucceededException This exception is chained off a SendFailedException when the mail.smtp.reportsuccess property is true. SMTPSenderFailedException This exception is thrown when the message cannot be sent. SMTPSendFailedException This exception is thrown when the message cannot be sent.The exception includes the sender”s address, which the mail server rejected. The com.sun.mail.smtp provider use SMTP Authentication optionally. To use SMTP authentication you”ll need to set the mail.smtp.auth property or provide the SMTP Transport with a username and password when connecting to the SMTP server. You can do this using one of the following approaches: Provide an Authenticator object when creating your mail Session and provide the username and password information during the Authenticator callback. mail.smtp.user property can be set to provide a default username for the callback, but the password will still need to be supplied explicitly. This approach allows you to use the static Transport send method to send messages. For example: Transport.send(message); Call the Transport connect method explicitly with username and password arguments. For example: Transport tr = session.getTransport(“smtp”); tr.connect(smtphost, username, password); msg.saveChanges(); tr.sendMessage(msg, msg.getAllRecipients()); tr.close(); The SMTP protocol provider supports the following properties, which may be set in the JavaMail Session object. The properties are always set as strings. For example: props.put(“mail.smtp.port”, “587”); Here the Type column describes how the string is interpreted. Name Type Description mail.smtp.user String Default user name for SMTP. mail.smtp.host String The SMTP server to connect to. mail.smtp.port int The SMTP server port to connect to, if the connect() method doesn”t explicitly specify one. Defaults to 25. mail.smtp.connectiontimeout int Socket connection timeout value in milliseconds. Default is infinite timeout. mail.smtp.timeout int Socket I/O timeout value in milliseconds. Default is infinite timeout. mail.smtp.from String Email address to use for SMTP MAIL command. This sets the envelope return address. Defaults to msg.getFrom() or InternetAddress.getLocalAddress(). mail.smtp.localhost String Local host name used in the SMTP HELO or EHLO command. Defaults to InetAddress.getLocalHost().getHostName(). Should not normally need to be set if your JDK and your name service are configured properly. mail.smtp.localaddress String Local address (host name) to bind to when creating the SMTP socket. Defaults to the address picked by the Socket class. Should not normally need to be set. mail.smtp.localport int Local port number to bind to when creating the SMTP socket. Defaults to the port number picked by the Socket class. mail.smtp.ehlo boolean If false, do not attempt to sign on with the EHLO command. Defaults to true. mail.smtp.auth boolean If true, attempt to authenticate the user using the AUTH command. Defaults to false. mail.smtp.auth.mechanisms String If set, lists the authentication mechanisms to consider. Only mechanisms supported by the server and supported by the current implementation will be used. The default is “LOGIN PLAIN DIGEST-MD5 NTLM”, which includes all the authentication mechanisms supported by the current implementation. mail.smtp.auth.login.disable boolean If true, prevents use of the AUTH LOGIN command. Default is false. mail.smtp.auth.plain.disable boolean If true, prevents use of the AUTH PLAIN command. Default is false. mail.smtp.auth.digest-md5.disable boolean If true, prevents use of the AUTH DIGEST-MD5 command. Default is false. mail.smtp.auth.ntlm.disable boolean If true, prevents use of the AUTH NTLM command. Default is false. mail.smtp.auth.ntlm.domain String The NTLM authentication domain. mail.smtp.auth.ntlm.flags int NTLM protocol-specific flags. mail.smtp.submitter String The submitter to use in the AUTH tag in the MAIL FROM command. Typically used by a mail relay to pass along information about the original submitter of the message. mail.smtp.dsn.notify String The NOTIFY option to the RCPT command. Either NEVER, or some combination of SUCCESS, FAILURE, and DELAY (separated by commas). mail.smtp.dsn.ret String The RET option to the MAIL command. Either FULL or HDRS. mail.smtp.sendpartial boolean If set to true, and a message has some valid and some invalid addresses, send the message anyway, reporting the partial failure with a SendFailedException. If set to false (the default), the message is not sent to any of the recipients if there is an invalid recipient address. mail.smtp.sasl.enable boolean If set to true, attempt to use the javax.security.sasl package to choose an authentication mechanism for login. Defaults to false. mail.smtp.sasl.mechanisms String A space or comma separated list of SASL mechanism names to try to use. mail.smtp.sasl.authorizationid String The authorization ID to use in the SASL authentication. If not set, the authentication ID (user name) is used. mail.smtp.sasl.realm String The realm to use with DIGEST-MD5 authentication. mail.smtp.quitwait boolean If set to false, the QUIT command is sent and the connection is immediately closed. If set to true (the default), causes the transport to wait for the response to the QUIT command. mail.smtp.reportsuccess boolean If set to true, causes the transport to include an SMTPAddressSucceededException for each address that is successful. mail.smtp.socketFactory Socket Factory If set to a class that implements the javax.net.SocketFactory interface, this class will be used to create SMTP sockets. mail.smtp.socketFactory.class String If set, specifies the name of a class that implements the javax.net.SocketFactory interface. This class will be used to create SMTP sockets. mail.smtp.socketFactory.fallback boolean If set to true, failure to create a socket using the specified socket factory class will cause

JavaMail – Authentication

JavaMail API – Authentication ”; Previous Next In the previous chapters Checking Emails and Fetching Emails, we passed authorization credentials (user ad password) along with host, when connecting to store of your mailbox. Instead we can configure the Properties to have the host, and tell the Session about your custom Authenticator instance. This is shown in the example below: Create Java Class We will modify our CheckingMails.java from the chapter Checking Emails. Its contents are as below: package com.tutorialspoint; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.NoSuchProviderException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Store; public class CheckingMails { public static void check(String host, String storeType, String user, String password) { try { // create properties field Properties properties = new Properties(); properties.put(“mail.pop3s.host”, host); properties.put(“mail.pop3s.port”, “995”); properties.put(“mail.pop3s.starttls.enable”, “true”); // Setup authentication, get session Session emailSession = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( “[email protected]”, “manisha123”); } }); // emailSession.setDebug(true); // create the POP3 store object and connect with the pop server Store store = emailSession.getStore(“pop3s”); store.connect(); // create the folder object and open it Folder emailFolder = store.getFolder(“INBOX”); emailFolder.open(Folder.READ_ONLY); // 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, n = messages.length; i < n; 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]); System.out.println(“Text: ” + message.getContent().toString()); } // close the store and folder objects emailFolder.close(false); store.close(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } catch (Exception e) { e.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 check(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 CheckingMails.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: CheckingMails.java Now that the class is compiled, execute the below command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: CheckingMails Verify Output You can see a similar message as below on the command console: messages.length—3 ——————————— Email Number 1 Subject: Today is a nice day From: XYZ <[email protected]> Text: javax.mail.internet.MimeMultipart@45f676cb ——————————— Email Number 2 Subject: hiiii…. From: XYZ <[email protected]> Text: javax.mail.internet.MimeMultipart@37f12d4f ——————————— Email Number 3 Subject: helloo From: XYZ <[email protected]> Text: javax.mail.internet.MimeMultipart@3ad5ba3a Print Page Previous Next Advertisements ”;

JavaMail – Checking Emails

JavaMail API – Checking Emails ”; Previous Next There are two aspects to which needs to understood before proceeding with this chapter. They are Check and Fetch. Checking an email in JavaMail is a process where we open the respective folder in the mailbox and get each message. Here we only check the header of each message i.e the From, To, subject. Content is not read. Fetching an email in JavaMail is a process where we open the respective folder in the mailbox and get each message. Alongwith the header we also read the content by recognizing the content-type. To check or fetch an email using JavaMail API, we would need POP or IMAP servers. To check and fetch the emails, Folder and Store classes are needed. Here we have used GMAIL”s POP3 server (pop.gmail.com). In this chapter will learn how to check emails using JavaMail API. Fetching shall be covered in the subsequent chapters. To check emails: Get a Session Create pop3 Store object and connect with pop server. Create folder object. Open the appropriate folder in your mailbox. Get your messages. Close the Store and Folder objects. Create Java Class Create a java class file CheckingMails, the contents of which are as follows: package com.tutorialspoint; import java.util.Properties; 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 CheckingMails { public static void check(String host, String storeType, String user, String password) { try { //create properties field Properties properties = new Properties(); properties.put(“mail.pop3.host”, host); properties.put(“mail.pop3.port”, “995”); properties.put(“mail.pop3.starttls.enable”, “true”); Session emailSession = Session.getDefaultInstance(properties); //create the POP3 store object and connect with the pop server Store store = emailSession.getStore(“pop3s”); store.connect(host, user, password); //create the folder object and open it Folder emailFolder = store.getFolder(“INBOX”); emailFolder.open(Folder.READ_ONLY); // 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, n = messages.length; i < n; 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]); System.out.println(“Text: ” + message.getContent().toString()); } //close the store and folder objects emailFolder.close(false); store.close(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } catch (Exception e) { e.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 check(host, mailStoreType, username, password); } } Compile and Run Now that our class is ready, let us compile the above class. I”ve saved the class CheckingMails.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: CheckingMails.java Now that the class is compiled, execute the below command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: CheckingMails Verify Output You should see the following message on the command console: messages.length—4 ——————————— Email Number 1 Subject: Test Mail–Fetch From: <[email protected]> Text: javax.mail.internet.MimeMultipart@327a5b7f ——————————— Email Number 2 Subject: testing —-checking simple email From: <[email protected]> Text: javax.mail.internet.MimeMultipart@7f0d08bc ——————————— Email Number 3 Subject: Email with attachment From: <[email protected]> Text: javax.mail.internet.MimeMultipart@30b8afce ——————————— Email Number 4 Subject: Email with Inline image From: <[email protected]> Text: javax.mail.internet.MimeMultipart@2d1e165f Here we have printed the number of messages in the INBOX which is 4 in this case. We have also printed Subject, From address and Text for each email message. Print Page Previous Next Advertisements ”;

JavaMail – Fetching Emails

JavaMail API – Fetching Emails ”; Previous Next In the previous chapter we learnt how to check emails. Now let us see how to fetch each email and read its content. Let us write a Java class FetchingEmail which will read following types of emails: Simple email Email with attachment Email with inline image Basic steps followed in the code are as below: Get the Session object. Create POP3 store object and connect to the store. Create Folder object and open the appropriate folder in your mailbox. Retrieve messages. Close the folder and store objects respectively. Create Java Class Create a java class file FetchingEmail, contents of which are as below: package com.tutorialspoint; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Date; import java.util.Properties; import javax.mail.Address; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.NoSuchProviderException; import javax.mail.Part; import javax.mail.Session; import javax.mail.Store; public class FetchingEmail { public static void fetch(String pop3Host, String storeType, String user, String password) { try { // create properties field Properties properties = new Properties(); properties.put(“mail.store.protocol”, “pop3”); properties.put(“mail.pop3.host”, pop3Host); properties.put(“mail.pop3.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_ONLY); 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(“———————————“); writePart(message); String line = reader.readLine(); if (“YES”.equals(line)) { message.writeTo(System.out); } else if (“QUIT”.equals(line)) { break; } } // close the store and folder objects emailFolder.close(false); store.close(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.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 //Call method fetch fetch(host, mailStoreType, username, password); } /* * This method checks for content-type * based on which, it processes and * fetches the content of the message */ public static void writePart(Part p) throws Exception { if (p instanceof Message) //Call methos writeEnvelope writeEnvelope((Message) p); System.out.println(“—————————-“); System.out.println(“CONTENT-TYPE: ” + p.getContentType()); //check if the content is plain text if (p.isMimeType(“text/plain”)) { System.out.println(“This is plain text”); System.out.println(“—————————“); System.out.println((String) p.getContent()); } //check if the content has attachment else if (p.isMimeType(“multipart/*”)) { System.out.println(“This is a Multipart”); System.out.println(“—————————“); Multipart mp = (Multipart) p.getContent(); int count = mp.getCount(); for (int i = 0; i < count; i++) writePart(mp.getBodyPart(i)); } //check if the content is a nested message else if (p.isMimeType(“message/rfc822”)) { System.out.println(“This is a Nested Message”); System.out.println(“—————————“); writePart((Part) p.getContent()); } //check if the content is an inline image else if (p.isMimeType(“image/jpeg”)) { System.out.println(“——–> image/jpeg”); Object o = p.getContent(); InputStream x = (InputStream) o; // Construct the required byte array System.out.println(“x.length = ” + x.available()); while ((i = (int) ((InputStream) x).available()) > 0) { int result = (int) (((InputStream) x).read(bArray)); if (result == -1) int i = 0; byte[] bArray = new byte[x.available()]; break; } FileOutputStream f2 = new FileOutputStream(“/tmp/image.jpg”); f2.write(bArray); } else if (p.getContentType().contains(“image/”)) { System.out.println(“content type” + p.getContentType()); File f = new File(“image” + new Date().getTime() + “.jpg”); DataOutputStream output = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(f))); com.sun.mail.util.BASE64DecoderStream test = (com.sun.mail.util.BASE64DecoderStream) p .getContent(); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = test.read(buffer)) != -1) { output.write(buffer, 0, bytesRead); } } else { Object o = p.getContent(); if (o instanceof String) { System.out.println(“This is a string”); System.out.println(“—————————“); System.out.println((String) o); } else if (o instanceof InputStream) { System.out.println(“This is just an input stream”); System.out.println(“—————————“); InputStream is = (InputStream) o; is = (InputStream) o; int c; while ((c = is.read()) != -1) System.out.write(c); } else { System.out.println(“This is an unknown type”); System.out.println(“—————————“); System.out.println(o.toString()); } } } /* * This method would print FROM,TO and SUBJECT of the message */ public static void writeEnvelope(Message m) throws Exception { System.out.println(“This is the message envelope”); System.out.println(“—————————“); Address[] a; // FROM if ((a = m.getFrom()) != null) { for (int j = 0; j < a.length; j++) System.out.println(“FROM: ” + a[j].toString()); } // TO if ((a = m.getRecipients(Message.RecipientType.TO)) != null) { for (int j = 0; j < a.length; j++) System.out.println(“TO: ” + a[j].toString()); } // SUBJECT if (m.getSubject() != null) System.out.println(“SUBJECT: ” + m.getSubject()); } } 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 FetchingEmail.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: FetchingEmail.java Now that the class is compiled, execute the below command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: FetchingEmail Verify Output You should see the following message on the command console: messages.length—3 ——————————— This is the message envelope ————————— FROM: XYZ <[email protected]> TO: ABC <[email protected]> SUBJECT: Simple Message —————————- CONTENT-TYPE: multipart/alternative; boundary=047d7b343d6ad3e4ea04e8ec6579 This is a Multipart ————————— —————————- CONTENT-TYPE: text/plain; charset=ISO-8859-1 This is plain text ————————— Hi am a simple message string…. — Regards xyz This is the message envelope ————————— FROM: XYZ <[email protected]> TO: ABC <[email protected]> SUBJECT: Attachement —————————- CONTENT-TYPE: multipart/mixed; boundary=047d7b343d6a99180904e8ec6751 This is a Multipart ————————— —————————- CONTENT-TYPE: text/plain; charset=ISO-8859-1 This is plain text ————————— Hi I”ve an attachment.Please check

JavaMail – Sending Emails

JavaMail API – Sending Emails ”; Previous Next Now that we have a fair idea about JavaMail API and its core classes, let us now write a simple programs which will send simple email, email with attachments, email with HTML content and email with inline images. Basic steps followed in all the above scenarios are as below: Get the Session object. Compose a message. Send the message. In the following sections we have demonstrated simple examples of: Send simple email Send attachment in email Send HTML content in email Send inline image in email Print Page Previous Next Advertisements ”;