Jakarta Mail

Last updated

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

Contents

The current version is 2.1.2, released on May 5, 2023. [2] Another open source Jakarta Mail implementation exists (GNU JavaMail), which -while supporting only the obsolete JavaMail 1.3 specification- 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). The reference implementation is part of the Eclipse Angus project.

Maven coordinates of the relevant projects required for operation are:

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

importjakarta.mail.*;importjakarta.mail.internet.*;importjava.time.*;importjava.util.*;// Send a simple, single part, text/plain e-mailpublicclassTestEmail{staticClockclock=Clock.systemUTC();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");Datenow=Date.from(LocalDateTime.now(clock).toInstant(ZoneOffset.UTC));msg.setSentDate(now);// 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();}}}

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

packageorg.example;importjakarta.activation.*;importjakarta.mail.*;importjakarta.mail.internet.*;importjava.io.*;importjava.time.*;importjava.util.*;publicclassSendMailUsage{staticClockclock=Clock.systemUTC();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(Date.from(LocalDateTime.now(clock).toInstant(ZoneOffset.UTC)));// 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(null!=mex.getNextException()){// 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(null==html)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";}}}

Related Research Articles

<span class="mw-page-title-main">Email</span> Mail sent using electronic means

Electronic mail is a method of transmitting and receiving messages using electronic devices. It was conceived in the late–20th century as the digital version of, or counterpart to, mail. Email is a ubiquitous and very widely used communication medium; in current use, an email address is often treated as a basic and necessary part of many processes in business, commerce, government, education, entertainment, and other spheres of daily life in most countries.

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 an Internet standard communication protocol for electronic mail transmission. Mail servers and other message transfer agents use SMTP to send and receive mail messages. User-level email clients typically use SMTP only for sending messages to a mail server for relaying, and typically submit outgoing email to the mail server on port 587 or 465 per RFC 8314. For retrieving messages, IMAP is standard, but proprietary servers also often implement proprietary protocols, e.g., Exchange ActiveSync.

<span class="mw-page-title-main">Email client</span> Computer program used to access and manage a users email

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

8-bit clean is an attribute of computer systems, communication channels, and other devices and software, that process 8-bit character encodings without treating any byte as an in-band control code.

In computer programming, Base64 is a group of binary-to-text encoding schemes that represent binary data in sequences of 24 bits that can be represented by four 6-bit Base64 digits.

<span class="mw-page-title-main">Apple Mail</span> Email client by Apple Inc.

Apple Mail is an email client included by Apple Inc. with its operating systems macOS, iOS, iPadOS 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.

An email attachment is a computer file sent along with an email message. One or more files can be attached to any email message, and be sent along with it to the recipient. This is typically used as a simple method to share documents and images.

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

MHTML, an initialism of "MIME encapsulation of aggregate HTML documents", is a Web archive file format used to combine, in a single computer file, the HTML code and its companion resources that are represented by external hyperlinks in the web page's HTML code. The content of an MHTML file is encoded using the same techniques that were first developed for HTML email messages, using the MIME content type multipart/related. MHTML files use an .mhtml or .mht filename extension.

Many email clients now offer some support for Unicode. Some clients 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.

A webform, web form or HTML form on a web page allows a user to enter data that is sent to a server for processing. Forms can resemble paper or database forms because web users fill out the forms using checkboxes, radio buttons, or text fields. For example, forms can be used to enter shipping or credit card data to order a product, or can be used to retrieve search results from a search engine.

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. Their purpose is somewhat similar to file extensions in that they identify the intended data format. 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 the 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.

Within computing, Jakarta Activation is a Jakarta EE API that enables developers to:

Ned Freed was an IETF participant and Request for Comments author who contributed to a significant number of Internet Protocol standards, mostly related to email. He is best known as the co-inventor of email MIME attachments, with Nathaniel Borenstein.

<span class="mw-page-title-main">Yesod (web framework)</span>

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.

<span class="mw-page-title-main">EFAIL</span> 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. "Jakarta Mail Home Page" . Retrieved 5 September 2023.
  3. "Jakarta Mail" . Retrieved 3 Sep 2019.