### Session Instance Methods Source: https://github.com/jakartaee/mail-api/blob/main/www/docs/JavaMail-1.2-changes.txt Provides convenience methods for obtaining Session objects, either the default instance or a new one, simplifying the setup process. ```APIDOC ## Session.getDefaultInstance(Properties props) ### Description Get the default Session object. If a default has not yet been setup, a new Session object is created and installed as the default. ### Method public static Session ### Parameters #### Path Parameters - **props** (Properties) - Properties object. Used only if a new Session object is created. ### Return Value the default Session object ## Session.getInstance(Properties props) ### Description Get a new Session object. ### Method public static Session ### Parameters #### Path Parameters - **props** (Properties) - Properties object that hold relevant properties. ### Return Value a new Session object ### See Also - javax.mail.Authenticator ``` -------------------------------- ### Build Jakarta Mail with Maven Source: https://github.com/jakartaee/mail-api/blob/main/www/Build-Instructions.md After cloning the repository and navigating into the mail directory, use this command to build the entire project. Maven must be installed. ```bash % cd mail % mvn install ``` -------------------------------- ### Run Sample Program (IMAP Example) Source: https://github.com/jakartaee/mail-api/blob/main/www/docs/README.txt Runs the 'msgshow' sample program using the IMAP protocol to display a specific message from the INBOX. Requires mail server, username, and password. ```java java msgshow -T imap -H -U -P -f INBOX 5 ``` -------------------------------- ### Java Method Signature Style Source: https://github.com/jakartaee/mail-api/blob/main/www/Contributions.md Shows the recommended style for Java method signatures, starting with access control. ```java public int foobar() { ... } ``` -------------------------------- ### Build Mbox Provider for Debian-based Distributions Source: https://github.com/jakartaee/mail-api/blob/main/www/Mbox-Provider.md Build the mbox provider for Debian-based distributions using mvn, ensuring the 'c89' command is in your PATH and the liblockfile-dev package is installed. ```bash (cd mbox; mvn) (cd mbox/native; mvn -Plinux) ``` -------------------------------- ### Set IPv4 Stack Preference Source: https://github.com/jakartaee/mail-api/blob/main/www/FAQ.html Work around IPv6 issues by setting the java.net.preferIPv4Stack system property to true when starting your Java application. ```bash java -Djava.net.preferIPv4Stack=true ... ``` -------------------------------- ### Clone Jakarta Mail Repository Source: https://github.com/jakartaee/mail-api/blob/main/www/Build-Instructions.md Use this command to download the latest source code of Jakarta Mail. Ensure Git is installed. ```bash % git clone git@github.com:eclipse-ee4j/mail.git ``` -------------------------------- ### Provider Registration for Custom Mail Stores/Transports Source: https://context7.com/jakartaee/mail-api/llms.txt Register custom `Store` or `Transport` implementations programmatically using `Session.addProvider()` or by creating a `META-INF/services/jakarta.mail.Provider` file. The example shows programmatic registration and listing all loaded providers. ```java import jakarta.mail.*; // Programmatic registration example Provider customSmtp = new Provider( Provider.Type.TRANSPORT, "mysmtp", // protocol name "com.example.mail.MyCustomSMTPTransport", // implementing class "Example Corp", // vendor "1.0" // version ); session.addProvider(customSmtp); session.setProvider(customSmtp); // make it default for "mysmtp" Transport t = session.getTransport("mysmtp"); // ... // META-INF/services/jakarta.mail.Provider (file in your JAR): // com.example.mail.MyCustomProvider // META-INF/jakarta.providers (legacy resource file): // protocol=mysmtp; type=transport; class=com.example.mail.MyCustomSMTPTransport; vendor=Example; // List all loaded providers for (Provider p : session.getProviders()) { System.out.printf(" %-10s %-12s %s%n", p.getProtocol(), p.getType(), p.getClassName()); } ``` -------------------------------- ### Flags - Reading and Setting Message Flags Source: https://context7.com/jakartaee/mail-api/llms.txt Explains how to work with `Flags` to inspect, read, and set system and user-defined flags on email messages. Includes examples for marking messages as read, deleted, and adding custom flags. ```APIDOC ## Flags ### Description `Flags` encapsulates both system flags (`SEEN`, `DELETED`, `ANSWERED`, `FLAGGED`, `DRAFT`, `RECENT`) and arbitrary user-defined string flags. Use `Message.setFlag()` / `Folder.setFlags()` to manipulate them. ### Method - `Message.getFlags()` - `Message.setFlag(Flags.Flag flag, boolean value)` - `Folder.setFlags(Message[] msgs, Flags flags, boolean value)` - `Folder.expunge()` - `Message.setFlags(Flags flags, boolean value)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java import jakarta.mail.*; // open inbox from a READ_WRITE IMAP session... Message[] msgs = inbox.getMessages(); // Inspect flags on a single message Flags flags = msgs[0].getFlags(); Flags.Flag[] sys = flags.getSystemFlags(); for (Flags.Flag f : sys) { if (f == Flags.Flag.SEEN) System.out.println("Read"); if (f == Flags.Flag.DELETED) System.out.println("Deleted"); if (f == Flags.Flag.ANSWERED) System.out.println("Replied"); if (f == Flags.Flag.FLAGGED) System.out.println("Starred"); } String[] userFlags = flags.getUserFlags(); System.out.println("User flags: " + java.util.Arrays.toString(userFlags)); // Mark single message as read msgs[0].setFlag(Flags.Flag.SEEN, true); // Bulk-flag a range of messages as deleted (soft-delete) Flags deleteFlag = new Flags(Flags.Flag.DELETED); inbox.setFlags(msgs, deleteFlag, true); // Permanently remove messages flagged as DELETED inbox.expunge(); // Add a custom user-defined flag msgs[1].setFlags(new Flags("$MyApp-Processed"), true); ``` ### Response #### Success Response (200) - **void**: Methods like `setFlag` and `expunge` do not return a value upon success. - **Flags**: `getFlags()` returns a `Flags` object representing the message's flags. #### Response Example (See Request Example for output) ``` -------------------------------- ### Get Default or New Session Instance Source: https://github.com/jakartaee/mail-api/blob/main/www/docs/JavaMail-1.2-changes.txt Convenience methods for obtaining a Session object. `getDefaultInstance` retrieves or creates a default session, while `getInstance` creates a new one. Both methods assume a null Authenticator. ```Java public static Session getDefaultInstance(Properties props) ``` ```Java public static Session getInstance(Properties props) throws MessagingException ``` -------------------------------- ### Get Store URLName - Store.getURLName() Source: https://github.com/jakartaee/mail-api/blob/main/doc/spec/JavaMail-1.1-changes.txt Clarifies the specification for Store.getURLName() to ensure the returned URLName does not include the password field. Subclasses should override only if their URLName format deviates from the standard. ```Java public URLName getURLName() /** * Return a URLName representing this store. The returned URLName * does not include the password field.

* * Subclasses should only override this method if their * URLName does not follow the standard format. * * @return the URLName representing this store * @see URLName */ ``` -------------------------------- ### Get Folder Open Mode - Folder.getMode() Source: https://github.com/jakartaee/mail-api/blob/main/doc/spec/JavaMail-1.1-changes.txt Adds a method to retrieve the open mode (READ_ONLY or READ_WRITE) of a folder. Existing Folder subclasses may not support this method if not updated. ```Java protected int mode = -1; public int getMode() { if (!isOpen()) throw new IllegalStateException("Folder not open"); return mode; } ``` -------------------------------- ### Get Default or New Session Instance Source: https://github.com/jakartaee/mail-api/blob/main/doc/spec/JavaMail-1.2-changes.txt Convenience methods for obtaining Session objects. getDefaultInstance retrieves the default session, creating one if it doesn't exist. getInstance creates a new session. ```Java public static Session getDefaultInstance(Properties props) ``` ```Java public static Session getInstance(Properties props) ``` -------------------------------- ### newStream(long start, long end) Source: https://github.com/jakartaee/mail-api/blob/main/doc/spec/JavaMail-1.2-changes.txt Creates a new InputStream from the current stream, starting at the specified 'start' position and ending before the 'end' position. The 'end' parameter is exclusive. If 'end' is -1, the new stream will end at the same position as the original stream. The returned InputStream also implements the SharedInputStream interface. ```APIDOC /** * Creates a new stream from the current stream, up to end (exclusive). start must be * non-negative. If end is -1, the new stream ends * at the same place as this stream. The returned InputStream * will also implement the SharedInputStream interface. * * @param start the starting position * @param end the ending position + 1 * @return the new stream */ public InputStream newStream(long start, long end); ``` -------------------------------- ### InstallCert Java Program Source: https://github.com/jakartaee/mail-api/blob/main/www/InstallCert.md Compile and run this Java program with the hostname as an argument to add the server's SSL certificate to your KeyStore. This is useful when connecting to hosts that use test certificates not issued by a commercial Certificate Authority. ```java import java.security.KeyStore; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; public class InstallCert { public static void main(String[] args) throws Exception { String host; int port; charorkeling c; if ((args.length == 1) || (args.length == 3)) { host = args[0]; String[] parts = host.split(":"); if (parts.length > 1) { host = parts[0]; port = Integer.parseInt(parts[1]); } else { port = 443; } if (args.length == 3) { c = args[2].charAt(0); } } else { System.out.println("Usage: " + InstallCert.class.getName() + " [:]\n or\nUsage: " + InstallCert.class.getName() + " [:] \n where is 'a' to add, 'r' to remove, 'l' to list\nExample: java InstallCert ecc.fedora.redhat.com:443\nExample: java InstallCert ecc.fedora.redhat.com:443 a\nExample: java InstallCert ecc.fedora.redhat.com:443 l\nExample: java InstallCert ecc.fedora.redhat.com:443 r"); return; } System.out.println("Loading KeyStore ``` ```java "/usr/jdk/instances/jdk1.5.0/jre/lib/security/cacerts"... Opening connection to ``` ```java ecc.fedora.redhat.com:443... Starting SSL handshake... ``` -------------------------------- ### Set Message-ID Header Source: https://github.com/jakartaee/mail-api/blob/main/www/FAQ.html Sets a custom Message-ID header for a message. This is a basic example of header manipulation. ```java protected void updateMessageID() throws MessagingException { header("Message-ID", "my-message-id"); } ``` -------------------------------- ### Display Available Command-Line Options Source: https://github.com/jakartaee/mail-api/blob/main/www/docs/README.txt Runs the 'msgshow' sample program with a '-' option to list all required and optional command-line arguments. ```java java msgshow - ``` -------------------------------- ### Recipient String Term Get Recipient Type Source: https://github.com/jakartaee/mail-api/blob/main/doc/spec/JavaMail-1.1-changes.txt Returns the recipient type that this RecipientStringTerm will match against. This is used internally. ```java public Message.RecipientType getRecipientType(); ``` -------------------------------- ### Get Sender Address from MimeMessage Source: https://github.com/jakartaee/mail-api/blob/main/doc/spec/JavaMail-1.3-changes.txt Retrieves the RFC 822 Sender header from a MimeMessage. Returns null if the header is absent. ```java /** * Returns the value of the RFC 822 "Sender" header field. * If the "Sender" header field is absent, null * is returned.

* * This implementation uses the getHeader method * to obtain the requisite header field. * * @return Address object * @exception MessagingException * @see #headers * @since JavaMail 1.3 */ public Address getSender() throws MessagingException ``` -------------------------------- ### Create a CharsetProvider for Unknown Charsets Source: https://github.com/jakartaee/mail-api/blob/main/www/FAQ.html Implement CharsetProvider to alias unsupported charsets to supported ones, like mapping 'x-unknown' to 'iso-8859-1'. Include the provider in META-INF/services. ```java import java.nio.charset.*; import java.nio.charset.spi.*; import java.util.*; public class UnknownCharsetProvider extends CharsetProvider { private static final String badCharset = "x-unknown"; private static final String goodCharset = "iso-8859-1"; public Charset charsetForName(String charset) { if (charset.equalsIgnoreCase(badCharset)) return Charset.forName(goodCharset); return null; } public Iterator charsets() { return Collections.emptyIterator(); } } ``` ```text UnknownCharsetProvider ``` -------------------------------- ### Compile Sample Program (Java) Source: https://github.com/jakartaee/mail-api/blob/main/www/docs/README.txt Compiles a Java sample program named 'msgshow.java' using the Java compiler. ```java javac msgshow.java ``` -------------------------------- ### Get Folder URLName - Folder.getURLName() Source: https://github.com/jakartaee/mail-api/blob/main/doc/spec/JavaMail-1.1-changes.txt Adds a method to retrieve a URLName representing the folder. The returned URLName will not include the password used for access. ```Java public URLName getURLName() throws MessagingException ``` -------------------------------- ### Build Mbox Provider for Solaris/OpenSolaris Source: https://github.com/jakartaee/mail-api/blob/main/www/Mbox-Provider.md Build the mbox provider for Solaris/OpenSolaris by running mvn in the mbox and mbox/native directories. ```bash (cd mbox; mvn) (cd mbox/native; mvn) ``` -------------------------------- ### Store and Folder - Reading Mail over IMAP Source: https://context7.com/jakartaee/mail-api/llms.txt Illustrates how to connect to an IMAP mail server using the `Store` class and access mailboxes using the `Folder` class. It shows how to open a folder, fetch messages, retrieve message details, and modify message flags. ```APIDOC ## Store and Folder — Reading Mail over IMAP `Store` represents a connection to a mail server. `Folder` models a mailbox folder. Messages fetched from a folder are lazy-loaded and cached while the folder is open. ```java import jakarta.mail.*; import jakarta.mail.internet.*; import java.util.Properties; Properties props = new Properties(); props.put("mail.imap.host", "imap.example.com"); props.put("mail.imap.port", "993"); props.put("mail.imap.ssl.enable", "true"); Session session = Session.getInstance(props); try (Store store = session.getStore("imap")) { store.connect("imap.example.com", "user@example.com", "secret"); // Navigate to INBOX try (Folder inbox = store.getFolder("INBOX")) { inbox.open(Folder.READ_WRITE); System.out.println("Total messages: " + inbox.getMessageCount()); System.out.println("Unread messages: " + inbox.getUnreadMessageCount()); // Fetch all messages (lazy — headers only until content accessed) Message[] messages = inbox.getMessages(); // Prefetch envelope headers in a single round trip (IMAP optimization) FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.FLAGS); inbox.fetch(messages, fp); for (Message m : messages) { System.out.printf("[%3d] %-50s from=%s seen=%b%n", m.getMessageNumber(), m.getSubject(), java.util.Arrays.toString(m.getFrom()), m.isSet(Flags.Flag.SEEN)); } // Mark the newest message as read and print its text body Message latest = messages[messages.length - 1]; latest.setFlag(Flags.Flag.SEEN, true); Object content = latest.getContent(); if (content instanceof String) { System.out.println("Body: " + content); } else if (content instanceof Multipart) { Multipart mp = (Multipart) content; for (int i = 0; i < mp.getCount(); i++) { BodyPart bp = mp.getBodyPart(i); if (bp.isMimeType("text/plain")) { System.out.println("Body: " + bp.getContent()); } } } } // folder.close() called automatically (AutoCloseable) } // store.close() called automatically ``` ``` -------------------------------- ### Add Certificate to Keystore Source: https://github.com/jakartaee/mail-api/blob/main/www/InstallCert.md This is the initial prompt and output when adding a certificate. It shows the certificate details and confirms its addition to the 'jssecacerts' keystore. ```text Enter certificate to add to trusted keystore or 'q' to quit: [1] [ [ Version: V3 Subject: CN=ecc.fedora.redhat.com, O=example.com, C=US Signature Algorithm: MD5withRSA, OID = 1.2.840.113549.1.1.4 Key: SunPKCS11-Solaris RSA public key, 1024 bits (id 5158256, session object) modulus: 1402933022884660852748661816869706021655226675890 0635441166580364941191074987345500771612454338502131694873337 233737712894815966313948609351561047977102880577818156814678 041303637255354084762814638611185951230474669455913908815827 173696651397340074281578017567044868711049821409365743953199 69584127568303024757 public exponent: 65537 Validity: [From: Wed Jan 18 13:16:12 PST 2006, To: Wed Apr 18 14:16:12 PDT 2007] Issuer: CN=Certificate Shack, O=example.com, C=US SerialNumber: [ 0f] Certificate Extensions: 2 [1]: ObjectId: 2.16.840.1.113730.1.1 Criticality=false NetscapeCertType [ SSL server ] [2]: ObjectId: 2.5.29.15 Criticality=false KeyUsage [ Key_Encipherment ] ] Algorithm: [MD5withRSA] Signature: 0000: 6D F4 2A 63 76 2A 05 70 A2 21 0E 1E 4A 31 BE 6B m.*cv*.p.!..J1.k 0010: 15 64 D8 BB 35 36 82 B0 0D 2A 96 FA 7A 9F A1 59 .d..56...*..z..Y 0020: CA 90 C3 28 C5 A6 9B 59 05 3B EB B2 8D C9 5E 38 ...(...Y.;....^8 0030: 62 ED 1A D7 93 DF 2A A5 D6 54 94 23 15 A2 0C E5 b.....*..T.#.... 0040: 13 40 2C 3E 59 E4 2A EB 51 AC 9E 28 44 23 87 B1 .@,>Y.*.Q..(D#.. 0050: 34 0B AC F3 E0 39 CA B8 35 B4 78 07 BF 28 4C C4 4....9..5.x..(L. 0060: 9A 2B A3 E9 04 26 78 19 F0 62 EA 0A B5 BB DC 0B .+...&x..b...... 0070: 90 59 E7 77 90 F8 BC 8A 1B 74 4B 4D C1 F8 3B 6C .Y.w.....tKM..;l ] Added certificate to keystore 'jssecacerts' using alias 'ecc.fedora.redhat.com-1' ``` -------------------------------- ### Store.connect(String host, String user, String password) Source: https://github.com/jakartaee/mail-api/blob/main/doc/spec/JavaMail-1.1-changes.txt Connects to a mail store using the provided host, username, and password. It handles default credential collection and protocol-specific connection logic. ```APIDOC ## Store.connect(String host, String user, String password) ### Description Connects to a mail store using the provided host, username, and password. It handles default credential collection and protocol-specific connection logic. An "open" ConnectionEvent is delivered upon successful connection. ### Method public void connect(String host, String user, String password) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Throws * AuthenticationFailedException: for authentication failures * MessagingException: for other failures * IllegalStateException: if the store is already connected ### See Also * javax.mail.event.ConnectionEvent ``` -------------------------------- ### ReadOnlyFolderException Class Source: https://github.com/jakartaee/mail-api/blob/main/www/docs/JavaMail-1.2-changes.txt A new MessagingException subclass to indicate that an attempt was made to open a folder with read-write access when the folder is read-only. Provides methods to get the affected folder. ```Java public class ReadOnlyFolderException extends MessagingException { /** * Constructor. * @param folder the Folder */ public ReadOnlyFolderException(Folder folder) /** * Constructor. * @param folder the Folder * @param message the detailed error message */ public ReadOnlyFolderException(Folder folder, String message) /** * Returns the Folder object. */ public Folder getFolder() } ``` -------------------------------- ### Add Service.connect(user, password) Method Source: https://github.com/jakartaee/mail-api/blob/main/doc/spec/JavaMail-1.4-changes.txt This convenience method connects to the current host using the specified username and password, simplifying the connection process for Transport and Store services. It's equivalent to calling connect(null, user, password). ```Java /** * Connect to the current host using the specified username * and password. This method is equivalent to calling the * connect(host, user, password) method with null * for the host name. * * @param user the user name * @param password this user's password * @exception AuthenticationFailedException for authentication failures * @exception MessagingException for other failures * @exception IllegalStateException if the service is already connected * @see javax.mail.event.ConnectionEvent * @see javax.mail.Session#setPasswordAuthentication ``` -------------------------------- ### Enable STARTTLS for SMTP Source: https://github.com/jakartaee/mail-api/blob/main/www/docs/SSLNOTES.txt Enable the STARTTLS command for SMTP connections by setting the 'mail.smtp.starttls.enable' property to 'true'. The command will be used if the server supports it. ```properties mail.smtp.starttls.enable=true ``` -------------------------------- ### Enable STARTTLS for IMAP Source: https://github.com/jakartaee/mail-api/blob/main/www/docs/SSLNOTES.txt Enable the STARTTLS command for IMAP connections by setting the 'mail.imap.starttls.enable' property to 'true'. The command will be used if the server supports it. ```properties mail.imap.starttls.enable=true ``` -------------------------------- ### Clone Specific Release of Jakarta Mail Source: https://github.com/jakartaee/mail-api/blob/main/www/Build-Instructions.md To download a specific version of Jakarta Mail, use the -b option with the desired release tag. Ensure Git is installed. ```bash % git clone -b 1.6.4 git@github.com:eclipse-ee4j/mail.git ``` -------------------------------- ### Get Default Java Charset Source: https://github.com/jakartaee/mail-api/blob/main/www/docs/JavaMail-1.1-changes.txt This new static method in MimeUtility retrieves the default charset for the platform's locale, returned as a Java charset. This is distinct from MIME charsets. ```java /** * Get the default charset for this locale.

* * @return the default charset of the platform's locale, * as a Java charset. (NOT a MIME charset) */ public static String getDefaultJavaCharset() ``` -------------------------------- ### Build mbox Store Provider Source: https://github.com/jakartaee/mail-api/blob/main/www/Mbox-Store.md Builds the mbox Store provider using Maven. Assumes 'c89' compiler is in PATH and JDK is in /usr/java. ```shell export MACH=`uname -p` export JAVA_HOME=/usr/java cd mbox mvn cd native mvn ``` -------------------------------- ### Build mbox Store Provider on Debian-based systems Source: https://github.com/jakartaee/mail-api/blob/main/www/Mbox-Store.md Builds the mbox Store provider on Debian-based systems, requiring liblockfile-dev and using the 'linux' profile with Maven. ```shell mvn -Plinux ``` -------------------------------- ### Importing Server Certificate using keytool Source: https://github.com/jakartaee/mail-api/blob/main/www/docs/SSLNOTES.txt Use the keytool command to import a server's certificate into your Java keystore. Replace 'imap-server' with your desired alias and 'imap.cer' with the certificate file path. ```bash keytool -import -alias imap-server -file imap.cer ``` -------------------------------- ### Get Default Java Charset for Locale Source: https://github.com/jakartaee/mail-api/blob/main/doc/spec/JavaMail-1.1-changes.txt This static method in MimeUtility retrieves the default charset for the platform's locale. It returns the charset as a Java charset name, not a MIME charset. ```java public static String getDefaultJavaCharset() ``` -------------------------------- ### InternetAddress - Parsing and Formatting Email Addresses Source: https://context7.com/jakartaee/mail-api/llms.txt Demonstrates how to create, parse, and validate email addresses using the InternetAddress class. It covers single address creation with display names, parsing comma-separated address strings, and strict syntax validation. ```APIDOC ## InternetAddress - Parsing and Formatting Email Addresses `InternetAddress` models RFC 822 addresses in `user@host` or `Personal Name ` form. It also provides bulk parsing and local-address utilities. ```java import jakarta.mail.internet.*; // Single address with display name InternetAddress addr = new InternetAddress("bob@example.com", "Bob Jones", "UTF-8"); System.out.println(addr.toString()); // Bob Jones System.out.println(addr.getAddress()); // bob@example.com System.out.println(addr.getPersonal()); // Bob Jones // Parse a comma-separated header string InternetAddress[] recipients = InternetAddress.parse( "Alice , bob@b.com, \"Carol, D\" ", true); for (InternetAddress a : recipients) { System.out.printf(" personal=%-15s address=%s%n", a.getPersonal(), a.getAddress()); } // Output: // personal=Alice address=alice@a.com // personal=null address=bob@b.com // personal=Carol, D address=carol@c.com // Validate strict RFC 822 syntax try { new InternetAddress("not-an-email@@bad", true); // strict=true } catch (AddressException e) { System.err.println("Invalid address: " + e.getMessage()); } // Obtain local address (e.g., for From fallback) // InternetAddress local = InternetAddress.getLocalAddress(session); // System.out.println("Local: " + local); ``` ``` -------------------------------- ### Get MimeMultipart Preamble Text Source: https://github.com/jakartaee/mail-api/blob/main/www/docs/JavaMail-1.4-changes.txt The MimeMultipart.getPreamble() method retrieves any text present before the first body part of a multipart message. Note that some protocols like IMAP may not provide access to this text. ```Java public String getPreamble() throws MessagingException ``` -------------------------------- ### Create and Configure Mail Session Source: https://context7.com/jakartaee/mail-api/llms.txt Use Session.getInstance() for an isolated session with properties like SMTP host, port, authentication, and TLS. An Authenticator can provide credentials inline. Set debug to true to trace protocol interactions. ```java import jakarta.mail.*; import java.util.Properties; // Isolated session with inline credentials via Authenticator Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.example.com"); props.put("mail.smtp.port", "587"); Session session = Session.getInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("user@example.com", "secret"); } }); session.setDebug(true); // write SMTP/IMAP protocol trace to System.out ``` -------------------------------- ### Get Raw InputStream for Body Part Source: https://github.com/jakartaee/mail-api/blob/main/doc/spec/JavaMail-1.2-changes.txt Provides access to the raw data of a body part with Content-Transfer-Encoding intact. Useful when the encoding is incorrect or corrupt, allowing the application to decode the data manually. ```Java public InputStream getRawInputStream() throws MessagingException ``` -------------------------------- ### SharedFileInputStream read with byte array Source: https://github.com/jakartaee/mail-api/blob/main/www/docs/JavaMail-1.4-changes.txt Reads bytes from the file stream into a specified byte array, starting at a given offset and for a maximum number of bytes. This is a standard InputStream operation optimized for file buffering. ```Java public int read(byte[] b, int off, int len) ``` -------------------------------- ### Java Code Block Formatting Source: https://github.com/jakartaee/mail-api/blob/main/www/Contributions.md Demonstrates the correct placement of braces and indentation for Java code blocks. ```java if (foo instanceof bar) { foobar(); barfoo(); } ``` -------------------------------- ### Dummy Trust Manager for SSL Source: https://github.com/jakartaee/mail-api/blob/main/www/docs/SSLNOTES.txt Implements X509TrustManager to accept any certificate. This is insecure and for testing purposes only. ```java import javax.net.ssl.X509TrustManager; import java.security.cert.X509Certificate; /** * DummyTrustManager - NOT SECURE */ public class DummyTrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] cert, String authType) { // everything is trusted } public void checkServerTrusted(X509Certificate[] cert, String authType) { // everything is trusted } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } ``` -------------------------------- ### InternetAddress implements Cloneable Source: https://github.com/jakartaee/mail-api/blob/main/doc/spec/JavaMail-1.2-changes.txt The `InternetAddress` class now implements the `Cloneable` interface and provides a public `clone` method to simplify the process of creating copies of `InternetAddress` objects. ```APIDOC ## `InternetAddress.clone()` ### Description Returns a copy of this `InternetAddress` object. This method allows for easy duplication of `InternetAddress` instances. ### Method Signature `public Object clone()` ### Implements `Cloneable` interface ``` -------------------------------- ### UIDFolder.getMessagesByUID(long start, long end) Source: https://github.com/jakartaee/mail-api/blob/main/www/docs/JavaMail-1.1-changes.txt Modified to return all available messages within the specified UID range, ignoring invalid UIDs instead of throwing NoSuchElementException. This is beneficial for clients fetching large ranges. ```APIDOC ## UIDFolder.getMessagesByUID(long start, long end) ### Description Retrieves Messages corresponding to the given UID range. Invalid UIDs within the range are ignored, and all available Messages are returned. ### Method public Message[] getMessagesByUID(long start, long end) ### Parameters - **start** (long) - The starting UID of the range. - **end** (long) - The ending UID of the range. ### Returns - **Message[]**: An array of Message objects within the specified range. Invalid UIDs are omitted. ### Throws None (previously `java.util.NoSuchElementException`) ``` -------------------------------- ### Enable Debugging for SSL/TLS Issues Source: https://github.com/jakartaee/mail-api/blob/main/www/docs/SSLNOTES.txt Set system properties to enable additional debugging output for certificate path and trust manager issues. This is useful for diagnosing problems with SSL/TLS connections. ```bash java -Djava.security.debug=certpath -Djavax.net.debug=trustmanager ... ``` -------------------------------- ### Get Deleted Message Count from Folder Source: https://github.com/jakartaee/mail-api/blob/main/doc/spec/JavaMail-1.3-changes.txt Retrieves the count of deleted messages in a Folder. This method can be invoked on a closed folder, but may return -1 if the implementation does not support it in a closed state or if it's an expensive operation. ```java /** * Get the number of deleted messages in this Folder.

* * This method can be invoked on a closed folder. However, note * that for some folder implementations, getting the deleted message * count can be an expensive operation involving actually opening * the folder. In such cases, a provider can choose not to support * this functionality in the closed state, in which case this method * must return -1.

* * Clients invoking this method on a closed folder must be aware * that this is a potentially expensive operation. Clients must * also be prepared to handle a return value of -1 in this case.

* * This implementation returns -1 if this folder is closed. Else * this implementation gets each Message in the folder using * getMessage(int) and checks whether its * DELETED flag is set. The total number of messages * that have this flag set is returned. * * @return number of deleted messages. -1 may be returned * by certain implementations if this method is * invoked on a closed folder. * @exception FolderNotFoundException if this folder does * does not exist. * @exception MessagingException * @since JavaMail 1.3 */ public int getDeletedMessageCount() throws MessagingException ``` -------------------------------- ### SharedInputStream Interface Definition Source: https://github.com/jakartaee/mail-api/blob/main/doc/spec/JavaMail-1.2-changes.txt Defines the SharedInputStream interface for InputStreams that support shared data access. It provides methods to get the current position and create new InputStreams representing subsets of the original data without copying. ```java package javax.mail.internet; /** * An InputStream that is backed by data that can be shared by multiple * readers may implement this interface. This allows users of such an * InputStream to determine the current positionin the InputStream, and * to create new InputStreams representing a subset of the data in the * original InputStream. The new InputStream will access the same * underlying data as the original, without copying the data. */ public interface SharedInputStream { /** * Return the current position in the InputStream, as an * offset from the beginning of the InputStream. * * @return the current position */ public long getPosition(); /** * Return a new InputStream representing a subset of the data * from this InputStream, starting at start (inclusive) ``` -------------------------------- ### MimeMultipart.getPreamble() and setPreamble() Methods Source: https://github.com/jakartaee/mail-api/blob/main/doc/spec/JavaMail-1.4-changes.txt Adds `getPreamble()` to retrieve the text preceding the first body part of a multipart message, and `setPreamble()` to set this text when constructing a message. This preamble is often used for compatibility with non-MIME compliant software. ```APIDOC ## Methods: MimeMultipart.getPreamble(), MimeMultipart.setPreamble() ### Description Provides access to the preamble text of a MIME multipart message, which is the content appearing before the first body part. ### `getPreamble()` #### Signature `public String getPreamble() throws MessagingException` #### Returns The preamble text as a `String`, or `null` if no preamble exists. Note that some protocols like IMAP may not provide access to this text. ### `setPreamble(String preamble)` #### Signature `public void setPreamble(String preamble) throws MessagingException` #### Parameters - **preamble** (String) - The text to set as the preamble. #### Description Sets the preamble text for the multipart message. It is generally recommended not to include preamble text unless it serves a specific purpose, such as providing instructions for older email clients. ``` -------------------------------- ### Initialize InternetHeaders with UTF-8 Support (JavaMail 1.6) Source: https://github.com/jakartaee/mail-api/blob/main/doc/spec/JavaMail-1.6-changes.txt Constructs an InternetHeaders object by parsing an RFC822 message stream, with support for UTF-8 encoded headers. The stream is left positioned at the start of the body. Use this for efficient header parsing, especially with internationalized content. ```Java public InternetHeaders(InputStream is, boolean allowutf8) throws MessagingException ``` -------------------------------- ### Session Configuration File Lookup for JDK 1.9+ Source: https://github.com/jakartaee/mail-api/blob/main/doc/spec/JavaMail-1.6-changes.txt Details the updated search order for JavaMail configuration files when running on JDK 1.9 or later, including the new /conf directory. ```APIDOC ## Session Configuration File Lookup ### Description On JDK 1.9 and later, JavaMail searches for its configuration files (javamail.providers, javamail.default.providers, javamail.address.map, javamail.default.address.map) in the following order: 1. `/conf/javamail.X` 2. `META-INF/javamail.X` 3. `META-INF/javamail.default.X` Where `X` represents the specific configuration file name and `` is the value of the "java.home" System property. The "conf" directory was introduced in JDK 1.9. ``` -------------------------------- ### Dynamically Set Default Transport Protocol for Address Type Source: https://github.com/jakartaee/mail-api/blob/main/doc/spec/JavaMail-1.4-changes.txt Use the setProtocolForAddress method in Session to dynamically control the mapping from an address type to a transport protocol. This can be used to change the default internet protocol, for example, from "smtp" to "smtps". ```Java public void setProtocolForAddress(String addresstype, String protocol) ``` -------------------------------- ### Provider Registration - Custom and ServiceLoader Providers Source: https://context7.com/jakartaee/mail-api/llms.txt Register custom Store or Transport implementations programmatically using `Session.addProvider()` or via the `META-INF/services/jakarta.mail.Provider` file for service discovery. ```APIDOC ## Provider Registration — Custom and ServiceLoader Providers Custom `Store` or `Transport` implementations are registered by subclassing `Provider` and registering via `META-INF/services/jakarta.mail.Provider`, or programmatically with `Session.addProvider()`. ```java import jakarta.mail.*; // Programmatic registration example Provider customSmtp = new Provider( Provider.Type.TRANSPORT, "mysmtp", // protocol name "com.example.mail.MyCustomSMTPTransport", // implementing class "Example Corp", // vendor "1.0" // version ); session.addProvider(customSmtp); session.setProvider(customSmtp); // make it default for "mysmtp" Transport t = session.getTransport("mysmtp"); // ... // META-INF/services/jakarta.mail.Provider (file in your JAR): // com.example.mail.MyCustomProvider // META-INF/jakarta.providers (legacy resource file): // protocol=mysmtp; type=transport; class=com.example.mail.MyCustomSMTPTransport; vendor=Example; // List all loaded providers for (Provider p : session.getProviders()) { System.out.printf(" %-10s %-12s %s%n", p.getProtocol(), p.getType(), p.getClassName()); } ``` ``` -------------------------------- ### Delete a Message in Gmail using Jakarta Mail Source: https://github.com/jakartaee/mail-api/blob/main/www/FAQ.html This example illustrates the specific method for deleting messages in Gmail via IMAP. It involves copying the message to the '[Gmail]/Trash' folder and then expunging it for permanent removal. Note that marking as deleted alone does not permanently remove the message. ```java msg.setFlag(Flags.Flag.DELETED, true); folder.close(true); ``` -------------------------------- ### Session Resource File Search Order (JDK 1.9+) Source: https://github.com/jakartaee/mail-api/blob/main/doc/spec/JavaMail-1.6-changes.txt Illustrates the search order for JavaMail resource files (javamail.providers, javamail.address.map, etc.) on JDK 1.9 and later. It prioritizes files in the java.home/conf directory, followed by META-INF/javamail.X and META-INF/javamail.default.X. ```Java 1. java.home/conf/javamail.X 2. META-INF/javamail.X 3. META-INF/javamail.default.X ``` -------------------------------- ### Configure Maven for Jakarta Snapshots Source: https://github.com/jakartaee/mail-api/blob/main/www/README-JakartaMail.md Add this configuration to your Maven settings.xml to enable loading Jakarta snapshot artifacts from the Jakarta Sonatype OSS repository. ```xml jakarta-snapshots jakarta-snapshots Jakarta Snapshots true always fail https://jakarta.oss.sonatype.org/content/repositories/snapshots/ default ``` -------------------------------- ### Get Deleted Message Count from Folder (JavaMail 1.3) Source: https://github.com/jakartaee/mail-api/blob/main/www/docs/JavaMail-1.3-changes.txt Returns the number of deleted messages in a Folder. This method can be invoked on a closed folder, but may return -1 if the implementation does not support it in the closed state or if it's an expensive operation. The default implementation returns -1 for closed folders. ```Java /** * Get the number of deleted messages in this Folder.

* * This method can be invoked on a closed folder. However, note * that for some folder implementations, getting the deleted message * count can be an expensive operation involving actually opening * the folder. In such cases, a provider can choose not to support * this functionality in the closed state, in which case this method * must return -1.

* * Clients invoking this method on a closed folder must be aware * that this is a potentially expensive operation. Clients must * also be prepared to handle a return value of -1 in this case.

* * This implementation returns -1 if this folder is closed. Else * this implementation gets each Message in the folder using * getMessage(int) and checks whether its * DELETED flag is set. The total number of messages * that have this flag set is returned. * * @return number of deleted messages. -1 may be returned * by certain implementations if this method is * invoked on a closed folder. * @exception FolderNotFoundException if this folder does * does not exist. * @exception MessagingException * @since JavaMail 1.3 */ public int getDeletedMessageCount() throws MessagingException ```