JavaMail

Last updated

JavaMail is a Java API used to send and receive email via SMTP, POP3 and IMAP. JavaMail is built into the Java EE platform, but also provides an optional package for use in Java SE. [1]

Contents

The current version is 1.6.5, released in March 2020 [2] . Another open source JavaMail implementation exists - GNU JavaMail - while supporting only version 1.3 of JavaMail specification, it provides the only free NNTP backend, which makes it possible to use this technology to read and send news group articles.

As of 2019, the software is known as Jakarta Mail, and is part of the Jakarta EE brand (formerly known as Java EE).

Licensing

Jakarta Mail is hosted as an open source project on Eclipse.org under its new name Jakarta Mail. [3]

Most of the Jakarta Mail source code is licensed under the following licences:

Examples

importjava.util.*;importjavax.mail.*;importjavax.mail.internet.*;importjavax.activation.*;// Send a simple, single part, text/plain e-mailpublicclassTestEmail{publicstaticvoidmain(String[]args){// SUBSTITUTE YOUR EMAIL ADDRESSES HERE!Stringto="sendToMailAddress";Stringfrom="sendFromMailAddress";// SUBSTITUTE YOUR ISP'S MAIL SERVER HERE!Stringhost="smtp.yourisp.invalid";// Create properties, get SessionPropertiesprops=newProperties();// If using static Transport.send(),// need to specify which host to send it toprops.put("mail.smtp.host",host);// To see what is going on behind the sceneprops.put("mail.debug","true");Sessionsession=Session.getInstance(props);try{// Instantiate a messageMessagemsg=newMimeMessage(session);//Set message attributesmsg.setFrom(newInternetAddress(from));InternetAddress[]address={newInternetAddress(to)};msg.setRecipients(Message.RecipientType.TO,address);msg.setSubject("Test E-Mail through Java");msg.setSentDate(newDate());// Set message contentmsg.setText("This is a test of sending a "+"plain text e-mail through Java.\n"+"Here is line 2.");//Send the messageTransport.send(msg);}catch(MessagingExceptionmex){// Prints all nested (chained) exceptions as wellmex.printStackTrace();}}}//End of class

Sample Code to Send Multipart E-Mail, HTML E-Mail and File Attachments

importjava.util.*;importjava.io.*;importjavax.mail.*;importjavax.mail.internet.*;importjavax.activation.*;publicclassSendMailUsage{publicstaticvoidmain(String[]args){// SUBSTITUTE YOUR EMAIL ADDRESSES HERE!!!Stringto="sendToMailAddress";Stringfrom="sendFromMailAddress";// SUBSTITUTE YOUR ISP'S MAIL SERVER HERE!!!Stringhost="smtpserver.yourisp.invalid";// Create properties for the SessionPropertiesprops=newProperties();// If using static Transport.send(),// need to specify the mail server hereprops.put("mail.smtp.host",host);// To see what is going on behind the sceneprops.put("mail.debug","true");// Get a sessionSessionsession=Session.getInstance(props);try{// Get a Transport object to send e-mailTransportbus=session.getTransport("smtp");// Connect only once here// Transport.send() disconnects after each send// Usually, no username and password is required for SMTPbus.connect();//bus.connect("smtpserver.yourisp.net", "username", "password");// Instantiate a messageMessagemsg=newMimeMessage(session);// Set message attributesmsg.setFrom(newInternetAddress(from));InternetAddress[]address={newInternetAddress(to)};msg.setRecipients(Message.RecipientType.TO,address);// Parse a comma-separated list of email addresses. Be strict.msg.setRecipients(Message.RecipientType.CC,InternetAddress.parse(to,true));// Parse comma/space-separated list. Cut some slack.msg.setRecipients(Message.RecipientType.BCC,InternetAddress.parse(to,false));msg.setSubject("Test E-Mail through Java");msg.setSentDate(newDate());// Set message content and sendsetTextContent(msg);msg.saveChanges();bus.sendMessage(msg,address);setMultipartContent(msg);msg.saveChanges();bus.sendMessage(msg,address);setFileAsAttachment(msg,"C:/WINDOWS/CLOUD.GIF");msg.saveChanges();bus.sendMessage(msg,address);setHTMLContent(msg);msg.saveChanges();bus.sendMessage(msg,address);bus.close();}catch(MessagingExceptionmex){// Prints all nested (chained) exceptions as wellmex.printStackTrace();// How to access nested exceptionswhile(mex.getNextException()!=null){// Get next exception in chainExceptionex=mex.getNextException();ex.printStackTrace();if(!(exinstanceofMessagingException))break;elsemex=(MessagingException)ex;}}}// A simple, single-part text/plain e-mail.publicstaticvoidsetTextContent(Messagemsg)throwsMessagingException{// Set message contentStringmytxt="This is a test of sending a "+"plain text e-mail through Java.\n"+"Here is line 2.";msg.setText(mytxt);// Alternate formmsg.setContent(mytxt,"text/plain");}// A simple multipart/mixed e-mail. Both body parts are text/plain.publicstaticvoidsetMultipartContent(Messagemsg)throwsMessagingException{// Create and fill first partMimeBodyPartp1=newMimeBodyPart();p1.setText("This is part one of a test multipart e-mail.");// Create and fill second partMimeBodyPartp2=newMimeBodyPart();// Here is how to set a charset on textual contentp2.setText("This is the second part","us-ascii");// Create the Multipart.  Add BodyParts to it.Multipartmp=newMimeMultipart();mp.addBodyPart(p1);mp.addBodyPart(p2);// Set Multipart as the message's contentmsg.setContent(mp);}// Set a file as an attachment.  Uses JAF FileDataSource.publicstaticvoidsetFileAsAttachment(Messagemsg,Stringfilename)throwsMessagingException{// Create and fill first partMimeBodyPartp1=newMimeBodyPart();p1.setText("This is part one of a test multipart e-mail."+"The second part is file as an attachment");// Create second partMimeBodyPartp2=newMimeBodyPart();// Put a file in the second partFileDataSourcefds=newFileDataSource(filename);p2.setDataHandler(newDataHandler(fds));p2.setFileName(fds.getName());// Create the Multipart.  Add BodyParts to it.Multipartmp=newMimeMultipart();mp.addBodyPart(p1);mp.addBodyPart(p2);// Set Multipart as the message's contentmsg.setContent(mp);}// Set a single part HTML content.// Sending data of any type is similar.publicstaticvoidsetHTMLContent(Messagemsg)throwsMessagingException{Stringhtml="<html><head><title>"+msg.getSubject()+"</title></head><body><h1>"+msg.getSubject()+"</h1><p>This is a test of sending an HTML e-mail"+" through Java.</body></html>";// HTMLDataSource is a static nested classmsg.setDataHandler(newDataHandler(newHTMLDataSource(html)));}/*     * Static nested class to act as a JAF datasource to send HTML e-mail content     */staticclassHTMLDataSourceimplementsDataSource{privateStringhtml;publicHTMLDataSource(StringhtmlString){html=htmlString;}// Return html string in an InputStream.// A new stream must be returned each time.publicInputStreamgetInputStream()throwsIOException{if(html==null)thrownewIOException("Null HTML");returnnewByteArrayInputStream(html.getBytes());}publicOutputStreamgetOutputStream()throwsIOException{thrownewIOException("This DataHandler cannot write HTML");}publicStringgetContentType(){return"text/html";}publicStringgetName(){return"JAF text/html dataSource to send e-mail only";}}}//End of class

Related Research Articles

Email Method of exchanging digital messages between people over a network

Electronic mail is a method of exchanging messages ("mail") between people using electronic devices. Email entered limited use in the 1960s, but users could only send to users of the same computer, and some early email systems required the author and the recipient to both be online simultaneously, similar to instant messaging. Ray Tomlinson is credited as the inventor of email; in 1971, he developed the first system able to send mail between users on different hosts across the ARPANET, using the @ sign to link the user name with a destination server. By the mid-1970s, this was the form recognized as email.

Multipurpose Internet Mail Extensions (MIME) is an Internet standard that extends the format of email messages to support text in character sets other than ASCII, as well as attachments of audio, video, images, and application programs. Message bodies may consist of multiple parts, and header information may be specified in non-ASCII character sets. Email messages with MIME formatting are typically transmitted with standard protocols, such as the Simple Mail Transfer Protocol (SMTP), the Post Office Protocol (POP), and the Internet Message Access Protocol (IMAP).

The Simple Mail Transfer Protocol (SMTP) is a communication protocol for electronic mail transmission. As an Internet standard, SMTP was first defined in 1982 by RFC 821, and updated in 2008 by RFC 5321 to Extended SMTP additions, which is the protocol variety in widespread use today. Mail servers and other message transfer agents use SMTP to send and receive mail messages. Proprietary systems such as Microsoft Exchange and IBM Notes and webmail systems such as Outlook.com, Gmail and Yahoo! Mail may use non-standard protocols internally, but all use SMTP when sending to or receiving email from outside their own systems. SMTP servers commonly use the Transmission Control Protocol on port number 25.

Email client computer software that allows sending and receiving emails

An email client, email reader or more formally mail user agent (MUA) is a computer program used to access and manage a user's email.

Java servlet Java programming language class

A Java servlet is a Java software component that extends the capabilities of a server. Although servlets can respond to many types of requests, they most commonly implement web containers for hosting web applications on web servers and thus qualify as a server-side servlet web API. Such web servlets are the Java counterpart to other dynamic web content technologies such as PHP and ASP.NET.

Apple Mail is an email client included by Apple Inc. with its operating systems macOS, iOS and watchOS. Apple Mail grew out of NeXTMail, which was originally developed by NeXT as part of its NeXTSTEP operating system, after Apple's acquisition of NeXT in 1997.

A bounce message or just "bounce" is an automated message from an email system, informing the sender of a previous message that message had not been delivered. The original message is said to have "bounced".

Push notifications are small messages that can reach audiences anywhere and anytime. While pop-ups appear only when audiences are on the site they belong to, push messages are independent of sites. They are associated with web browsers and apps.

Many email clients now offer some support for Unicode. While some use Unicode by default, many others will automatically choose between a legacy encoding and Unicode depending on the mail's content, either automatically or when the user requests it.

Push Access Protocol is a protocol defined in WAP-164 of the Wireless Application Protocol (WAP) suite from the Open Mobile Alliance. PAP is used for communicating with the Push Proxy Gateway, which is usually part of a WAP Gateway.

The Mobile Media API (MMAPI) is an API specification for the Java ME platform CDC and CLDC devices such as mobile phones. Depending on how it's implemented, the APIs allow applications to play and record sounds and video, and to capture still images. MMAPI was developed under the Java Community Process as JSR 135.

In software engineering, a WAR file is a file used to distribute a collection of JAR-files, JavaServer Pages, Java Servlets, Java classes, XML files, tag libraries, static web pages and other resources that together constitute a web application.

HTML email is the use of a subset of HTML to provide formatting and semantic markup capabilities in email that are not available with plain text: Text can be linked without displaying a URL, or breaking long URLs into multiple pieces. Text is wrapped to fit the width of the viewing window, rather than uniformly breaking each line at 78 characters. It allows in-line inclusion of images, tables, as well as diagrams or mathematical formulae as images, which are otherwise difficult to convey.

A media type is a two-part identifier for file formats and format contents transmitted on the Internet. The Internet Assigned Numbers Authority (IANA) is the official authority for the standardization and publication of these classifications. Media types were originally defined in Request for Comments RFC 2045 (MIME) Part One: Format of Internet Message Bodies in November 1996 as a part of MIME specification, for denoting type of email message content and attachments; hence the original name, MIME type. Media types are also used by other internet protocols such as HTTP and document file formats such as HTML, for similar purposes.

JGroups is a library for reliable one-to-one or one-to-many communication written in the Java language.

JavaBeans Activation Framework, or JAF, is a Java API that enables developers to:

Ned Freed has contributed as an IETF participant and RFC writer to a significant number of internet protocol standards.

In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain. Thus, the chain of responsibility is an object oriented version of the if ... else if ... else if ....... else ... endif idiom, with the benefit that the condition–action blocks can be dynamically rearranged and reconfigured at runtime.

Yesod is a free and open-source web framework based on Haskell for productive development of type-safe, REST model based, high performance web applications, developed by Michael Snoyman et al.

EFAIL email security vulnerability

Efail, also written EFAIL, is a security hole in email systems with which content can be transmitted in encrypted form. This gap allows attackers to access the decrypted content of an email if it contains active content like HTML or JavaScript, or if loading of external content has been enabled in the client. Affected email clients include Gmail, Apple Mail, and Microsoft Outlook.

References

  1. "JavaEE inclusion" . Retrieved 12 Nov 2014.
  2. ""News"" . Retrieved 13 May 2020.
  3. "Jakarta Mail" . Retrieved 3 Sep 2019.