Giter Club home page Giter Club logo

mail-api's Introduction

Jakarta Mail

Build Status Jakarta Staging (Snapshots)

Jakarta Mail defines a platform-independent and protocol-independent framework to build mail and messaging applications.

IMPORTANT: The implementation of the Jakarta Mail API, aka JakartaMail (formerly JavaMail), is no longer part of this repository. As part of breaking tight integration between Jakarta Mail API and the implementation, its sources were moved to the new project - Eclipse Angus - and further development continues there. Eclipse Angus is the direct successor of JavaMail/JakartaMail.

See the Jakarta Mail web site.

License

You'll find the text of the licenses in the workspace in various LICENSE.txt or LICENSE.md files. Don't let the presence of these license files in the workspace confuse you into thinking that they apply to all files in the workspace.

You should always read the license file included with every download, and read the license text included in every source file.

Contributing

We use contribution policy, which means we can only accept contributions under the terms of Eclipse Contributor Agreement.

Links

mail-api's People

Contributors

arjantijms avatar bshannon avatar cousjava avatar dependabot[bot] avatar diegosalvi avatar dslztx avatar ggam avatar ibavtovich avatar javamail-bot avatar jayasheelankumar avatar jbescos avatar jmehrens avatar lukasj avatar maeichris avatar mnlipp avatar nubzor avatar pzygielo avatar scottmarlow avatar senivam avatar seongeon-jo avatar tweimer avatar yersan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mail-api's Issues

add Message.getSession() method

Add a method to Message to allow access to the Session used when the
Message was created.

Affected Versions

1.4.5

Environment

All
All

add Transport.send(msg, username, password) method

You shouldn't be required to manage a Transport object yourself just
to authenticate when sending a message. There should be a new static
convenience method for this case.

Affected Versions

1.4.5

Environment

All
All

add additional "next" methods to HeaderTokenizer to help parsing bad headers

Add the following methods to HeaderTokenizer:

/**
 * Parses the next token from this String.
 * If endOfAtom is not NUL, the token extends until the
 * endOfAtom character is seen, or to the end of the header.
 * This method is useful when parsing headers that don't
 * obey the MIME specification, e.g., by failing to quote
 * parameter values that contain spaces.
 *
 * @param   endOfAtom       if not NUL, character marking end of token
 * @return          the next Token
 * @exception       ParseException if the parse fails
 * @since           JavaMail 1.5
 */
Token next(char endOfAtom) throws ParseException

/**
 * Parses the next token from this String.
 * endOfAtom is handled as above.  If keepEscapes is true,
 * any backslash escapes are preserved in the returned string.
 * This method is useful when parsing headers that don't
 * obey the MIME specification, e.g., by failing to escape
 * backslashes in the filename parameter.
 *
 * @param   endOfAtom       if not NUL, character marking end of token
 * @param   keepEscapes     keep all backslashes in returned string?
 * @return          the next Token
 * @exception       ParseException if the parse fails
 * @since           JavaMail 1.5
 */
Token next(char endOfAtom, boolean keepEscapes)
                            throws ParseException

Affected Versions

1.4.5

Environment

All
All

fix protected fields in final classes in javax.mail.search

Some of the final classes in javax.mail.search have protected fields.
Since these classes can't be subclassed, no one can access these protected
fields. These fields should become private.

Affected Versions

1.4.5

Environment

All
All

base64 decoding of multipart mime text checks for error too soon

Created attachment 167
move code to fix this issue

I'm parsing email which contains text encoded in base64 but JavaMail 1.4.2 throws an exception like this:

com.sun.mail.util.DecodingException: BASE64Decoder: Error in encoded stream: needed at least 2 valid base64 characters, but only got 0 before padding character (=), the 10 most recent characters were: "IGFyZSEi\n="
at com.sun.mail.util.BASE64DecoderStream.decode(BASE64DecoderStream.java:263)
at com.sun.mail.util.BASE64DecoderStream.read(BASE64DecoderStream.java:140)
...

I've attached a patch which moves this check down slightly so that the end of the base64 block is correctly detected.

Affected Versions

1

Environment

PC
Linux

Infinite loop if Quota information is not correctly reported by imap server

Dear Javamail community,

while I was connecting to the IMAP server of the Canadian telco Telus (imap.telus.net) I experienced an infinity loop with Javamail. The reason was that Javamail tries to parse an invalid Quota response from the IMAP server and infinitely loops.

The broken response from the IMAP server looks like this:
C: A168 GETQUOTAROOT "folderB/TESTfolder(S)C"
S: * QUOTAROOT folderB/TESTfolder(S)C ""
S: * QUOTA "" (STORAGE 79 102401 MESSAGE 26 10000)
S: A168 OK GETQUOTAROOT completed

Please note the missing " characters around the folder's full name in the server's response.

While parsing the readAtom method of the Response class keeps returning empty strings. This leads to an infinity loop in the getQuotaRoot method of the IMAPProtocol class.

To resolve this situation the getQuotaRoot method must be slightly adjusted to check for empty strings as well:
...
while (((root = ir.readAtomString()) != null) && (!root.isEmpty()))
tab.put(root, new Quota(root));
...

What do you think about this bugfix? Please consider this bugfix to be added to the javamail source as it helps making the library more robust!

Thanks in advance,
Thomas

Affected Versions

1.4.5

Environment

PC
Linux

mw test

Please ignore.

Affected Versions

1

Environment

PC
Linux

should add a TransportClosedException

Should add a TransportClosedException to parallel StoreClosedException,
for use by Transports. And of course should modify the SMTP Transport
to use it.

Affected Versions

1.4.5

Environment

All
All

Add RFC 3348 (IMAP Child Mailbox Extension) support

RFC 3348 allows the server to specify if a folder has or does not have children folders. Supporting this is critical for quickly enumerating all the folders of IMAP accounts that have many non-nested folders (e.g. Gmail).

Note: The RFC says that "It is an error for the server to return both a \HasChildren and a \HasNoChildren attribute in a LIST response." but Gmail violates this:

A57 LIST "" "[Gmail]/%"

  • LIST (\HasNoChildren) "/" "[Gmail]/All Mail"
  • LIST (\HasNoChildren) "/" "[Gmail]/Drafts"
  • LIST (\HasNoChildren) "/" "[Gmail]/Sent Mail"
  • LIST (\HasNoChildren) "/" "[Gmail]/Spam"
  • LIST (\HasChildren \HasNoChildren) "/" "[Gmail]/Starred"
  • LIST (\HasChildren \HasNoChildren) "/" "[Gmail]/Trash"
    A57 OK Success

Affected Versions

1

Environment

PC
Mac OS

ParameterList needs to support use by IMAP

Normally the ParameterList class parses an entire string and separates
it into parameters, combining multi-segment parameters as defined by
RFC 2231. The segments can't be combined until they're all parsed.
When parsing a string, the combining step is done at the end.

The IMAP protocol presents each of the parameters as a separate name/value
pair. The IMAP provider would like to set each of these in a ParameterList,
and then tell the ParameterList to combine the segments when all values
have been set. The current code uses a kludge to do this. There should
be a way for the IMAP provider to subclass ParameterList for this use case,
e.g., by adding a protected method indicating that all values have been set.

Affected Versions

1.4.5

Environment

All
All

add MimeMultipart(String subtype, BodyPart... bps) constructor

It's sometimes convenient to construct a message "bottom up",
by constructing body parts, then a multipart, then the message.
A new MimeMultipart constructor that takes an array of BodyParts
(varargs) would make this more convenient.

Affected Versions

1.4.5

Environment

All
All

test bug kenai

test bug kenai

Affected Versions

1

Environment

All
Mac OS

InternetAddress follows RFC822 but violates RFC1034

Per RFC822, the domain portion of an email address may contain any ASCII character other than chars 0-31 (control characters), 32 (space character) and any of the following: "(", ")", "<", ">", "@", ",", ";", ":", "", <", ".", "[", "]".

However, RFC1034, the DNS Domain Name spec specifies that domain names can only contain alpha numerical characters and the hyphen/dot characters.

The RFC's contradict each other and while technically the InternetAddress class is doing what it says when one passes in 'true' for the strict flag, it yields a potentially bad email address which the user won't find out about until they actually try and send the email message.

I realize that this is not a bug, per se, but JavaMail should probably do something or provide some mechanism to ensure that the Address objects set on a Message object are already valid rather than waiting until the message is sent before failing.

I am, however, open to discussion.

Affected Versions

1

Environment

All
All

Wrong representation of CR/LF are appended to the attachment

When sending an attachment that's encoded in UTF16-BE (big endian/little endian/unicode), the line feeds in the attachment appeared to be broken.

Steps to reproduce

  1. Use the demo program, modify 'sendfile.java' with the following diff
  2. Use the attached text file (encoded in utf16-be) as the attachment, and send it through.

{code}
diff -r 1e32fa90f44b demo/src/main/java/sendfile.java
--- a/demo/src/main/java/sendfile.java Mon Jan 24 16:28:06 2011 -0800
+++ b/demo/src/main/java/sendfile.java Fri Jan 28 16:55:51 2011 -0800
@@ -90,21 +90,21 @@
MimeBodyPart mbp2 = new MimeBodyPart();

    // attach the file to the message
  •   if (false)
      mbp2.attachFile(filename);
    
      /*
       * Use the following approach instead of the above line if
       * you want to control the MIME type of the attached file.
       * Normally you should never need to do this.
    
  •    *
    
  •    */
      FileDataSource fds = new FileDataSource(filename) {
      public String getContentType() {
    
  •       return "application/octet-stream";
    
  •       return "text/plain; charset=utf-16be";
      }
      };
      mbp2.setDataHandler(new DataHandler(fds));
      mbp2.setFileName(fds.getName());
    
  •    */ 
    
      // create the Multipart and add its parts to it
      Multipart mp = new MimeMultipart();
    

{code}

Affected Versions

1.4.4

Environment

All
All

Multiparts do not parse correctly in presence of legacy Mac line endings

Created attachment 426
Example email

I'm attaching an example email which has a Multipart at the top-level, but Multipart.getCount() returns 1 instead of 3. After investigating this for almost a day, it turns out that the problem is related to the line endings. If we convert them to \n up-front then JavaMail can parse the result correctly.

@Test
public void testMultipartWithMacLineEndings() throws Exception
{
    byte[] data = FileUtils.readFileToByteArray(new File("G:\\Invoice Receipt copy.eml"));

    Session session = Session.getDefaultInstance(new Properties());
    MimeMessage mimeMessage = new MimeMessage(session, new ByteArrayInputStream(data));

    Multipart topMultipart = (Multipart) mimeMessage.getContent();
    assertEquals("Wrong number of parts", 3, topMultipart.getCount());
}

Affected Versions

1.4.3

Environment

PC
Mac OS

parse() method removes quotes around personal name when parsing in InternetAddress

The parse() method in \mail\src\main\java\javax\mail\internet\InternetAddress.java(669) always removes surrounding quotes in personal name by calling unquote() in line 1071. Can this behaviour be changed to be over-ridden by an API user via some extra flag, params, etc?

As a user of the parse() method in javamail 1.4.5 and needing to keep the quotes around my personal name (eg. "ID=123456789" [email protected]) for some special configuration reasons (dial-out, etc) what are my options?

Affected Versions

1.4.5

Environment

PC
Windows

BODYSTRUCTURE does not correctly parse extension fields for single-part message

We are encountering an exception when retrieving the Content-Type header of a single-part message from Microsoft Exchange 365. The following debug flags are in effect:

  • Session.setDebug(true)
  • System.setProperty("mail.imap.parse.debug", "true")

===snip===
A6 FETCH 3099 (BODYSTRUCTURE)

  • 3099 FETCH (BODYSTRUCTURE ("text" "plain" ("charset" "utf-8") NIL NIL "quoted-printable" 802 19 NIL "inline" NIL NIL))
    DEBUG IMAP: parsing BODYSTRUCTURE
    DEBUG IMAP: msgno 3099
    DEBUG IMAP: single part
    DEBUG IMAP: type text
    DEBUG IMAP: subtype plain
    DEBUG IMAP: parameter name charset
    DEBUG IMAP: parameter value utf-8
    DEBUG IMAP: cParams ; charset=utf-8
    DEBUG IMAP: id null
    DEBUG IMAP: description null
    DEBUG IMAP: encoding quoted-printable
    DEBUG IMAP: size 802
    DEBUG IMAP: lines 19
    A6 OK FETCH completed.
    DEBUG IMAP: IMAPProtocol noop
    A7 NOOP
    ===snip===

In BODYSTRUCTURE.java:138, there is a call to parseParameters(); looking at this method, it appears to either expect a parenthesized list of parameters or NIL.

However, RFC 3501 doesn't appear to require that extension parameters be passed as a parenthesized list for single-part messages (http://tools.ietf.org/html/rfc3501#section-7.4.2). Unfortunately, there are no examples, and it does look like parenthesis are required for multi-part messages.

Affected Versions

1.4.5

Environment

PC
Linux

SSL Re-Negotiation Problem with checkserveridentity=true

When I enable the checkserveridentity flag, my IMAP client application fails to connect to the server. The server is dovecot (openssl-based) and the error I get in the server logs is this:

TLS: SSL_read() failed: error:140940F5:SSL routines:SSL3_READ_BYTES:unexpected record

The problem is apparently that "checkserveridentity" causes a SSL renegotiation. I don't know if the client is allowed to start a renegotiation at this point, but I think it's not necessary at all.

Have a look at SocketFetcher.java:

    boolean idCheck = PropUtil.getBooleanProperty(props,
			prefix + ".ssl.checkserveridentity", false);
    if (idCheck)
	checkServerIdentity(host, (SSLSocket)socket);
    if (ssf instanceof MailSSLSocketFactory) {
	MailSSLSocketFactory msf = (MailSSLSocketFactory)ssf;
	if (!msf.isServerTrusted(host, (SSLSocket)socket)) {
	    try {
		socket.close();
	    } finally {
		throw new IOException("Server is not trusted: " + host);
	    }
	}
    }
    configureSSLSocket(socket, props, prefix);

As you can see, the call to checkServerIdentity happens before the call to configureSSLSocket. The SSL handshake is supposed to happen during configureSSLSocket, but my debugging shows that the first handshake actually happens during checkServerIdentity. I think this is because checkServerIdentity tries to access the peer's certificates, which is obviously only possible after SSL has been initiated. So what happens is a first handshake (with default settings) during checkServerIdentity, and then a second (renegotiating) handshake immediately afterwards in configureSSLSocket.

Moving the call to configureSSLSocket in front of the call to checkServerIdentity removes the (redundant?) renegotiation and fixes the problems connecting to dovecot for me.

Affected Versions

1.4.5

Environment

PC
Linux

Management of the recipients list. (rfc: 5321, section: 4.5.3)

Hi.
I used the package to deliver mails to a large number of destinations and I received the following error:

javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 452 #4.5.3 Too many recipients.

Details: first I instanced a MimeMessage object with the list of recipients, then I use the Trasport class to send it.

The rfc 5321, limit the number to 100 recipients and each path (forward or reply) not longer than 256 bytes, and I used only 82 recipients...

I believe that this is a server SMTP error, but I was asking whether it can be implemented a better management of the Trasport class, so to junk the list in two or more parts, and send automatically emails, without errors.

Thanks

R. AGOSTINO

Affected Versions

1.4.4

Environment

PC
Windows

IMAPMessage.loadEnvelope() may hang on certain IMAP servers

Steps to reproduce:

Place this mail in the inbox of the IMAP store:

--
From: [email protected]
To: [email protected]
Subject: Here goes nothing (or does it

This mail will hang.

The trick is to leave an open parenthesis inside the subject, without a corresponding closing one!

Now as soon as the command

FETCH 1 (ENVELOPE INTERNALDATE RFC822.SIZE)

has been issued, no fetch response will return from certain IMAP servers, like Cyrus or MDaemon.

It's possibly due to incorrect parsing of the envelope string on the mail server side (containing a lot of parentheses usually).

Some other servers will provide the correct response to IMAPProtocaol.fetch(seqNo, envCmd) however, like MS Exchange, so you won't notice the problem there!

If mail.imap.timeout has been set, IMAPMessage will throw a FolderClosedException after the time has elapsed. If not, the thread will hang forever!

A possible workaround would be to not use any methods that will call the loadEnvelope method internally.

Note: it might be a good idea to implement methods to retrieve the date and size alone so the overhead of loading the envelope along won't be necessary if it's not used later on.

Affected Versions

1.4.4

Environment

All
All

SMTPSaslAuthenticator mishandles empty responses from SaslClient

The SaslClient.evaluateChallenge documentation (http://docs.oracle.com/javase/1.5.0/docs/api/javax/security/sasl/SaslClient.html#evaluateChallenge(byte[])) describes the case of a client returning null to signify that no response needs to be sent to the server. This could be useful, for example, if the server wanted to update the client with some information at the end of the SASL negotiation.

However, in SMTPSaslAuthenticator.authenticate, at line 185, if the server has sent a 334 response to the client, there is no way to avoid sending something back to the server. If the client returns null, this code will convert that to a "*", which aborts the authentication. If the client returns non-null, the return value will be sent to the server.

If the SaslClient returns null, SMTPSaslAuthenticator should not send anything to the server, but should instead try to read the next line from the server.

Affected Versions

1.4.5

Environment

All
All

SharedFileInputStream does not behave as specified

when the close method is called on a SharedFileInputStream it behaves inconsistent depending on the "master" flag, which causes all derived streams to be closed as well.
this is contradicts what is defined in the SharedInputStream interface where it says:

  • Note that implementations of this interface must ensure that the
  • close method does not close any underlying stream
  • that might be shared by multiple instances of SharedInputStream
  • until all shared instances have been closed.

we are using the SharedFileInputStream outside of the java mail context and had problems due to this unexpected behavior. for example if derived streams are used in different threads and the master stream gets closed.

Affected Versions

1.4.4

Environment

PC
Windows

Add SOCKS5 support

I need in my multithreading application to use SOCKS5 for each threads so I can't use System.setProperty() for whole application (I need each socks for each thread).
So can you add support of SOCKS5?

Affected Versions

1.4.5

Environment

PC
Linux

SMTP socket connections are not closed on timeout waiting for server header

Create a server using a dumb socket listener like netcat to just listen on a port.

Have JavaMail client connect to that port to send mail.

JavaMail client times out waiting on the server to send "220 ...", but leaves the Socket connected until the Transport object is finalized.

Transport.close() is ineffective because the service is not marked as connected.

Stack trace is from JavaMail 1.4.2, but SMTPTransport code has not changed
since then to fix this.

javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1925)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1684)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:525)
at javax.mail.Service.connect(Service.java:291)
...
Caused by: java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:106)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:84)
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1903)
... 17 more

Affected Versions

1.4.4

Environment

PC
Mac OS

wrong message accessed when another client expunges and adds messages

In some cases, when another client expunges messages from a folder
and adds new messages to the folder, JavaMail's tracking of message
sequence numbers can be confused, causing JavaMail to use the wrong
sequence number when accessing the the messages after the expunged
messages. The problem only occurs with just the right sequence of
expunges and message additions, and usually requires that at least
64 new messages are added to the folder.

The problem is unrelated to expunges or additions done only by the
JavaMail client, and can be seen by a JavaMail client monitoring
a folder for new and deleted messages from another client.

When the problem occurs, JavaMail may simply access the wrong message,
which may not be immediately apparent to the client. Or, JavaMail
may use an invalid sequence number when accessing a message, which
may cause a MessagingException.

Affected Versions

1.4.4

Environment

All
All

Work with servers which response "235 auth failure"

As we know 235 answer means that auth is successful. But some servers like qmail response "235 auth failure" and JM accept this answer as successful auth.
So it's neccessary to parse also some strings in response like "fail" and so on.

Affected Versions

1.4.5

Environment

PC
Linux

Released sources don't compile

Running ant in the source zip provided at
http://kenai.com/projects/javamail/downloads/download/javamail-1.4.3-src.zip

results in

BUILD FAILED
/usr/src/ark/BUILD/javamail-1.4.3/build.xml:330: /usr/src/ark/BUILD/javamail-1.4.3/legal/src/main/resources/META-INF not found.

There is no legal directory inside the zip file, but build.xml references files in it.

Also, bugzilla shows a version 1.4.4 option while the latest version on the source download page is 1.4.3.

Affected Versions

1.4.3

Environment

PC
Linux

STARTTLS when already using SSL may cause connection to fail

Created attachment 531
Brief Java Programm to Reproduce the Case

Hi all,

I am using mail.imap.socketFactory.fallback=true and this stops my code from connecting to some providers (like freenet.de and aol.com).

The reason is that some providers like the ones named above advertise STARTTLS even though the connection to the server is already secured by SSL. Javamail picks this advertisement for STARTTLS up and tries to initiate TLS over a SSL connection. This is then rejected by these (previously named) IMAP servers. See the log for mx.freenet.de while connecting over SSL:
DEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc]
...
DEBUG: enable STARTTLS
...

  • OK IMAP ready.
    A0 CAPABILITY
  • CAPABILITY IMAP4rev1 AUTH=CRAM-MD5 QUOTA STARTTLS
    A0 OK CAPABILITY completed
    DEBUG IMAP: AUTH: CRAM-MD5
    DEBUG: protocolConnect login, host=mx.freenet.de, user=[email protected], password=
    A1 STARTTLS
    A1 NO TLS already active
    DEBUG IMAP: STARTTLS ProtocolException: com.sun.mail.iap.CommandFailedException: A1 NO TLS already active

I attached a small java program that reproduces the case with Javamail 1.4.5.

I also attached a bugfix for this. The change is simple: It just checks if the socket is not of instance SSLSocket before initiating the STARTTLS sequence.

As TLS over SSL does not make much sense I believe this change is valid and sound. I tested this bugfix with all kinds of IMAP servers (like dovecot, courier, cyrus, 1&1, etc) and different SSL/TLS settings. I could not find any interference with this bugfix.

Could you please review my bug description and the solution I propose?

Best regards,
Thomas

Affected Versions

1.4.5

Environment

All
All

Some messages are marked as read after getting their content

I am using JavaMail to check mail via IMAP + SSL. Here is part of my code:

Get unread messages:

import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.search.FlagTerm;
import javax.mail.Multipart;

...

private void checkMail() {
//login
...

//get unread messages
Folder inbox = store.getFolder("inbox");
inbox.open(Folder.READ_WRITE);
FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
Message[] messages = inbox.search(ft);

//for each message
for (Message message : messages) {
  //do something
  ...

  //check attachment
  boolean hasAttachment = false;
  try {
    Object content = message.getContent();
    if (content instanceof Multipart) {
      Multipart multipart = (Multipart) content;
      for (int i = 0; i < multipart.getCount(); i++) {
        if (BodyPart.ATTACHMENT.equalsIgnoreCase(multipart.getBodyPart(i).getDisposition())) {
          hasAttachment = true;
          break;
        }
      }//for
    }//if
  } catch (Exception ex) {}
  finally {
    /*
     * currently, for some messages, after checking attachment by this way,
     * the messages are marked as read, so we need to mark them as unread
     */
    message.setFlag(Flag.SEEN, false);
  }
}

Please see the comments, currently, after getting content of some messages, the message will be marked as read. For instance, those messages are sent from vworker.com to me daily. They are about new projects on the site. I tested by forwarding messages to another mail account, but the code ran fine. So the code runs failed with original messages.

It is hard for you to check this. But if you have free time, please register at vworker.com, then make a search settings, the site will send you email about new projects daily.

My project is open source. Here is the link to the file containing above code:
http://code.google.com/p/mail-gate/source/browse/src/main/java/group/pals/mailgate/threads/EmailReader.java

Affected Versions

1.4.4

Environment

All
Linux

IMAP Store socket leak on connect with ProtocolException

I ran into a bug where after failing to make an IMAP connection to the mail server the connection would stay half opened (in a CLOSED_WAIT state - the connection was closed by the mail server but never closed by the IMAP Store). The exception being thrown had the message "No login methods supported!". I am invoking close on the IMAP Store after receiving the exception, but the socket stays in the half open state.

Downloading the source code and doing some investigating, I found that the login method, called from protocolConnect, of IMAPStore is throwing a ProtocolException which was caught in protocolConnect which is then rethrowing a MessagingException. The connect method of Service calls protocolConnect method of IMAP Store. The connection boolean is never set to true and thus calling close on the IMAP Store does not close the underlying socket.

Perhaps the ProtocolException catch block in protocolConnect should do the same as the CommandFailedException and disconnect the underlying protocol, like:

{noformat}
if(protocol != null)
protocol.disconnect();
protocol = null;
{noformat}

This fixed the socket leak for me. Is this the right fix for this issue?

Affected Versions

1.4.5

Environment

PC
Windows

Yahoo: Error reading emails containing "undisclosed recipients" as a recipient

Hello all,

with Javamail 1.4.5 it is not possible to retrieve the envelope of emails from Yahoo containing "undisclosed recipients" as a recipient. If you try to retrieve such an email you get an exception:
javax.mail.MessagingException: Failed to load IMAP envelope
at com.sun.mail.imap.IMAPMessage.loadEnvelope(IMAPMessage.java:1265)
at com.sun.mail.imap.IMAPMessage.getSize(IMAPMessage.java:394)
...

The reason is that Yahoo returns the recipient in a wrong format:
A8 FETCH 2 (ENVELOPE INTERNALDATE RFC822.SIZE)

  • 2 FETCH (INTERNALDATE "24-Apr-2012 20:28:58 +0000" RFC822.SIZE 155937 ENVELOPE ("Wed, 28 Sep 2011 11:16:17 +0100" "[WI] Call for Papers (Neurocomputing Special Issue on Image Feature Detection and Description)" ((NIL NIL "xxx" "tju.edu.cn")) ((NIL NIL "xxx" "gmail.com")) ((NIL NIL "xx" "tju.edu.cn")) (("undisclosed-recipients" NIL ""undisclosed-recipients"" NIL )) NIL NIL NIL "CAPr0uQNP+cSbqaJ_J1fA6A0vY6v6WhjwfTL5yRVX8Vbu5YpvZQ@mail.gmail.com"))

To be more precise the reason is the space after the last NIL in
("undisclosed-recipients" NIL ""undisclosed-recipients"" NIL ))

The root cause of the problem is Yahoo as it delivers the emails in a wrong format. However, in order to make Javamail more robust I propose the following patch:
tking@linux-tu08:/test/javamail_hg/javamailmercurial/mail/src/main/java/com/sun/mail/imap/protocol> hg diff ENVELOPE.java
diff -r 42b6d8c53009 mail/src/main/java/com/sun/mail/imap/protocol/ENVELOPE.java
--- a/mail/src/main/java/com/sun/mail/imap/protocol/ENVELOPE.java Fri Mar 23 14:31:07 2012 -0700
+++ b/mail/src/main/java/com/sun/mail/imap/protocol/ENVELOPE.java Wed Apr 25 00:10:20 2012 +0200
@@ -158,7 +158,14 @@
r.readString(); // throw away address_list
String mb = r.readString();
String host = r.readString();

  •    if (r.readByte() != ')') // skip past terminating ')'
    
  •       byte character = r.readByte();
    
  •       // this check is required because Yahoo IMAP servers set such a string if undisclosed-recipients (or similar strings) are used as a recipient:
    
  •       // (("undisclosed-recipients" NIL "\"undisclosed-recipients\"" NIL ))
    
  •       // here the last character in the string before the brakets is a space
    
  •       if (character == ' ') {
    
  •           character = r.readByte();
    
  •       }
    
  •    if (character != ')') // skip past terminating ')'
           throw new ParsingException("ADDRESS parse error");
    
      if (host == null) {
    

Please review the patch and my proposed solution.

Best regards,
Thomas

Affected Versions

1.4.5

Environment

All
All

InputStreams are not closed in MimeMultipart

in the parse() and parsebm() methods there are new InputStreams created but never closed.

part = createMimeBodyPart(sin.newStream(start, end));

due to the wrong implementation of the SharedFileInputStream it is not seen as a problem, because the master stream is closed in the finally which also closes this sub-stream.

however this becomes a problem when you are using a SharedInputStream implementation that behaves as specified (for example the bouncy-castle lib has such an implementation)
In that case, the unclosed stream results in a file handle leak.

Affected Versions

1.4.4

Environment

PC
Windows

add FetchProfile.Item.SIZE

Should add FetchProfile.Item.SIZE to allow prefetching the size
of a message. This is currently an IMAP-specific fetch item.

Affected Versions

1.4.5

Environment

All
All

ContentType.toString and ContentDisposition.toString should never return null

The general contract of the Object.toString method is that it always
returns a non-null value. The JavaMail spec says that null can be
returned in error cases. This should be changed to always return a
value.

This is, of course, an incompatible change, but I think it's justified
to match the general contract of toString.

Affected Versions

1.4.5

Environment

All
All

Directory traversal vulnerability in MimeBodyPart.getFileName(): CVE-2005-1105

This issue was originally identified on bugtraq in 2005:

http://marc.info/?l=bugtraq&m=111335615600839&w=2

The vulnerability does not appear to have ever been addressed. Looking at the latest code in hg, I see:

mail/src/main/java/javax/mail/internet/MimeBodyPart.java

Is still missing any protection against directory traversal in getFileName(). Could this issue please be addressed in the next release? I am happy to provide a suggested patch if that helps. Thanks!

Affected Versions

1.4.5

Environment

All
All

The cachemultipart enhancement is not working properly in specific use cases

The cachemultipart enhancement is not working properly in specific use cases. Please also see the following bug opened in BC:

http://www.bouncycastle.org/jira/browse/BJA-406

And this code which is implemented in 1.4.7.

// Paranoia:
// allow this last minute change to be disabled if it causes problems
static final boolean cacheMultipart = 	// accessed by MimeMessage
PropUtil.getBooleanSystemProperty("mail.mime.cachemultipart", true);

I was unable to verify a complex multipart containing a part which is actually a multipart on its own. The nested multipart has 4 parts, 2 of which are encrypted.

The problem seems to occur in the method SMIMEUtil.outputBodyPart() which is processing the nested body part incorrectly. This is working with 1.43.
line 294 - MimeMultipart mp = (MimeMultipart)bodyPart.getContent(); - the mp object has obviously 4 parts, which is correct. Everything seems OK until we reach line 328 which is added only recently and in 1.43 it was not there. Why was this method added?
line 328 - outputPostamble(lOut, mimePart, mp.getCount(), boundary); - the mimePart is actually the same object as bodyPart, but in this method the Raw Input Stream is read and the boundaries are counted. Although this multipart has 4 parts only 4 boundaries are counted, but 5 are expected, which throws an exception for a mismatch in the boundaries count. This happens because one of the boundaries is not visible using the raw input stream. Because the third and the fourth parts of the multipart are encrypted, while reading the input stream it doesn't match the check if a line starts with a boundary, because the boundary between these parts is also encrypted.

Please advise why was this line added there and is there a workaround for this issue?

This was resolved by setting the property mail.mime.cachemultipart=false.
It seems that the cache mechanism is not working as required.

Affected Versions

1.4.5

Environment

PC
Windows

javamail 1.4.4 - OOM occurs when receive emails for a POP3 account that has more than 14,612,804 messages in INBOX

We encounters OOM (OutOfMemoryError) when tried to receive emails for a POP3 account that has more than 14 million messages in its INBOX.
The heap size of JVM is 3GB and we are using a 64-bit JVM.

I think it happens when opening folder, since from the heap dump, I can find that the size of the vector POP3Folder#message_cache is 14,612,804, while there are only 13,583,387 instances of POP3Message. So OOM happens while it tried to create the 13583388th instance of POP3Message.
And the size of an empty POP3Message is 216 bytes, so it costs us 216 * 13583387 = 2934011592 bytes = 2.73GB

I think a quick fix is enough for this case, e.g. if the total message in the folder is more than a configurable value (e.g., 10, 000), then throw an exception. Or if you can fix it like IMAPFolder in javamail 1.4.4, then it would be better.

Affected Versions

1.4.4

Environment

Other
Linux

ArrayIndexOutOfBoundsException at com.sun.mail.imap.MessageCache.getMessage(MessageCache.java:117)

Hi!

We're getting this exception when reading an attachment from a part using this code:

  1. Message message;
  2. Multipart multipart = (Multipart) message.getContent();
  3. Part part = multipart.getBodyPart(index);
  4. IOUtils.copyLarge(part.getInputStream(), contentsOutputStream);

Exception is thrown in the line 4. Here we're reading the contents of the attachment to an outputStream that is a ByteArrayOutputStream.

I didn't find this as a bug in the bug database.

Any help with this will be very appreciated as It is affecting a service in production that we have.

Here is the stack trace, we're using Microsoft's mail server with IMAP to retrieve mail from a cron job.

java.lang.ArrayIndexOutOfBoundsException: message number out of bounds
at com.sun.mail.imap.MessageCache.getMessage(MessageCache.java:117)
at com.sun.mail.imap.MessageCache.getMessageBySeqnum(MessageCache.java:147)
at com.sun.mail.imap.IMAPFolder.getMessageBySeqNumber(IMAPFolder.java:2735)
at com.sun.mail.imap.IMAPFolder.handleResponse(IMAPFolder.java:2412)
at com.sun.mail.iap.Protocol.notifyResponseHandlers(Protocol.java:212)
at com.sun.mail.imap.protocol.IMAPProtocol.fetchBody(IMAPProtocol.java:1222)
at com.sun.mail.imap.protocol.IMAPProtocol.fetchBody(IMAPProtocol.java:1209)
at com.sun.mail.imap.IMAPInputStream.fill(IMAPInputStream.java:144)
at com.sun.mail.imap.IMAPInputStream.read(IMAPInputStream.java:204)
at com.sun.mail.imap.IMAPInputStream.read(IMAPInputStream.java:230)
at com.sun.mail.util.BASE64DecoderStream.getByte(BASE64DecoderStream.java:354)
at com.sun.mail.util.BASE64DecoderStream.decode(BASE64DecoderStream.java:245)
at com.sun.mail.util.BASE64DecoderStream.read(BASE64DecoderStream.java:140)
at java.io.FilterInputStream.read(FilterInputStream.java:90)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1025)
at com.odc.salesforceservice.messaging.inbounddocument.mail.EmailParser.addAttachments(EmailParser.java:130)

Affected Versions

1.4.4

Environment

PC
Windows

POP3 UIDL capability not supported

If the server does not list UIDL capability in the response to CAPA before authentication, POP3Folder will fail to retrieve the message IDs.

If the server does list the UIDL capability but only after a successful login, the POP3Folder will not list the UIDLs of the messages even though it should.

According to the RFC there is no harm in listing different capabilities in TRANSACTION and AUTHORIZATION state

http://www.ietf.org/rfc/rfc2449.txt

Fix: reload the capabilities after a successful login

Affected Versions

1.4.5

Environment

PC
Linux

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.