You are on page 1of 175

JavaMail FAQ From jGuru

Generated Sep 13, 2005 2:11:33 PM

Location: http://www.jguru.com/faq/JavaMail
Ownership: http://www.jguru.com/misc/user-agree.jsp#ownership.

How do I send email from a servlet?


Location: http://www.jguru.com/faq/view.jsp?EID=154
Created: Sep 3, 1999 Modified: 2000-07-25 12:18:54.284
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3)

From: James Cooper (pixel@bitmechanic.com)

GSP and GnuJSP both come with SMTP classes that make sending email very simple.
if you are writing your own servlet you could grab one of the many SMTP
implementations from www.gamelan.com (search for SMTP and java). All the ones
I've seen are pretty much the same -- open a socket on port 25 and drop the mail
off. so you have to have a mail server running that will accept mail from the machine
JServ is running on.

See also the JavaMail FAQ for a good list of Java mail resources, including SMTP and
POP classes.

Comments and alternative answers

If you want to use the JavaMail API, get it and create...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jul 24,
2000
If you want to use the JavaMail API, get it and create a program similar to the Hello
World program.

See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Sep 20, 2001
This thread: Re: Automatically send and get mails using servlet...

Some examples
Author: Chris Lack (http://www.jguru.com/guru/viewbio.jsp?EID=326717), Sep 21,
2001
I've written an "EMailClient" class for sending e-mails for my guestbook entries. I've
also done an "InBox" servlet class that lists e-mails in your pop mail in-box so that
you can delete or bounce them before downloading to your PC. Have a look at the
code, it might help -

http://www.chris.lack.org and choose the java option on the professional menu.

By the way you'll need JavaMail and Java Activation foundation from Sun if you've
not already downloaded them. You don't need your own mail server.
How can I send email from a JSP page?
Location: http://www.jguru.com/faq/view.jsp?EID=1163
Created: Nov 19, 1999 Modified: 2002-03-26 06:47:10.343
Author: Govind Seshadri (http://www.jguru.com/guru/viewbio.jsp?EID=14)

The JavaMAIL API is the standard mechanism for sending email. See the JavaMail
FAQ for how to use it. You can place j2ee.jar (or mail.jar and activation.jar) under
web-inf/lib folder in tomcat3.2.4.

You can send email from any JSP engine (like the JSWDK reference implementation)
that supports the Sun specific sun.net.smtp package.

(Statutory warning: Using internal Sun-specific packages is not an approach jGuru


recommends, as it will prevent your JSP pages from being truly portable.)

The following scriptlet makes use of the SmtpClient class to send an email from
within a JSP page.

<%@ page import="sun.net.smtp.SmtpClient, java.io.*" %>


<%
String from="gseshad@hotmail.com";
String to="gov@jguru.com, govi@bigfoot.com";
try{
SmtpClient client = new SmtpClient("mail.xxxxx.xxx");
client.from(from);
client.to(to);
PrintStream message = client.startMessage();
message.println("To: " + to);
message.println("Subject: Sending email from JSP!");
message.println("This was sent from a JSP page!");
message.println();
message.println("Cool beans! :-)");
message.println();
message.println();
client.closeServer();
}
catch (IOException e){
System.out.println("ERROR SENDING EMAIL:"+e);
}
%>
Comments and alternative answers

error in the scriptlet


Author: Fabio Mercuri (http://www.jguru.com/guru/viewbio.jsp?EID=1049210), Jan
22, 2003
after the line PrintStream message = client.startMessage(); the scriptlet sets in the
message stream the following attribute: message.println("To: " + to); in this way the
received email will not display the from address! The correct lines are: PrintStream
message = client.startMessage(); message.println("From: " + from);
message.println("To: " + to); As regards
Re: error in the scriptlet
Author: john turner (http://www.jguru.com/guru/viewbio.jsp?EID=1122937), Oct
21, 2003
I can never get the subject line to be included in the email when using the
SmtpClient class. Don't think there's anything wrong with me code, it works
perfectly well apart from this. Has anyone else had this problem?
String from="me@myDomain.com";
String to = (String)session.getAttribute("enqEmail");
String subject="Rate Response";
try{
SmtpClient client = new SmtpClient("Server");
client.from(from);
client.to(to);
PrintStream message = client.startMessage();
message.println("From: " + from);
message.println("To: " + to);
message.println("Subject: " + subject);

Re[2]: error in the scriptlet


Author: Tushar Kapila (http://www.jguru.com/guru/viewbio.jsp?EID=1059392),
Jan 22, 2004
the subject should come before the To, thus: message.println("From: " + from);
message.println("Subject: " + subject); message.println("To: " + to);

Take a look at the jakarta taglibs


Author: Thiadmer Sikkema (http://www.jguru.com/guru/viewbio.jsp?EID=1079811),
Jan 21, 2004
Include the taglib declaration in your web.xml and use the following code in your
JSP:
<%@ taglib uri="http://jakarta.apache.org/taglibs/mailer-1.1"
prefix="mt" %>
<mt:mail server="home.net" to="foo@home.net"
from="bar@home.net" subject="mail taglib">
<mt:message>[body of message]</mt:message>
<mt:send/>
</mt:mail>
Jakarta Project: Mailer Tag library docs

What do I need to acquire in order to get started with JavaMail?


Location: http://www.jguru.com/faq/view.jsp?EID=4139
Created: Jan 5, 2000 Modified: 2000-09-10 09:04:15.57
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The reference JavaMail implementation is available from Sun from


http://java.sun.com/products/javamail/. You also need the JavaBeans Activation
Framework extension from http://java.sun.com/beans/glasgow/jaf.html. If you
intend to use JavaMail to read mail, you also need a POP3 provider and might wish to
pick up the provider that Sun offers (also available from
http://java.sun.com/products/javamail/).
The JavaMail libraries works with Java 1.1.x or greater.

Read the LICENSE.txt file that comes with the tools for complete redistribution
information. Basically you are free to redistribute the unmodified packages.

What is the basic SMTP protocol for sending mail?


Location: http://www.jguru.com/faq/view.jsp?EID=4344
Created: Jan 8, 2000 Modified: 2002-03-30 19:06:02.876
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

RFC 2821 (http://www.faqs.org/rfcs/rfc2821.html) defines the SMTP protocol. To


send a message you would normally open up port 25 on your mail server and send
the following information:

HELO sending host


MAIL FROM: sender email
RCPT TO: recipient email
DATA
... the email message...
... any number of lines ...
.
QUIT

Between the DATA line and the . (period) line is the message. The period is alone on
the line following the end of the message.

Comments and alternative answers

A much more cogent place to start learning more about...


Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4), Jan 27, 2000
A much more cogent place to start learning more about SMTP than the RFCs is at
http://cr.yp.to/smtp.html.

How can I send mail when I don't have the JavaMail libraries installed?
Location: http://www.jguru.com/faq/view.jsp?EID=5062
Created: Jan 15, 2000 Modified: 2000-07-25 12:50:33.754
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Assuming you have access to an SMTP server that will accept your request, you can
either open up a socket connection to port 25 and send the raw SMTP commands, or
use the non-standard sun.net.smtp.SmtpClient class that is provided with Sun's
development environments.

Keep in mind that both the JavaMail library and JavaBeans Activation Framework are
in javax.* packages and thus downloadable to an applet.

And for an application, you can always just install them yourself.

In the case of an untrusted applet, the web server and SMTP server must be the
same machine.
Comments and alternative answers

SMTP raw commands


Author: Sir Peter Brightman (http://www.jguru.com/guru/viewbio.jsp?EID=786643),
Mar 7, 2002
take a look at the socket-test program from castalia.com, it comes with SMTP
examples:

How to simulate an SMTP converstaion... Refer to RFC 821


(ftp://ds.internic.net/rfc/rfc821.txt)

The service port for the SMTP protocol is 25.

NOTE: Make sure you are appending a CRLF to the end of each line sent.

Instructions
------------

Set the Connect to IP address to an SMTP server such as mail.compuserve.com.

Set the port to 25.

Select Actions|Connect to a Server.

Below is the transmission log from a typical session. For your testing, type in all lines
that start with the word Sent:

Connected to IP = 149.174.183.74 on server port #25 From socket(128)--> 220-


csi.com Microsoft SMTP MAIL ready at Sat, 19 Jul 1997 21:45:01 -0400 220
ESMTP spoken here

Sent: HELO CASTALIA.COM

From socket(128)--> 250 csi.com Hello [204.179.128.110]

Sent: VRFY smith

From socket(128)--> 252 Cannot VRFY user, but will take message for smith

Sent: MAIL FROM:<weo@castalia.com>

From socket(128)--> 250 weo@castalia.com....


Sender OK

Sent: RCPT TO:<weo@castalia.com>


From socket(128)--> 250 weo@castalia.com

Sent: DATA

From socket(128)--> 354 Start mail input; end with <CRLF>.<CRLF>

Sent: Test message via compuserve...

Sent: SMTP is easy...

Sent: .

From socket(128)--> 250 04f831546011477NIH2WAAE Queued mail for delivery

Sent: QUIT

From socket(128)--> 221 csi.com Service closing transmission channel

Lost connection on socket(128)

Note:

For CRLF
CR stands for carriage return
LF stands for linefreed

Use '\r' for carriage return and '\n' for line feed.

Is there a mailing list for discussion of the JavaMail API?


Location: http://www.jguru.com/faq/view.jsp?EID=9967
Created: Jan 29, 2000 Modified: 2000-07-25 12:50:54.46
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Sun manages the JAVAMAIL-INTEREST list. You can signup at


http://archives.java.sun.com/archives/javamail-interest.html.

I am trying to send a mail through JavaMail but I am getting an exception:


Could not connect to SMTP host 25. How to give this SMTP host?
Location: http://www.jguru.com/faq/view.jsp?EID=12854
Created: Feb 9, 2000 Modified: 2000-07-25 12:51:34.544
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by chandu sekhar
(http://www.jguru.com/guru/viewbio.jsp?EID=12358

If you get an exception like:


Exception in thread "main" javax.mail.MessagingException:
Could not connect to SMTP host: www.myhost.com, port: 25;

it means there is no mail (SMTP) server software running on the designated host.
You'll need to find an appropriate host to use as your transport.
Comments and alternative answers

Not totally true ..


Author: Serge Sozonoff (http://www.jguru.com/guru/viewbio.jsp?EID=1019873),
Dec 19, 2002
This is not totally true. I have seen this Exception several times when in fact there is
an SMTP server on the other end, only it is not immediately returning a 220 response.
This can often be because your server is lacking a reverse DNS entry or maybe you
have been blacklisted and the remote SMTP host is just creating a black hole. Other
thoughts welcome.... Serge

Re: Not totally true ..


Author: Peter Feldman (http://www.jguru.com/guru/viewbio.jsp?EID=1060651),
Feb 25, 2003
I find that when there is no server running I get
javax.mail.SendFailedException: Sending failed;
nested exception is: class javax.mail.MessagingException: Unknown SMTP host:
<servername>
nested exception is: java.net.UnknownHostException: <servername>

I get the following when the session cannot be established to the existing server.
javax.mail.SendFailedException: Sending failed;
nested exception is: class javax.mail.MessagingException: Could not connect to
SMTP host: <servername>, port: 25;
nested exception is: java.net.ConnectException: Connection refused: connect

What is the proverbial "Hello, World" program for JavaMail?


Location: http://www.jguru.com/faq/view.jsp?EID=12858
Created: Feb 9, 2000 Modified: 2001-08-19 06:57:29.633
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The following program will send a mail message. It requires three command line
arguments:

• SMTP Server
• From Email Address
• To Email Address

An example start follows:

java MailExample smtp.mailserver from@from.com to@to.com


Source:

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class MailExample {


public static void main (String args[])
throws Exception {
String host = args[0];
String from = args[1];
String to = args[2];

// Get system properties


Properties props = System.getProperties();

// Setup mail server


props.put("mail.smtp.host", host);

// Get session
Session session = Session.getInstance(props, null);

// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("Hello JavaMail");
message.setText("Welcome to JavaMail");

// Send message
Transport.send(message);
}
}

How do I send mail using the non-standard sun.net.smtp.SmtpClient class?


Location: http://www.jguru.com/faq/view.jsp?EID=16021
Created: Feb 19, 2000 Modified: 2000-07-25 12:53:36.191
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Sun's Java runtime environments (as well as the ones included with Netscape
Communicator and Internet Explorer) include the SmtpClient class. As part of the
sun.net package, it is not a standard Java library. However, since it is available, you
may wish to use it to send mail, without going for the full fledged JavaMail
installation.

The following program demonstrates how to send mail with the class:

import sun.net.smtp.SmtpClient;
import java.io.PrintStream;

public class SmtpClientExample {


public static void main (String args[])
throws Exception {
String host = args[0];
String from = args[1];
String to = args[2];

SmtpClient smtp = new SmtpClient(host);


smtp.from(from);
smtp.to(to);

PrintStream msg = smtp.startMessage();


msg.println("To: " + to);
msg.println("Subject: Hello SmtpClient");

// blank line between headers and message


msg.println();
msg.println("This is a test message.");

smtp.closeServer();
}
}

How can I get a list of messages from my POP3 server?


Location: http://www.jguru.com/faq/view.jsp?EID=17030
Created: Feb 22, 2000 Modified: 2000-07-25 12:54:43.311
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

After getting a POP3 provider for JavaMail (quite possibly from Sun at
http://java.sun.com/products/javamail/pop3.html, getting a list of messages
involves the following steps:

1. Creating a session
2. Getting a store for the POP3 provider
3. Getting a folder to read messages from (even if the provider doesn't use
folders)
4. Then finally getting a directory of messages

The following program demonstrates this:

import javax.mail.*;
import javax.mail.internet.*;

public class GetListExample {


public static void main (String args[])
throws Exception {
String host = args[0];
String username = args[1];
String password = args[2];

// Get session
Session session = Session.getInstance(
System.getProperties(), null);

// Get the store


Store store = session.getStore("pop3");
store.connect(host, username, password);

// Get folder
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);

// Get directory
Message message[] = folder.getMessages();
for (int i=0, n=message.length; i<n; i++) {
System.out.println(i + ": "
+ message[i].getFrom()[0]
+ "\t" + message[i].getSubject());
}

// Close connection
folder.close(false);
store.close();
}
}

How do you delete a message from the mail server?


Location: http://www.jguru.com/faq/view.jsp?EID=17035
Created: Feb 23, 2000 Modified: 2000-07-25 12:55:22.365
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Benjamin Alejandro Rodriguez Rengifo
(http://www.jguru.com/guru/viewbio.jsp?EID=16246

The basic process of deleting a message is to call setFlag() on the message and set
the Flags.Flag.DELETED flag to true.

message.setFlag(Flags.Flag.DELETED, true);

Then, when you close the folder, deleted messages will be removed.

Be sure to open the folder for read/write access:

folder.open(Folder.READ_WRITE);

The following program demonstrates listing each message in the folder and
prompting for deletion:

import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;

public class DeleteMessageExample {


public static void main (String args[]) throws Exception {
String host = args[0];
String username = args[1];
String password = args[2];

// Get session
Session session = Session.getInstance(
System.getProperties(), null);

// Get the store


Store store = session.getStore("pop3");
store.connect(host, username, password);

// Get folder
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);

BufferedReader reader = new BufferedReader (


new InputStreamReader(System.in));

// Get directory
Message message[] = folder.getMessages();
for (int i=0, n=message.length; i<n; i++) {
System.out.println(i + ": " + message[i].getFrom()[0]
+ "\t" + message[i].getSubject());

System.out.println("Do you want to delete message? [YES to


delete]");
String line = reader.readLine();
// Mark as deleted if appropriate
if ("YES".equals(line)) {
message[i].setFlag(Flags.Flag.DELETED, true);
}
}

// Close connection
folder.close(true);
store.close();
}
}

You can also expunge() the Folder. However, the POP3 server from Sun does not
support this operation.

How can I read a mail message from my mail server?


Location: http://www.jguru.com/faq/view.jsp?EID=17193
Created: Feb 23, 2000 Modified: 2000-08-22 14:15:56.377
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The Message objects include writeTo() method. All you have to do is specify a stream
to write to. The following program demonstrates this:

import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class GetMessageExample {


public static void main (String args[]) throws Exception {
String host = args[0];
String username = args[1];
String password = args[2];

// Create empty properties


Properties props = new Properties();
// Get session
Session session = Session.getInstance(props, null);

// Get the store


Store store = session.getStore("pop3");
store.connect(host, username, password);

// Get folder
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);

BufferedReader reader = new BufferedReader (


new InputStreamReader(System.in));

// Get directory
Message message[] = folder.getMessages();
for (int i=0, n=message.length; i<n; i++) {
System.out.println(i + ": " + message[i].getFrom()[0]
+ "\t" + message[i].getSubject());

System.out.println(
"Do you want to read message? [YES to read/QUIT to end]");
String line = reader.readLine();
// Mark as deleted if appropriate
if ("YES".equals(line)) {
message[i].writeTo(System.out);
} else if ("QUIT".equals(line)) {
break;
}
}

// Close connection
folder.close(false);
store.close();
}
}

For really long messages, you might want to display the output in a TextArea instead
of to System.out.

Comments and alternative answers

For an IMAP provider, use "imap" instead...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Apr 21,
2000
For an IMAP provider, use "imap" instead of "pop3" when you get the session store.

How do I send mail from an applet?


Location: http://www.jguru.com/faq/view.jsp?EID=17409
Created: Feb 23, 2000 Modified: 2000-07-27 09:22:00.606
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

There are many different ways:


• You can speak SMTP directly
• You can use the non-standard sun.net.smtp.SmtpClient class
• You can use the JavaMail API

Keep in mind though that the SMTP server to use must be the same as the web
server. If that is not the case, you would need to create something like a servlet on
the web server that used one of the three options listed.

See also http://java.sun.com/products/javamail/FAQ.html#applets in the Sun


JavaMail FAQ.

How do you send mail using the JavaMail API through a proxy server?
I have connected to the net through a proxy server and I also have a
firewall installed. When I try to execute demo programs given in JavaMail
API, I do not get any errors and everything seems to be ok, but my mail has
not reached the destination.
Location: http://www.jguru.com/faq/view.jsp?EID=21068
Created: Mar 6, 2000 Modified: 2000-12-11 06:31:12.53
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Vinod Tadepalli
(http://www.jguru.com/guru/viewbio.jsp?EID=19366

If you're "proxying" SMTP, what you're really doing is just running an SMTP relay on
the firewall box. You would need to put different rules for incoming versus outgoing
in the firewall.

Keep in mind that (normally) a proxy only forwards HTTP requests. You would need
to setup a socks gateway to connect to the mail server, but it requires a socks server
installed somewhere in your network.

Comments and alternative answers

How can I make URL connections through a proxy server?...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Aug 28,
2000
How can I make URL connections through a proxy server? shows the necessary proxy
settings.

How does JavaMail deal with queuing mail when the initial attempt fails?
Location: http://www.jguru.com/faq/view.jsp?EID=23401
Created: Mar 12, 2000 Modified: 2000-07-25 12:57:28.387
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Mitchell PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=4

It doesn't. A javax.mail.MessagingException will be thrown if there is a failure in


sending the message. It is your responsibility to try to recover. The
MessagingException class maintains a linked list of exceptions that caused the
problem, as there may be more than one. You get each one by following the return
of getNextException().
How can I find out how many messages are waiting to be read on my
IMAP/POP server?
Location: http://www.jguru.com/faq/view.jsp?EID=25270
Created: Mar 16, 2000 Modified: 2000-07-25 12:58:44.354
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The getMessageCount() method of Folder reports this information. The following


program demonstrates.
import javax.mail.*;
import javax.mail.internet.*;

public class GetCountExample {


public static void main (String args[])
throws Exception {
String host = args[0];
String username = args[1];
String password = args[2];

// Get session
Session session = Session.getInstance(
System.getProperties(), null);

// Get the store


Store store = session.getStore("pop3");
store.connect(host, username, password);

// Get folder
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);

// Get Count
int count = folder.getMessageCount();
System.out.println("Messages waiting: "
+ count);
count = folder.getUnreadMessageCount();
System.out.println("Unread messages waiting: "
+ count);

// Close connection
folder.close(false);
store.close();
}
}

Where can I find an NNTP provider for the JavaMail API?


Location: http://www.jguru.com/faq/view.jsp?EID=26204
Created: Mar 20, 2000 Modified: 2004-12-31 04:37:02.756
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Knife (http://bluezoo.org/knife/) is a free mail and user news agent that uses the
JavaMail API and comes with a POP3 and NNTP provider. It is distributed under the
GNU General Public License. A second source for the JAR files is
http://www.vroyer.org/lgpl/.
How does one determine the number of new mail messages in a POP
account?
Location: http://www.jguru.com/faq/view.jsp?EID=26898
Created: Mar 21, 2000 Modified: 2000-07-25 12:59:22.252
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Sriram Gopalan
(http://www.jguru.com/guru/viewbio.jsp?EID=23852

POP servers do not support flags like read or answered. It is only meant for
forwarding messages to an appropriate client store. IMAP is one such protocol that
will report flags where you can find out how many new messages are to be read.
Comments and alternative answers

If the provider supported it, the Folder.getUnread...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Mar 22,
2000
If the provider supported it, the Folder.getUnreadMessageCount() method would
provide the answer.

Retreive the number of new, unread and old messages in pop3


Author: Stan Ozier (http://www.jguru.com/guru/viewbio.jsp?EID=755306), Feb 11,
2002

True, Flags are usually not supported, but most of POP3 servers include a header field
"status" to let you find out if the message is read, unread or new.

The following code is an example that explains and compares the 2 methods.

import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class GetMessageExample {


public static void main (String args[]) throws Exception {
String host = args[0];
String username = args[1];
String password = args[2];

// Create empty properties


Properties props = new Properties();

// Get session
Session session = Session.getDefaultInstance(props, null);

// Get the store


Store store = session.getStore("pop3");

// Connect to store
store.connect(host, username, password);
// Get folder
Folder folder = store.getFolder("INBOX");

// Open read-only
folder.open(Folder.READ_ONLY);

// Get stats
int mCount = folder.getMessageCount();
int mNewCount = folder.getNewMessageCount();
int mUnreadCount = folder.getUnreadMessageCount();

int mNewCount2 = 0;
int mUnreadCount2 = 0;

System.out.println("\nInbox of user "+username+" on POP3 server


"+host+"\n");

for (int i=1; i<=mCount; i++) {

String status = " ";


// display 'N' for new, 'U' for unread, ' ' for read messages

Message message = folder.getMessage(i);


String[] statusHeader = message.getHeader("Status");

if (statusHeader.length > 0) {
// Let's suppose there's only one status header
if (statusHeader[0].equals("")) {
// new message
status = "N";
mNewCount2++;
// mUnreadCount2++; // shall we consider that a new message
is also unread ?
} else if (statusHeader[0].equals("O")) {
// unread message
status = "U";
mUnreadCount2++;
} else if (statusHeader[0].equals("RO")) {
// message read
}
} else {
// no status in header?
// you should check for flags are they may be supported
if (message.isSet(Flags.Flag.RECENT)) {
status = "N";
} else if (!message.isSet(Flags.Flag.SEEN)) {
status = "U";
}
}

System.out.println("\t"+status+" "+i+":
"+message.getSubject());
}
System.out.println("\nFolder contains a total of "+mCount+"
messages");
System.out.println("\nFolder methods return:\t"+mNewCount+"
new,\t"+mUnreadCount+" unread\t");
System.out.println("Message Headers return:\t"+mNewCount2+"
new,\t"+mUnreadCount2+" unread\t\n");

// Close connection
folder.close(false);
store.close();
}
}

Re: Retreive the number of new, unread and old messages in pop3
Author: Vladimir Bilyov (http://www.jguru.com/guru/viewbio.jsp?EID=710818),
May 14, 2004
It works only in several cases (better to say servers). I couldn't find this header in
any pop3 rfc.
More over I have a deal with pop server that doesn't suppport this flag :-(
So it is better to check server that you use.

How do I deal with attachments when reading messages?


Location: http://www.jguru.com/faq/view.jsp?EID=26996
Created: Mar 22, 2000 Modified: 2001-08-19 09:04:23.411
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

When a message includes an attachment, the content of the message will be


Multipart [message.getContent() instanceof Multipart] instead of Part. You'll
need to get each part of the Multipart and process it [for (int i=0,
n=multipart.getCount(); i<n; i++) process(multipart.getBodyPart(i))]
based upon its disposition [part.getDisposition()] and content type
[part.getContentType()].

The following program demonstrates this capability, leaving out the exception
handling:

import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class GetParts {


public static void main (String args[])
throws Exception {
String host = args[0];
String username = args[1];
String password = args[2];

// Get session
Session session = Session.getInstance(
new Properties(), null);

// Get the store


Store store = session.getStore("pop3");
store.connect(host, username, password);

// Get folder
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);

BufferedReader reader = new BufferedReader (


new InputStreamReader(System.in));

// Get directory
Message message[] = folder.getMessages();
for (int i=0, n=message.length; i<n; i++) {
System.out.println(i + ": "
+ message[i].getFrom()[0]
+ "\t" + message[i].getSubject());

System.out.println(
"Do you want to get the content?
[YES to read/QUIT to end]");
String line = reader.readLine();
if ("YES".equals(line)) {
Object content = message[i].getContent();
if (content instanceof Multipart) {
handleMultipart((Multipart)content);
} else {
handlePart(message[i]);
}
} else if ("QUIT".equals(line)) {
break;
}
}

// Close connection
folder.close(false);
store.close();
}
public static void handleMultipart(Multipart multipart)
throws MessagingException, IOException {
for (int i=0, n=multipart.getCount(); i<n; i++) {
handlePart(multipart.getBodyPart(i));
}
}
public static void handlePart(Part part)
throws MessagingException, IOException {
String disposition = part.getDisposition();
String contentType = part.getContentType();
if (disposition == null) { // When just body
System.out.println("Null: " + contentType);
// Check if plain
if ((contentType.length() >= 10) &&
(contentType.toLowerCase().substring(
0, 10).equals("text/plain"))) {
part.writeTo(System.out);
} else { // Don't think this will happen
System.out.println("Other body: " + contentType);
part.writeTo(System.out);
}
} else if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
System.out.println("Attachment: " + part.getFileName() +
" : " + contentType);
saveFile(part.getFileName(), part.getInputStream());
} else if (disposition.equalsIgnoreCase(Part.INLINE)) {
System.out.println("Inline: " +
part.getFileName() +
" : " + contentType);
saveFile(part.getFileName(), part.getInputStream());
} else { // Should never happen
System.out.println("Other: " + disposition);
}
}
public static void saveFile(String filename,
InputStream input) throws IOException {
if (filename == null) {
filename = File.createTempFile("xx", ".out").getName();
}
// Do no overwrite existing file
File file = new File(filename);
for (int i=0; file.exists(); i++) {
file = new File(filename+i);
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);

BufferedInputStream bis = new BufferedInputStream(input);


int aByte;
while ((aByte = bis.read()) != -1) {
bos.write(aByte);
}
bos.flush();
bos.close();
bis.close();
}
}
Comments and alternative answers

Decode the name of the attachments... Lotus Notes Release 5.X only!
Author: Andriano Franck (http://www.jguru.com/guru/viewbio.jsp?EID=703045),
Dec 13, 2002
With Lotus Notes Release 5.X ("Cacahuète jaune... in french!") you need to decode
the name of the attachment... use MimeUtility.decodeText!

if ((disposition != null) && ( disposition.equals(Part.ATTACHMENT) ||


disposition.equals(Part.INLINE) ) )
{
String filename = MimeUtility.decodeText(part.getFileName()); // for
Lotus Notes only!
String path_filename = saveFile(filename, part.getInputStream());
}

Best regards,
/Franck

handleMultipart should be recursive


Author: henry hess (http://www.jguru.com/guru/viewbio.jsp?EID=1231029), Mar 6,
2005
i'm a beginner in working with the javamail api so please correct me if i'm wrong but i
think a method that handles multipart content has to be recursive due to the fact that
the single parts of the multipart mail can also be multiparts. especially mail clients
like outlook often produce these kind of nested e-mails when sending html with
picture files included.

How do I encrypt the body text of an email? Can I use PGP in conjunction
with JavaMail?
Location: http://www.jguru.com/faq/view.jsp?EID=29831
Created: Mar 29, 2000 Modified: 2000-04-24 19:51:06.138
Author: Shiva Kumar (http://www.jguru.com/guru/viewbio.jsp?EID=29825) Question
originally posed by Gary Moh (http://www.jguru.com/guru/viewbio.jsp?EID=23320

If you are an US/Canadian you can use the JCE (Java Cryptographic Extension),
available from Sun (http://java.sun.com/products/jce/). Remember that after
encryption, you will get binary output, so don't forget to base64 encode, otherwise
X.25 mailing systems may corrupt the mailed data.
Comments and alternative answers

You can also get an S/MIME implementation that deals...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Apr 19,
2000
You can also get an S/MIME implementation that deals with signing and encryption.
See another FAQ entry for a few pointers.

How do I send email with attachments using the JavaMail API?


Location: http://www.jguru.com/faq/view.jsp?EID=30251
Created: Mar 30, 2000 Modified: 2000-10-20 06:21:26.37
Author: Sateesh Rudrangi (http://www.jguru.com/guru/viewbio.jsp?EID=2996)
Question originally posed by subba pathipati
(http://www.jguru.com/guru/viewbio.jsp?EID=29238

Here is the code to send an attachment:

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class AttachExample {
public static void main (String args[])
throws Exception {
String host = args[0];
String from = args[1];
String to = args[2];
String fileAttachment = args[3];

// Get system properties


Properties props = System.getProperties();

// Setup mail server


props.put("mail.smtp.host", host);

// Get session
Session session =
Session.getInstance(props, null);

// Define message
MimeMessage message =
new MimeMessage(session);
message.setFrom(
new InternetAddress(from));
message.addRecipient(
Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject(
"Hello JavaMail Attachment");

// create the message part


MimeBodyPart messageBodyPart =
new MimeBodyPart();

//fill message
messageBodyPart.setText("Hi");

Multipart multipart = new MimeMultipart();


multipart.addBodyPart(messageBodyPart);

// Part two is attachment


messageBodyPart = new MimeBodyPart();
DataSource source =
new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(
new DataHandler(source));
messageBodyPart.setFileName(fileAttachment);
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(multipart);

// Send the message


Transport.send( message );
}
}

How can I send an attachment using sun.net.smtp.SmtpClient?


Location: http://www.jguru.com/faq/view.jsp?EID=36079
Created: Apr 13, 2000 Modified: 2000-07-25 13:03:06.548
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Vinay Ghule
(http://www.jguru.com/guru/viewbio.jsp?EID=11951

From the looks of the public API:

public class sun.net.smtp.SmtpClient


extends sun.net.TransferProtocolClient {
public void closeServer()
throws IOException;
public void to(String)
throws IOException;
public void from(String)
throws IOException;
public PrintStream startMessage()
throws IOException;
public sun.net.smtp.SmtpClient(String)
throws IOException;
public sun.net.smtp.SmtpClient()
throws IOException;
public String getMailHost();
}
It appears to only support sending simple messages, not attachments. You'll need to
use the JavaMail capabilities instead.

How secure is JavaMail?


Location: http://www.jguru.com/faq/view.jsp?EID=38021
Created: Apr 19, 2000 Modified: 2000-04-19 20:55:04.721
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Mitchell PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=4

If you are worried about security with your mail, you would need to get an S/MIME
provider to work with JavaMail. This would include support for email signing and
encryption. The Phaos S/MIME toolkit and JCSI are two implementations you can
look into.
Comments and alternative answers
One more thing to worry about
Author: Eugene Kuleshov (http://www.jguru.com/guru/viewbio.jsp?EID=442441),
Nov 19, 2001
S/MIME gives secure or trusted message content but if you have a real paranoya and
don't want to have even a little chance that your messages will be intercepted you
should use secure transport.

So. You have to add TLS/SSL to all your JavaMail connections (smtp, pop3, imap,
nntp, etc.). More details is here.

How do I include a text name with the from header, besides just an email
address?
Location: http://www.jguru.com/faq/view.jsp?EID=38450
Created: Apr 20, 2000 Modified: 2000-07-25 13:12:22.844
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The message.setFrom(new InternetAddress(from)); line is suffcient to


include a name with the line, where from would be a string like "\"Bill Clinton\"
<president@whitehouse.gov>". You can also use the constructor public
InternetAddress(java.lang.String address, java.lang.String
personal) that allows you to pass the address and personal information
separately. Or, you can even call the setPersonal() method to directly set the
information on an existing InternetAddress.

Can I get a trace of the actual SMTP commands sent to the mail server?
Location: http://www.jguru.com/faq/view.jsp?EID=38705
Created: Apr 21, 2000 Modified: 2000-04-21 07:52:05.1
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Yes. For your mail session, set the debug property to true:
session.setDebug(true).

How can I add/delete mail user accounts with JavaMail?


Location: http://www.jguru.com/faq/view.jsp?EID=38708
Created: Apr 21, 2000 Modified: 2000-08-25 16:05:57.24
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

There is no support for this built into the API.

According to Sun's JavaMail FAQ:

The JavaMail API does not include any facilities for adding, removing, or changing
user accounts. There are no standards in this area; every mail server handles this
differently.

How can I reply to a message?


Location: http://www.jguru.com/faq/view.jsp?EID=38717
Created: Apr 21, 2000 Modified: 2000-07-25 13:14:09.835
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Calling the reply() method of the Message class will create a properly created
header for your reply. If you wish to include the content of the original message,
you'll have to include it yourself.

How do I efficiently send a bulk mailing, where I want to send mail out to
lots of recipients, not all on the same TO/CC/BCC line?
Location: http://www.jguru.com/faq/view.jsp?EID=38720
Created: Apr 21, 2000 Modified: 2000-10-12 19:02:32.099
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Get the necessary Transport object and call sendMessage() on it for each message.
Be sure to set/change recipients between calls.

Message message = ...;


Transport t = session.getTransport("smtp");
t.connect();

message.setRecipient(
Message.RecipientType.TO, recipient1);
t.sendMessage(message, recipient1Array);
message.setRecipient(
Message.RecipientType.TO, recipient2);
t.sendMessage(message, recipient2Array);
message.setRecipient(
Message.RecipientType.TO, recipient3);
t.sendMessage(message, recipient3Array);

t.close();
Comments and alternative answers

This does not strike me as particularly efficient....


Author: Peter Snow (http://www.jguru.com/guru/viewbio.jsp?EID=215260), Oct 12,
2000
This does not strike me as particularly efficient. The same message is sent over and
over again to the mail server. A better way to do it would be simply to set up an array
of Address objects and then send them in one call using sendMessage. For example:
Transport transport = session.getTransport(addressObjects[0]);
transport.connect();
transport.sendMessage(message,addressObjects);

The mail server will then take the one copy of the message and send it to multiple
addresses. It doesn't need to receive thousands of copies of the same message.
Optionally, you could specify an address to appear in the "TO:" header:
message.setRecipient(Message.RecipientType.TO,
addressObjects[0]);

setRecipient() only specifies what appears in the "TO:" header in the email, it doesn't
have to match the address in the Address objects.

FAQ Manager Note: The problem with including all of them in the TO field though is
all the addresses are visible. If you must show the specific TO address or include a
specific footer for each user for unsubscribing, you're stuck with sending separate
messages.

How do I use BCC to hide recipient addresses?


Location: http://www.jguru.com/faq/view.jsp?EID=38725
Created: Apr 21, 2000 Modified: 2000-07-25 13:16:02.296
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

When you add a recipient InternetAddress, use Message.RecipientType.BCC:

String addressString =
"bill@microsoft.com";
InternetAddress bcc =
new InternetAddress(addressString);
message.addRecipient(
Message.RecipientType.BCC, bcc);
Comments and alternative answers

Another way
Author: Chris Chen (http://www.jguru.com/guru/viewbio.jsp?EID=454197), Jul 12,
2001
message.addHeader("bcc","bill@microsoft.com"); will let you bcc also.

How do you find out the text character set in the message body?
Location: http://www.jguru.com/faq/view.jsp?EID=39071
Created: Apr 22, 2000 Modified: 2000-07-25 14:02:00.758
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by ronen portnoy
(http://www.jguru.com/guru/viewbio.jsp?EID=27420

You should find this in the ContentType of the part. If you're lucky, it will be present
as something like "text/plain; charset=foobar". However, I don't believe this is
required.
What are the distribution limitations of Sun's reference implementation?
Location: http://www.jguru.com/faq/view.jsp?EID=40126
Created: Apr 25, 2000 Modified: 2000-04-25 10:11:10.436
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

According to the license that comes with the distribution, you are free to redistribute
the unmodified JAR files.

Are there any other FAQs for JavaMail?


Location: http://www.jguru.com/faq/view.jsp?EID=40659
Created: Apr 26, 2000 Modified: 2000-07-25 14:54:12.776
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Sun maintains a FAQ on JavaMail at


http://java.sun.com/products/javamail/FAQ.html.

How can I incorporate mail facilities into JSP pages?


Location: http://www.jguru.com/faq/view.jsp?EID=42156
Created: Apr 28, 2000 Modified: 2000-04-28 20:22:58.827
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Gunjan Vaishnav
(http://www.jguru.com/guru/viewbio.jsp?EID=34698

Why, by using the JavaMail API of course... Your best bet is to create some
JavaBeans that do all the work and access the beans from the JSP pages. You'll need
to include the appropriate mail classes in the CLASSPATH of your server. If you don't
want to create the beans yourself, you can always buy them. ImMailBean is one such
product.
Comments and alternative answers

Or you could check out the JavaMail tag library at...


Author: Kellan Elliott-McCrea (http://www.jguru.com/guru/viewbio.jsp?EID=40670),
Apr 30, 2000
Or you could check out the JavaMail tag library at Source Forge

How do I send an HTML content message through the JavaMail API?


Location: http://www.jguru.com/faq/view.jsp?EID=43236
Created: May 2, 2000 Modified: 2000-08-23 06:54:32.26
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Salman Ahmed
(http://www.jguru.com/guru/viewbio.jsp?EID=41787

First create a String object containg the HTML text for the message. Then use
setContent() to set the message content to a specific content-type. For example :
String msgText = getHtmlMessageText(...);
msg.setContent(msgText, "text/html");
Comments and alternative answers

HTML
Author: Rahul Parmar (http://www.jguru.com/guru/viewbio.jsp?EID=1147635), Feb
19, 2004
In case you are creating an email with a MultiPart Message, you should do something
like this:

Multipart mp = new MimeMultipart();

MimeBodyPart mbp1 = new MimeBodyPart();


mbp1.setContent(body, "text/html");
mp.addBodyPart(mbp1);

..add other file attachments to Multipart...

A lot of code has been written that uses MimeBodyPart.setText(String body) for the
message. That will not work as it uses "text/plain" and doesn't support "text/html"
encoding.

Where do I place the JAR files so that I can use JavaMail from JSP?
Location: http://www.jguru.com/faq/view.jsp?EID=45978
Created: May 8, 2000 Modified: 2000-05-08 10:08:08.318
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Using the JavaMail API from JSP pages requires the JavaMail and JavaBeans
Activation Framework JAR files (mail.jar and activation.jar respectively) to be in the
CLASSPATH for the Java runtime of your JSP-enabled web server. While most servers
allow you to configure their CLASSPATH, either through mucking with batch files or
through some configuration program, the easiest way to configure the server is to
take advantage of the standard Java Extensions Mechanism. Just copy the JAR files
into the ext under your Java runtime directory. For instance, Windows users of Java
1.2.2 who installed to the default location would copy the JAR files to
C:\JDK1.2.2\JRE\LIB\EXT.
Comments and alternative answers

If you are deploying your application as a "j2ee...


Author: Simon Brown (http://www.jguru.com/guru/viewbio.jsp?EID=44588), May
10, 2000
If you are deploying your application as a "j2ee web application", an alternative (and
more portable) solution is to place the relevant JAR files in a "lib" directory
underneath the "web-inf" directory.

This way, you can easily distribute the web application and its dependencies as one
unit (i.e. the WAR file).

How can I use an Authenticator to prompt for username and password when
reading mail from a IMAP/POP server?
Location: http://www.jguru.com/faq/view.jsp?EID=46850
Created: May 9, 2000 Modified: 2000-07-25 14:06:22.939
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

Keep in mind that the Authenticator in JavaMail is different than the one in the
java.net package. To use the javax.mail.Authenticator, the basic process to connect
to the Store is as follows:

// Create empty properties


Properties props = new Properties();
props.put("mail.host", host);

// Setup authentication, get session


Authenticator auth = new PopupAuthenticator();
Session session = Session.getInstance(
props, auth);

// Get the store


Store store = session.getStore("pop3");
store.connect();
Then, you would need to create a PopupAuthenticator class that extends
Authenticator. In the public PasswordAuthentication
getPasswordAuthentication() method, the class would pop a frame up
prompting for username and password, returning the information in a
PasswordAuthentication object.

How do I set up a default mime type for unknown file types using
MimetypesFileTypeMap? At present when sending a message with an
attached file of unknown file type a NullPointerException is thrown.
Location: http://www.jguru.com/faq/view.jsp?EID=47665
Created: May 11, 2000 Modified: 2001-07-24 10:37:07.552
Author: Rajesh Ajmera (http://www.jguru.com/guru/viewbio.jsp?EID=47656)
Question originally posed by Chris Webb
(http://www.jguru.com/guru/viewbio.jsp?EID=2096

Just create a new map and ask:

MimetypesFileTypeMap mmp = new MimetypesFileTypeMap();


System.out.println(mmp.getContentType("d:\\rajesh\\abc.jpg"
));

How do I store messages locally using JavaMail?


Location: http://www.jguru.com/faq/view.jsp?EID=47747
Created: May 11, 2000 Modified: 2000-05-11 08:41:31.696
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Anand Naik
(http://www.jguru.com/guru/viewbio.jsp?EID=44857

The JavaMail API provides the core interfaces for working with many different types
of providers. Sun provides implementations of SMTP and IMAP with the JavaMail
implementation and freely offers a POP3 provider separately. In order to use the
JavaMail API to provide a local data store for your messages involves just getting
another provider. One such provider of a mailbox file is Knife which is distributed
under the GNU Lesser General Public Licence. For a list of additional providers see
Sun's list at http://java.sun.com/products/javamail/Third_Party.html.
Comments and alternative answers

This can be achieved using the writeTo() method of...


Author: Rajesh Ajmera (http://www.jguru.com/guru/viewbio.jsp?EID=47656), May
11, 2000
This can be achieved using the writeTo() method of MimeMessage class.
Yes, you have to use object of MimeMessage instead of using object of Message
class.
The following code can be helpful :

FileOutputStream fos = new FileOutputStream("test.mail");


mimemessage.writeTo(fos);

How do I encode the string that I want to send so that the message is mail
safe?
Location: http://www.jguru.com/faq/view.jsp?EID=47805
Created: May 11, 2000 Modified: 2000-07-25 14:07:02.652
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Chinnappa Codanda
(http://www.jguru.com/guru/viewbio.jsp?EID=47761

When you call setText(message) on the MimePart/MimeMessage this will encode


the string for you using the platform's default character set. If you know the
character set, you can call setText(message, charset), which will be faster
for larger messages.
Comments and alternative answers

I did put the setText(...) in but it still did not...


Author: Chinnappa Codanda (http://www.jguru.com/guru/viewbio.jsp?EID=47761),
May 11, 2000
I did put the setText(...) in but it still did not work. Apparently if in the message the
lines are too long the SMTP server seems to think it is encoded as "quoted-printable'
and converts the message to 8bit. When I restricted the maximum length of a line to
72 everything worked fine.

Where can I get the source code for the JavaMail classes?
Location: http://www.jguru.com/faq/view.jsp?EID=48755
Created: May 13, 2000 Modified: 2000-05-13 11:29:09.911
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
The source for Sun's reference implementation of the JavaMail API is available as
part of the J2EE 1.2 Sun Community Source Licensing release, available from
http://www.sun.com/software/communitysource/j2ee/index.html.

If my mail server requires authentication to send messages, how do I set


my username/password through the JavaMail API so I don't get a
'javax.mail.SendFailedException: 550 Relaying is prohibited' error?
Location: http://www.jguru.com/faq/view.jsp?EID=48895
Created: May 14, 2000 Modified: 2001-07-25 08:44:44.659
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Bram Stieperaere
(http://www.jguru.com/guru/viewbio.jsp?EID=48026

When you connect to the Transport you can pass a username and password:

Transport transport =
session.getTransport("smtp");
transport.connect(
host, username, password);

Unfortunately, this doesn't use the Authenticator class in javax.mail, so you would
have to build in your own mechanism to prompt the user for this information.

You may also need to set the mail.smtp.auth property to true:

props.put("mail.smtp.auth", "true");

How do you get the file attachment size? I tried using


multipart.getBodyPart(i).getSize(), but this returns -1.
Location: http://www.jguru.com/faq/view.jsp?EID=53410
Created: May 21, 2000 Modified: 2000-07-25 14:18:28.298
Author: Andrea Pompili (http://www.jguru.com/guru/viewbio.jsp?EID=51802)
Question originally posed by Sunil San
(http://www.jguru.com/guru/viewbio.jsp?EID=42975

In this situation you can do this:


size = multipart.getBodyPart(i).
getInputStream().available();
[Manager Note: This works perfectly for text (7-bit) attachments. In the case of
binary attachments, they will be encoded so the stream size will be slightly larger.]
Comments and alternative answers

The encoded form of the file is expanded by 37% for...


Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708),
Nov 5, 2000
The encoded form of the file is expanded by 37% for UU encoding and by 35% for
base64 encoding (3 bytes become 4 plus control information).
size=bodyPart.getInputStream().available()*0.65;

should therefore be pretty close to the real size.

How do I check if an email address string is valid, like


username@domain.net, both for a valid/working domain name and for
address within domain?
Location: http://www.jguru.com/faq/view.jsp?EID=54630
Created: May 23, 2000 Modified: 2000-05-23 12:38:19.57
Author: Tripp Lilley (http://www.jguru.com/guru/viewbio.jsp?EID=1743) Question
originally posed by Jim Garrett
(http://www.jguru.com/guru/viewbio.jsp?EID=53862

Use the javax.mail.internet.InternetAddress class from the JavaMail API.

Note that there is no way to verify that an address actually exists and is a working
"inbox" short of sending a message to it and waiting to receive a "bounce" message
indicating some kind of delivery failure. The best you can hope to do is validate that
the form of the address conforms to governing standards.

The governing standard, in this case, is the IETF's RFC 822 - STANDARD FOR THE
FORMAT OF ARPA INTERNET TEXT MESSAGES.

Comments and alternative answers

You can also try to verify the MX (mail exchange) ...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Sep 20,
2000
You can also try to verify the MX (mail exchange) record yourself with classes like
MX Lookup Client Version from AXL.

You can also verify the MX record for free using the...
Author: Patrick Gibson (http://www.jguru.com/guru/viewbio.jsp?EID=301077), Jan
12, 2001
You can also verify the MX record for free using the dnsjava package.

Complete e-mail verification tool


Author: Brien Voorhees (http://www.jguru.com/guru/viewbio.jsp?EID=328000), May
11, 2001
You might want to check out JVerify at http://www.jscape.com/jverify.html . It claims
to do complete verification including address syntax, mx-lookup, and connecting to
the server to see if the address is accepted.

How can I use SearchTerm to match specific messages with POP/IMAP


servers?
Location: http://www.jguru.com/faq/view.jsp?EID=56461
Created: May 25, 2000 Modified: 2000-07-25 14:20:07.358
Author: Andrea Pompili (http://www.jguru.com/guru/viewbio.jsp?EID=51802)
Question originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

You have to build a condition tree using the single SearchTerm blocks given in the JM
API (package javax.mail.search.*).
The SearchTerm blocks are of this type:

• AND terms (class AndTerm)


• OR terms (class OrTerm)
• NOT terms (class NotTerm)
• SENT DATE terms (class SentDateTerm)
• CONTENT terms (class BodyTerm)
• HEADER terms (From, Recipients, Subjects, etc..) (classes FromStringTerm,
RecipientStringTerm, SubjectTerm)

Once you have built the searching term using these blocks, you have to use this
method:
foldername.search(search term);
For example, to search in the INBOX folder all messages with body and subject
containing the word "hello" you have to write that:
//Initialize the folder and the search term
Folder folder = store.getFolder("INBOX");
SearchTerm st = new AndTerm(
new SubjectTerm("hello"),
new BodyTerm("hello");

Message[] msgs = folder.search(st);


Now you have an array of messages that match your request.
This code doesn't depend on the protocol used and is the same in POP3, IMAP, or
other existing protocol.

If you want you can write your own search term extending one of these classes and
writing inside your own searching logic.

I have written a DataHandler for multipart/signed messages. However, I


am unable to obtain the value of micalg field from the Content-Type header
of a Message. How do I get the value of micalg?
Location: http://www.jguru.com/faq/view.jsp?EID=59042
Created: May 29, 2000 Modified: 2000-07-25 14:23:31.911
Author: Andrea Pompili (http://www.jguru.com/guru/viewbio.jsp?EID=51802)
Question originally posed by Godson Menezes
(http://www.jguru.com/guru/viewbio.jsp?EID=57114

You have to extract directly the Content Type Header from the Message and extract it
manually (or using the ContentType class):

Example (it's only an example, I don't include error chekings or other):


Message msg = ... (code for generating it);
//Other code...

MimeMessage mimeMsg = (MimeMessage)msg;


String[] all = mimeMsg.getHeader("Content-Type");
String ctype = "";

for (int i = 0; i < all.length; i++)


ctype += all[i] + " ";

int idx1 = ctype.indexOf("micalg=");


int idx2 = ctype.indexOf(";", idx1);
String micalg = ctype.substring(idx1, idx2);
Otherwise you could use the JavaMail API:
//As the above example...

MimeMessage mimeMsg = (MimeMessage)msg;


String ctype = mimeMsg.getHeader("Content-Type", " ");
ContentType ct = new ContentType(ctype);
String micalg = ct.getParameter("micalg");
Comments and alternative answers

dont use stringin the loop...


Author: ftp gogo (http://www.jguru.com/guru/viewbio.jsp?EID=448128), Jul 1, 2001
use string buffer instead

Use the API Luke


Author: Paul Mitchell-Gears
(http://www.jguru.com/guru/viewbio.jsp?EID=1223501), Jan 27, 2005
public String getMicalg(MimeMessage aMessage) {
return new
ContentType(aMesssage.getContentType()).getParameter("micalg");
}

How can I use the ESMTP (RFC 1869) protocol with JavaMail?
Location: http://www.jguru.com/faq/view.jsp?EID=65108
Created: Jun 5, 2000 Modified: 2000-06-05 07:34:07.251
Author: Andrea Pompili (http://www.jguru.com/guru/viewbio.jsp?EID=51802)
Question originally posed by Alireza Banaei
(http://www.jguru.com/guru/viewbio.jsp?EID=56441

If you look the draft of the JavaMail Specification 1.2 at


http://java.sun.com/products/javamail/index.html you can see that it supports
ESMTP 8BITMIME extension.

So I think the future release of JavaMail 1.2 will support this protocol.

Here is a section of the draft:


"If the property "mail.smtp.allow8bitmime" is set to "true", and the SMTP server
supports the 8BITMIME extension, the SMTP Transport will traverse the message and
adjust the Content-Transfer-Encoding of text body parts from "quoted-printable" or
"base64" to "8bit" as appropriate."
Comments and alternative answers

Is there a way to restrict the protocol between javamail and the smtp server to
use only SMTP, and not use e-SMTP?
Author: Sean Kang (http://www.jguru.com/guru/viewbio.jsp?EID=1197159), Sep 3,
2004
Is there a way to restrict the protocol between javamail and the smtp server to use
only SMTP, and not use e-SMTP? I use this javax.mail.* package and connect to an
exchange smtp, which supports ESMTP. However, there is a firewall component
which blocks ESMTP protocol. The regular SMTP stuff seems to get through. Any
way to retrict the protocol to use only SMTP?

Is there a way to restrict the protocol between javamail and the smtp server to
use only SMTP, and not use e-SMTP?
Author: Sean Kang (http://www.jguru.com/guru/viewbio.jsp?EID=1197159), Sep 3,
2004
Is there a way to restrict the protocol between javamail and the smtp server to use
only SMTP, and not use e-SMTP? I use this javax.mail.* package and connect to an
exchange smtp, which supports ESMTP. However, there is a firewall component
which blocks ESMTP protocol. The regular SMTP stuff seems to get through. Any
way to retrict the protocol to use only SMTP?

restrict to only SMTP


Author: Sean Kang (http://www.jguru.com/guru/viewbio.jsp?EID=1197159), Sep 3,
2004
Is there a way to restrict the protocol between javamail and the smtp server to use
only SMTP, and not use e-SMTP? I use this javax.mail.* package and connect to an
exchange smtp, which supports ESMTP. However, there is a firewall component
which blocks ESMTP protocol. The regular SMTP stuff seems to get through. Any
way to retrict the protocol to use only SMTP?

restrict to only SMTP


Author: Sean Kang (http://www.jguru.com/guru/viewbio.jsp?EID=1197159), Sep 3,
2004
Is there a way to restrict the protocol between javamail and the smtp server to use
only SMTP, and not use ESMTP?

I use this javax.mail.* package and connect to an exchange smtp, which supports
ESMTP. However, there is a firewall component which blocks ESMTP protocol. The
regular SMTP stuff seems to get through.

Any way to retrict the protocol to use only SMTP?

restrict SMTP
Author: Sean Kang (http://www.jguru.com/guru/viewbio.jsp?EID=1197159), Sep 3,
2004
Is there a way to restrict the protocol between javamail and the smtp server to use
only SMTP, and not use ESMTP?

I use this javax.mail.* package and connect to an exchange smtp, which supports
ESMTP. However, there is a firewall component which blocks ESMTP protocol. The
regular SMTP stuff seems to get through.

Any way to retrict the protocol to use only SMTP?

How can I send an e-mail outside of the US-ASCII character set? Using
MimeUtility.encodeText() leaves the character set in the subject when
looking at the message (in MS Outlook).
Location: http://www.jguru.com/faq/view.jsp?EID=74374
Created: Jun 13, 2000 Modified: 2000-07-25 14:24:42.459
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Lena Braginsky
(http://www.jguru.com/guru/viewbio.jsp?EID=25428

For the subject, use:


MimeMessage.setSubject(String subj, String charset)

How do you use the JNDI ENC to access JavaMail?


Location: http://www.jguru.com/faq/view.jsp?EID=75066
Created: Jun 14, 2000 Modified: 2000-06-14 07:30:41.03
Author: Steven Lau (http://www.jguru.com/guru/viewbio.jsp?EID=72026) Question
originally posed by Se Hee Lee
(http://www.jguru.com/guru/viewbio.jsp?EID=21287

First of all, you have to create a javax.mail.Session like you would in accessing other
resources such as JDBC connections:

InitialContext ctx = new InitialContext();


Session session =
(Session) ctx.lookup("java:comp/env/TheMailSession");
After that, everything else is the same:

Message msg = new MimeMessage(session);


...
...
Depending on the application server you're using, you'll have different ways in
setting up the ENC.

How do I pick up the attachment from the client's machine, in a web-based


email system?
Location: http://www.jguru.com/faq/view.jsp?EID=81033
Created: Jun 20, 2000 Modified: 2001-07-23 10:50:29.979
Author: Andrea Pompili (http://www.jguru.com/guru/viewbio.jsp?EID=51802)
Question originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

You can do it using an HTML form, a Servlet and the class MultipartRequest of the
O'Reilly package avaiable at http://www.servlets.com/resources/com.oreilly.servlet/.
In this zip file (named cos.zip) you can found all the information you need to upload
a file using a browser and a servlet.
Remember that the file you upload is stored in the server filesystem, so remember to
remove it after sending your E-mail.

I tried also another way that worked perfectly, but is more complicated.
I wrote three classes :

• A mine DataSource for handling a stream of byte with a filename and a


content type
• An ExtendedMultipartRequest class that extracts the parts from the stream
of the Servlet (similar to the one provided by O'Reilly)
• A MultipartInputStream for reading the InputStream of the servlet line by
line

For creating a message I passed each data (bytes), content-type, and filename
parsed by my ExtendedMultipartRequest class to my DataSource. Then I built a
DataHandler using this DS and a Message using this as Content... It worked
perfectly!!!
Comments and alternative answers

See also
Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Jul 23, 2001
See also How do I upload a file to my servlet? and the topic Servlets:Files:Uploading

How can I detect when my SMTP server is down? Can it be done by setting a
timeout on the Transport.send() call?
Location: http://www.jguru.com/faq/view.jsp?EID=80979
Created: Jun 20, 2000 Modified: 2000-07-25 14:25:40.861
Author: Andrea Pompili (http://www.jguru.com/guru/viewbio.jsp?EID=51802)
Question originally posed by werner mueller
(http://www.jguru.com/guru/viewbio.jsp?EID=66596

You can do it in three ways:

1. Setting the Timeout in the property file you use to initialize the session.
mail.smtp.timeout = <timeout>

This works only for the SUN provider, if you use something else you have to
see the documentation of that thirdy-part provider.
2. Using the method Transport.connect()
In this case, if the server is down you obtain a MessagingException explaining
that. Look also at the Transport.protocolConnect(...) method that does
the same thing.
All the methods are inherited by Service class.
3. Trying to enstablish a connection to the address/port of your SMTP Server and
waiting for response. No answer means it's down...

How can I rename a folder without creating a new one and moving the
messages?
Location: http://www.jguru.com/faq/view.jsp?EID=82138
Created: Jun 21, 2000 Modified: 2000-07-25 14:26:09.378
Author: Andrea Pompili (http://www.jguru.com/guru/viewbio.jsp?EID=51802)
Question originally posed by Jordi Domingo Borras
(http://www.jguru.com/guru/viewbio.jsp?EID=51078

If you're using 1.1.3 version of JavaMail you can use this method of the Folder
class:
boolean renameTo(Folder f) throws MessagingException
You have to create a new Folder object with the desired new name and then apply
this method to the Folder you want to rename.
If something goes wrong (wrong name, not existing folder, already existing folder...)
it returns FALSE.

You must take care of two things:

• The folder you want to rename must be closed.


• This works only for IMAP protocol (or others similar), if you call this method in
a POP3 environment you obtain a MethodNotSupportedException.

How / when does one use a TransportListener?


Location: http://www.jguru.com/faq/view.jsp?EID=95355
Created: Jul 4, 2000 Modified: 2002-03-30 19:39:29.027
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Han Feng (http://www.jguru.com/guru/viewbio.jsp?EID=82674

You can add a TransportListener to a specific instance of the Transport you are using.
In other words, you have to get a specific Transport, like with Transport
transport = session.getTransport("smtp") to get the Transport. You
can't just use the send() method to send the message. Once you have a Transport,
add a listener with addTransportListener(). It will then be notified of
successful or unsuccessful sending of the message. A partially successful send is if
some of the recipients are not valid, but at least one is valid.

Also, be sure not to use Transport.send().

How do you send HTML mail with images?


Location: http://www.jguru.com/faq/view.jsp?EID=97371
Created: Jul 6, 2000 Modified: 2003-04-12 08:08:16.864
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Geoff Han (http://www.jguru.com/guru/viewbio.jsp?EID=97195
The basic process of sending an HTML message is described in
http://www.jguru.com/jguru/faq/view.jsp?EID=43236. Basically, you need to set the
content type for the HTML part.

As far as the images go... you are actually better off leaving them on your server and
letting the user's mail tool take care of pulling them across when viewing the HTML
file. While yes you can include the images as attachments with the HTML body, what
the mail tool does with them you have no control over. For instance, if all attachment
files are saved to the same directory (like Eudora) then you must name the image
files uniquely in order for the mail tool to be sure to display YOUR images and not
some other image that the user received from you or someone else.

Remember to make your image URLs absolute, not relative, too. As relative ones will
not resolve properly from the mail client.

If you really want to send them along with the message... You'll need to create a
"multipart/related" message. One of the parts will be the HTML part which refers to
the other parts which are the image parts. An RFC that contains information about
multipart/related messages is available at http://www.faqs.org/rfcs/rfc2387.html.

To reference the other parts, the URL will have to specify the content id / message
id, like cid:, instead of http:. This is described in RFC 2111.

The following example was posted to the JavaMail mailing list from lys to
demonstrate using the cid:

import java.io.*;
import java.util.Properties;
import java.util.Date;
import javax.mail.*;
import javax.activation.*;
import javax.mail.internet.*;

public class sendhtml {

public static void main(String[] argv) {


new sendhtml(argv);
}

public sendhtml(String[] argv) {

String to, subject = null, from = null,


cc = null, bcc = null, url = null;
String mailhost = null;
String mailer = "sendhtml";
String protocol = null, host = null, user = null, password = null;
String record = null; // name of folder in which to record mail
boolean debug = false;
BufferedReader in =
new BufferedReader(new InputStreamReader(System.in));
int optind;

for (optind = 0; optind < argv.length; optind++) {


if (argv[optind].equals("-T")) {
protocol = argv[++optind];
} else if (argv[optind].equals("-H")) {
host = argv[++optind];
} else if (argv[optind].equals("-U")) {
user = argv[++optind];
} else if (argv[optind].equals("-P")) {
password = argv[++optind];
} else if (argv[optind].equals("-M")) {
mailhost = argv[++optind];
} else if (argv[optind].equals("-f")) {
record = argv[++optind];
} else if (argv[optind].equals("-s")) {
subject = argv[++optind];
} else if (argv[optind].equals("-o")) { // originator
from = argv[++optind];
} else if (argv[optind].equals("-c")) {
cc = argv[++optind];
} else if (argv[optind].equals("-b")) {
bcc = argv[++optind];
} else if (argv[optind].equals("-L")) {
url = argv[++optind];
} else if (argv[optind].equals("-d")) {
debug = true;
} else if (argv[optind].equals("--")) {
optind++;
break;
} else if (argv[optind].startsWith("-")) {
System.out.println("Usage: sendhtml [[-L
store-url] | [-T prot] [-H host] [-U
user] [-P passwd]]");
System.out.println("\t[-s subject] [-o
from-address] [-c cc-addresses] [-b
bcc-addresses]");
System.out.println("\t[-f record-mailbox]
[-M transport-host] [-d] [address]");
System.exit(1);
} else {
break;
}
}

try {
if (optind < argv.length) {
// XXX - concatenate all remaining arguments
to = argv[optind];
System.out.println("To: " + to);
} else {
System.out.print("To: ");
System.out.flush();
to = in.readLine();
}
if (subject == null) {
System.out.print("Subject: ");
System.out.flush();
subject = in.readLine();
} else {
System.out.println("Subject: " + subject);
}

Properties props = System.getProperties();


// could use Session.getTransport() and Transport.connect()
// assume we're using SMTP
if (mailhost != null)
props.put("mail.smtp.host", mailhost);

// Get a Session object


Session session = Session.getDefaultInstance(props, null);
if (debug)
session.setDebug(true);

// construct the message


Message msg = new MimeMessage(session);
if (from != null)
msg.setFrom(new InternetAddress(from));
else
msg.setFrom();

msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to, false));
if (cc != null)
msg.setRecipients(Message.RecipientType.CC,
InternetAddress.parse(cc, false));
if (bcc != null)
msg.setRecipients(Message.RecipientType.BCC,
InternetAddress.parse(bcc, false));

msg.setSubject(subject);

MimeMultipart mp = new MimeMultipart();

mp.setSubType("related");

MimeBodyPart mbp1= new MimeBodyPart();


String html =
"<html>"+
"<head><title></title></head>"+
"<body>"+
"<b> see the following jpg : it is a car!</b><br>"+
"<a href=a.jsp>hello</a><br>"+
"<IMG SRC=cid:23abc@pc27 width=80% height=60%><br>"+
"<b> end of jpg</b>"+
"</body>"+
"</html>";

mbp1.setContent(html,"text/html");

MimeBodyPart mbp2 = new MimeBodyPart();


FileDataSource fds = new FileDataSource(
"d:/html/bmp/1-1-95679_0005.jpg");
mbp2.setFileName(fds.getName());
mbp2.setText("This is a beautiful car !");
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setHeader("Content-ID","<23abc@pc27>");
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
msg.setContent(mp);

msg.setSentDate(new Date());

Transport.send(msg);
System.out.println(mp.getCount());
System.out.println("\nMail was sent successfully.");

} catch (Exception e) {
e.printStackTrace();
}
}
}
You can run it by following steps:

1. replace the .gif file with another one on your local machine.
2. javac sendhtml.java
3. java sendhtml -M 111.222.1.21 test@yahoo.com .
* 111.222.1.21 is the SMTP Server

How do I specify the reply-to address of a message?


Location: http://www.jguru.com/faq/view.jsp?EID=98939
Created: Jul 9, 2000 Modified: 2000-07-25 14:28:58.575
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by wendy ye (http://www.jguru.com/guru/viewbio.jsp?EID=98119

The setReplyTo() method of the Message class allows to you specify a different set of
reply-to addresses than the from field. The following demonstrates. Be sure to
provide the method with an array of InternetAddress objects:
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class ReplyExample {


public static void main (String args[])
throws Exception {
String host = args[0];
String from = args[1];
String to = args[2];
String reply = args[3];

// Get system properties


Properties props = System.getProperties();

// Setup mail server


props.put("mail.smtp.host", host);

// Get session
Session session = Session.getInstance(props, null);
// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setReplyTo(new InternetAddress[]
{new InternetAddress(reply)});
message.setSubject("Hello JavaMail");
message.setText("Welcome to JavaMail");

// Send message
Transport.send(message);
}
}

How do I set/get the priority of a message?


Location: http://www.jguru.com/faq/view.jsp?EID=100832
Created: Jul 12, 2000 Modified: 2000-07-12 19:38:23.819
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Shashidhar Mudigonda
(http://www.jguru.com/guru/viewbio.jsp?EID=100253

To set the header, you need to add an "X-Priority" header:

MimeMessage msg;
...
msg.addHeader("X-Priority", "1");
To get the header, just ask for the header. Do notice that you get an array back.

MimeMessage msg;
...
String priority[] = msg.getHeader
("X-Priority");
You can also ask with String getHeader(String name, String
delimiter) if you want to treat them as a delimited list.

How can I make a Message object from a text file / input stream (in RFC-
822 format)?
Location: http://www.jguru.com/faq/view.jsp?EID=104131
Created: Jul 17, 2000 Modified: 2000-07-25 14:44:49.007
Author: Eric Aubourg (http://www.jguru.com/guru/viewbio.jsp?EID=104119)
Question originally posed by Alex Chaffee PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=3

If your text file input stream is istr, just do:

javax.mail.internet.MimeMessage msg = new javax.mail.internet.MimeMessage(sess,


istr);
where sess is a JavaMail session. If you need to create a session (for instance, you
just want to parse the text file using Message methods):

class MyAuthenticator
extends javax.mail.Authenticator {}
javax.mail.Authenticator auth =
new MyAuthenticator();
java.util.Properties prop =
new java.util.Properties();
javax.mail.Session sess =
javax.mail.Session.getInstance(
prop, auth);

How long can a mail folder remain open?


Location: http://www.jguru.com/faq/view.jsp?EID=104355
Created: Jul 17, 2000 Modified: 2000-07-25 14:45:16.643
Author: Andrea Pompili (http://www.jguru.com/guru/viewbio.jsp?EID=51802)
Question originally posed by Az Madu
(http://www.jguru.com/guru/viewbio.jsp?EID=103536

It depends by the Mail Server's configuration.

JavaMail doesn't allow to handle this timeout value because all accesses to the Mail
Server are made using a remote protocol as POP3 or IMAP.

These protocols could not control the timeout setting because this procedure changes
from Mail Server to Mail Server...

So you need to control this parameter accessing directly to the Mail Server
administration. To alert the user for session timeout you have to use a parameter
inside your application initially set to the value of the Mail Server's timeout and
decrease its value once per second until it reaches 0.

How do I use the JavaMail API to read newsgroups messages?


Location: http://www.jguru.com/faq/view.jsp?EID=107152
Created: Jul 20, 2000 Modified: 2000-07-25 12:10:49.352
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Francesco Marchioni
(http://www.jguru.com/guru/viewbio.jsp?EID=59707

1. Get an NNTP provider. The only one I am aware of is the one provided from
knife at http://www.dog.net.uk/knife/.
2. Place JAR file in CLASSPATH. It has a javamail.providers file already there so
you don't need to edit/modify this.
3. When you get the store, get it as "nttp"
4. When you get the folder, get the newsgroup you want, like
"comp.lang.java.corba"
5. To get the list of messages in the folder, use folder.getMessages()
Thats basically about it. Treat the newsgroup messages as you would a mail message
to read / deal with attachments.

The following program demonstrates:

import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class GetNewsExample {


public static void main (String args[])
throws Exception {
String host = args[0];
String username = args[1];
String password = args[2];
String newsgroup = args[3];

// Create empty properties


Properties props = new Properties();

// Get session
Session session = Session.getInstance(
props, null);

// Get the store


Store store = session.getStore("nntp");
store.connect(host, username, password);

// Get folder
Folder folder = store.getFolder(newsgroup);
folder.open(Folder.READ_ONLY);

BufferedReader reader = new BufferedReader (


new InputStreamReader(System.in));

// Get directory
Message message[] = folder.getMessages();
for (int i=0, n=message.length; i<n; i++) {
System.out.println(i + ": "
+ message[i].getFrom()[0]
+ "\t" + message[i].getSubject());

System.out.println(
"Do you want to read message?" +
" [YES to read/QUIT to end]");
String line = reader.readLine();
// Mark as deleted if appropriate
if ("YES".equals(line)) {
message[i].writeTo(System.out);
} else if ("QUIT".equals(line)) {
break;
}
}

// Close connection
folder.close(false);
store.close();
}
}

How do I "forward" an email along with any attachments?


Location: http://www.jguru.com/faq/view.jsp?EID=112681
Created: Jul 27, 2000 Modified: 2001-11-12 17:08:57.914
Author: susanta panda (http://www.jguru.com/guru/viewbio.jsp?EID=112666)
Question originally posed by Kam Bansal
(http://www.jguru.com/guru/viewbio.jsp?EID=107942

Its very simple. All you need to do is:

1. Create a new MimeBodyPart object


2. Set the content of it as the attachment
3. Create a MimeMultipart object
4. Add The MimeBodyPart to the MimeMultipart object
5. Send it the usual way

Comments and alternative answers

I've tried attaching an email as you said, but I'm...


Author: Erik Bielefeldt (http://www.jguru.com/guru/viewbio.jsp?EID=304539), Jan
17, 2001
I've tried attaching an email as you said, but I'm having a few problems. Whenever I
try to create a MimeBodyPart with the content set to the message to be forwarded, it
interprets the forwarded messages headers as the MimeBodyPart's own. Here's an
example:
InternetHeaders ih = new InternetHeaders();
ih.addHeader("Content-Type", "message/rfc822");
ih.addHeader("Content-Disposition", "inline");
MimeBodyPart mbp = new MimeBodyPart(ih,is);

Here, "is" is an input stream which contains the forwarded messages, as well as its
headers. Unfortunately, these get whiped out by the MimeBodyPart's headers, so the
original content-type and disposition of the forwarded message are lost. Hence, if the
forwarded message was a mime multipart, it won't be parsed correctly upon receipt.
I've tried every constructor there is and setting the content manually, but I always get
the same problem. Any help would be much appreciated. Thanks!

I guess I'll answer my own question for the benefit...


Author: Erik Bielefeldt (http://www.jguru.com/guru/viewbio.jsp?EID=304539), Feb
12, 2001
I guess I'll answer my own question for the benefit of anyone else who has come
across the same problem. The trick seems to be to create the MimeBodyPart, set the
needed headers, and then set the content using
MimeBodyPart.setDataHandler(DataHandler dh). I created a StringBufDataSource
specifically to handle this case. The parsing of headers in the MimeBodyPart
constructors is really a poor API, and at least should be documented to let users know.

Re: I guess I'll answer my own question for the benefit...


Author: Stefan Preuss (http://www.jguru.com/guru/viewbio.jsp?EID=508542), Oct
2, 2001
I'll get mad about this. It have the same problem as you. Maybe you can give an
example of your code. Thanx a lot. Stefan Preuß

Re: Re: I guess I'll answer my own question for the benefit...
Author: Stefan Preuss (http://www.jguru.com/guru/viewbio.jsp?EID=508542),
Oct 2, 2001
After hours of testing :) I think I've found a solution:

messageBodyPart = new MimeBodyPart();


DataHandler dh = new DataHandler(message, "message/rfc822");
messageBodyPart.setDataHandler(dh);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);

If you wan't to put another attachments into the mail it seems to be very import
that the messaage/rfc-part is the last body-part in the message. Otherwise the
displaying is corrupt.

Re: Re: Re: I guess I'll answer my own question for the benefit...
Author: Ellen Katsnelson
(http://www.jguru.com/guru/viewbio.jsp?EID=531891), Oct 27, 2001
With a little correction it worked for me.
messageBodyPart = new MimeBodyPart();
DataHandler dh = new DataHandler(originalMessage,
"message/rfc822");
messageBodyPart.setDataHandler(dh);
multipart.addBodyPart(messageBodyPart);
newMessage.setContent(multipart);

Also this is needed only in case the original message is not multipart. If it is
multipart I use:
newMessage.setContent((Multipart)originalMessage.getContent());

I'm having problems using JavaMail with the Microsoft Exchange Server.
What do I have to do to fix this?
Location: http://www.jguru.com/faq/view.jsp?EID=112788
Created: Jul 27, 2000 Modified: 2000-12-13 13:25:47.611
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by susanta panda
(http://www.jguru.com/guru/viewbio.jsp?EID=112666

According to the Notes.txt file that comes with JavaMail:

4. We've received reports of IMAP authentication failures on the Microsoft Exchange


Server 5.5, enterprise edition. This is due to a bug in the Microsoft server and the
"Service Pack 1 for Exchange Server 5.5" apparently fixes this server bug. The
service pack can be downloaded from the Microsoft website.

I want to use a port other than the default port for SMTP. Can I specify it in
JavaMail?
Location: http://www.jguru.com/faq/view.jsp?EID=116603
Created: Aug 1, 2000 Modified: 2000-08-01 21:02:09.463
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Sudheer Divakaran
(http://www.jguru.com/guru/viewbio.jsp?EID=106294

You can either set the "mail.smtp.port" property in the Properties you pass to the
Session object, or specify the port when you connect in the transport:
Transport smtp = Session.getTransport("smtp");
smtp.connect(host, port, username, password);

When using JavaMail with the Java WebServer, I get an


AccessControlException. How do I disable the security checks to permit
this?
Location: http://www.jguru.com/faq/view.jsp?EID=117574
Created: Aug 2, 2000 Modified: 2000-08-13 16:29:50.283
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Assuming you really want to disable the security checks for ALL your servlets, you
need to edit the server.properties file and set server.security=false.

How do you send a message such that the sender gets a return receipt when
the recipient opens the email?
Location: http://www.jguru.com/faq/view.jsp?EID=121033
Created: Aug 7, 2000 Modified: 2000-11-01 07:45:35.858
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by kj taimara
(http://www.jguru.com/guru/viewbio.jsp?EID=120720
(Thankfully) This isn't part of the SMTP mail protocol. It also is not possible given the
way e.g., security and mail relaying work. I.e., intermediate relays have no clue
whether or not a particular mail address is real or not or just another forwarding
alias or a mailing list or... And, any decent mail server won't tell you if the email
address is real or not since that's a security hole. In terms of robustness, this return-
receipt concept is silly, check out: ftp://koobera.math.uic.edu/www/proto/nrudt.txt
for a more thorough explanation.

However, RFC 1891 does define a way to find out if the message was successfully
delivered. See How do I receive an acknowledgement that a user has received my
message? for information on its usage.

What does this messaging exception mean:


javax.mail.NoSuchProviderException:
No provider for Address type: rfc822

I am running a Weblogic on a Sun...


Location: http://www.jguru.com/faq/view.jsp?EID=122151
Created: Aug 8, 2000 Modified: 2000-11-08 07:42:44.104
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Jane Ng (http://www.jguru.com/guru/viewbio.jsp?EID=112489

According to Sun's JavaMail FAQ:

Usually this is because JavaMail can't access the configuration files in mail.jar,
possibly because of a security permission problem; see this item for more details.
Also, make sure that you haven't extracted the mail.jar contents; you should include
the unmodified mail.jar file in the server's CLASSPATH.

Comments and alternative answers

Problem is with the JavaMail classes which are given...


Author: Kishan A (http://www.jguru.com/guru/viewbio.jsp?EID=66106), Aug 9, 2000
Problem is with the JavaMail classes which are given with Weblogic. To get around
this problem, download the latest jar files(mail.jar and activation.jar) from here and
put them in the classpath used by weblogic. Ensure that these jar files come before
weblogicaux.jar file (which contains the JavaMail classes) in the classpath used to
start Weblogic. This will solve the problem.

Re: Problem is with the JavaMail classes which are given...


Author: Sharan RM (http://www.jguru.com/guru/viewbio.jsp?EID=395782), Apr 5,
2001
Hello There, I prepended mail.jar,smtp.jar,activation.jar using d:\wlconfig.exe
-classpath. Still I am getting the following error
javax.mail.NoSuchProviderException: No Provider for Address Type: rfc822 I am
using weblogic 5.1 without any service patches. The same code is working fine
from a client. Heeeeeeeeelp meeeeeee. Thanks in advance. Sharan

Re: Re: Problem is with the JavaMail classes which are given...
Author: sachin Sahoo (http://www.jguru.com/guru/viewbio.jsp?EID=411391),
May 1, 2001
Hope the problem got solved for you by this time, otherwise try to set the
Javaclasspath with the above mentioned jar files after you updated
weblogic.policy file with the appropriate grant permissions. Hope this helps,
-Sachin. SachinSahoo@yahoo.com

Re: Re: Problem is with the JavaMail classes which are given...
Author: ssk ssk (http://www.jguru.com/guru/viewbio.jsp?EID=415094), May 4,
2001
you just set the PRE_CLASSPATH in startweblogic.cmd file. you must provide
the classpath for all the related .jar file(activation.jar,mail.jar...). it will solve ur
problem.

Re: Re: Re: Problem is with the JavaMail classes which are given...
Author: Sverker Brundin
(http://www.jguru.com/guru/viewbio.jsp?EID=472457), Aug 9, 2001
I had this problem on Linux with Weblogic. The application worked fine on
my Windows 2000 machine. When I compared the weblogic.jar files on both
machines I noticed that the one on Linux missed the file
javamail.default.providers. I added this to the weblogic.jar file on linux (has
to be under the META-INF directory). I also had to update the mail.jar and
activation.jar files and make weblogic to use these instead of the ones in
weblogic.jar (by editing the classpath in startWebLogic.sh). Now everything
works fine!

Re: Re: Re: Re: Problem is with the JavaMail classes which are
given...
Author: Sverker Brundin
(http://www.jguru.com/guru/viewbio.jsp?EID=472457), Aug 9, 2001
A better solution: Just add mail.jar to bea\wlserver6.0\lib and change the
classpath so that mail.jar is loaded before weblogic.jar.
(javamail.default.providers is included in mail.jar). Works for me anyway!
;)

Re[2]: Problem is with the JavaMail classes which are given...


Author: Shilpi Goyal (http://www.jguru.com/guru/viewbio.jsp?EID=741110),
Jan 30, 2002
I have set the pre_classpath in startweblogic as well as the classpath in setenv..
still I get the same message if i try to send mail thru weblogic server.
javax.mail.NoSuchProviderException: No provider for Address type: rfc822
My independent application(without weblogic server) works fine. Please tell
me where to set the jar files' classpath???

Re[2]: Problem is with the JavaMail classes which are given...


Author: Omindra Rana
(http://www.jguru.com/guru/viewbio.jsp?EID=1164665), Jun 1, 2004
as u have included all files but meta-inf file. include this file where all files are
resides ie in classpath. this must solve your problem

How do I set the mail.jar and activation.jar files...


Author: Darbha Anuradha (http://www.jguru.com/guru/viewbio.jsp?EID=241011),
Oct 31, 2000
How do I set the mail.jar and activation.jar files in the server's CLASSPATH? In the
System properties I put the mail.jar and activation.jar before WebLogic's path. Still it
is giving NoSuchProviderException and is giving No Provider for rfc822. Please
kindly send the solution.

Type this on the command prompt. d:\weblogic\bin\...


Author: Kunal Jolly (http://www.jguru.com/guru/viewbio.jsp?EID=248487), Nov 7,
2000
Type this on the command prompt.

d:\weblogic\bin\wlconfig.exe -classpath
d:\weblogic\classes\mail.jar;d:\weblogic\classes\activation.jar

Be sure to use the proper drive

Re: Type this on the command prompt. d:\weblogic\bin\...


Author: Shelli Byers (http://www.jguru.com/guru/viewbio.jsp?EID=720848), Jan
15, 2002
A solution I have just found is updating the set PRE_CLASSPATH in
StartWeblogic.cmd, then upating the set CLASSPATH to include the
PRE_CLASSPATH. This is how I finally got it to work.

Re[2]: Type this on the command prompt. d:\weblogic\bin\...


Author: Bhavesh Vakil
(http://www.jguru.com/guru/viewbio.jsp?EID=1066016), Mar 14, 2003
Hi, I have similar problem, my hosting provider is not providing JAR file
support. Due to this limitation I have to extract JAR file content (mail.jar) and
(activation.jar). I upload extracted content. I apply all suggestion mention
above, but No luck. It's working my development PC, but not working at
hosting site. Bhavesh www.ResMe.com

Re[3]: Type this on the command prompt. d:\weblogic\bin\...


Author: Shabeer Ibrahim
(http://www.jguru.com/guru/viewbio.jsp?EID=1078909), Apr 24, 2003
Hi , If you have done all the classpath settings try the following . You
might not be instantiating a Transport. ie You may be using the default
transport. try the following code before calling the send method: Transport
transport = session.getTransport(address[0]); transport.send(msg); Shabeer
don't worry
Author: Omindra Rana (http://www.jguru.com/guru/viewbio.jsp?EID=1164665), Jun
1, 2004
include mail.jar,activation.jar,smtp.jar and other mail jar files in your classpath with
meta-inf file

Where can I get an IMAP mail server for testing purposes?


Location: http://www.jguru.com/faq/view.jsp?EID=123063
Created: Aug 9, 2000 Modified: 2000-08-09 12:01:27.293
Author: Gerre Gannaway (http://www.jguru.com/guru/viewbio.jsp?EID=123060)
Question originally posed by Muhammad Qureshi
(http://www.jguru.com/guru/viewbio.jsp?EID=87763

The following URL contains a long list of mail servers(with descriptions and links)
from http://www.davecentral.com/mailserv.html.

How can I use the mailto: protocol from URL or URLConnection?


Location: http://www.jguru.com/faq/view.jsp?EID=126822
Created: Aug 14, 2000 Modified: 2000-09-01 13:28:32.946
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Tim Rohaly PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=10

Both URL and URLConnection act as mail user agents when using the mailto:
protocol. They need to connect to a mail transfer agent to effect delivery. An MTA, for
example sendmail, handles delivery and forwarding of e-mail.

Note that a mailto: URL doesn't contain any information about where this MTA is
located - you need to specify it explicitly by setting a Java system property on the
command line. For example, to run the program mailto.java shown below, you would
use the command:

java -Dmail.host=mail.yourisp.net mailto


This tells the mailto: protocol handler to open a socket to port 25 of
mail.yourisp.net and speak SMTP to it. You should of course substitute the name of
your own SMTP server in the above command line.
import java.io.*;
import java.net.*;

public class mailto {

public static void main(String[] args) {


try {
URL url =
new URL("mailto:foo@bar.com");
URLConnection conn =
url.openConnection();
PrintStream out =
new PrintStream(conn.getOutputStream(), true);

out.print(
"From: jguru-fan@yourisp.com"+"\r\n");
out.print(
"Subject: Works Great!"+"\r\n");
out.print(
"Thanks for the example - it works great!"+"\r\n");
out.close();
System.out.println("Message Sent");
} catch (IOException e) {
System.out.println("Send Failed");
e.printStackTrace();
}
}
}

What's the difference between an MUA and an MTA?


Location: http://www.jguru.com/faq/view.jsp?EID=126826
Created: Aug 14, 2000 Modified: 2000-08-14 22:55:09.941
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10)

An MUA is a mail user agent - this is a program that allows a user to read, compose,
and send e-mail. Examples of MUAs are Eudora, pine, Netscape Mail, and Microsoft
Outlook. If your program uses the JavaMail API to send e-mail, it is acting as an
MUA.

There are typically multiple applications on each computer that can act as an MUA;
each user typically runs an MUA directly. You can think of an MUA as an e-mail client.

An MTA is a mail transfer agent - this is a program that is responsible for the
transport, delivery, and forwarding of e-mail. SMTP servers like sendmail are MTAs.

There will typically be at most one MTA on a machine. More likely, a large number of
users will use the same MTA. For example, you probably send e-mail using your ISP's
SMTP server. The ISPs MTA will be shared by all of that ISP's customers. You can
think of an MTA as an e-mail server.

How do I find out the SMTP server of the recipient of a message?


Location: http://www.jguru.com/faq/view.jsp?EID=128496
Created: Aug 16, 2000 Modified: 2000-08-16 13:46:41.243
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Like when sending email through Eudora or Outlook, the only SMTP server you
specify is your own. It is the responsibility of the SMTP server to figure out how the
email message will get from here to there for each recipient.

If your mail server requires authentication before sending a message, see another
question about relaying.

How do I limit the parts of a message I get? I'd like to avoid fetching
attachments until a user wants it.
Location: http://www.jguru.com/faq/view.jsp?EID=130491
Created: Aug 19, 2000 Modified: 2000-08-20 10:09:44.73
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
The JavaMail API supports a FetchProfile that allows you to limit the contents
retrieved. The FetchProfile.Item class specifies three pre-defined items that can be
fetched: ENVELOPE, FLAGS, and/or CONTENT_INFO. For instance, if all you want is
the From, To, Subject, and Date (or message Envelope info), you could do something
like the following:
Messages msgs[] = folder.getMessages();
FetchProfile profile = new FetchProfile();
profile.add(FetchProfile.Item.ENVELOPE);
folder.fetch(msgs, profile);
You can also add specific headers to the fetch profile with:
profile.add("X-mailer");

Where can I find a list of the different properties that the JavaMail API
uses?
Location: http://www.jguru.com/faq/view.jsp?EID=131682
Created: Aug 21, 2000 Modified: 2002-03-21 17:13:14.978
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Appendix A of the JavaMail specification includes the standard set. Each provider
may support additional properties that are specific to that provider. For instance, in
the Notes.txt file that comes with JavaMail, you can find an additional list that the
Sun IMAP/SMTP providers supports.

Is there a way to send mail using Lotus Notes mail server in Java with
JavaMail or any other API?
Location: http://www.jguru.com/faq/view.jsp?EID=132324
Created: Aug 22, 2000 Modified: 2000-08-22 14:02:27.567
Author: Animikh Sen (http://www.jguru.com/guru/viewbio.jsp?EID=110646)
Question originally posed by sharad gupta
(http://www.jguru.com/guru/viewbio.jsp?EID=100198

You can turn on the SMTP service in the Notes server to send mail.
You can also create a IMAP mailBox and turn on the IMAP service in Notes (I think
only in 4.6 + versions) and read from there using JavaMail.

How do I use a ConnectionListener/ConnectionEvent to know when a


connection is opened?
Location: http://www.jguru.com/faq/view.jsp?EID=132573
Created: Aug 22, 2000 Modified: 2000-08-28 07:33:23.834
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Ulises D Estecche I.
(http://www.jguru.com/guru/viewbio.jsp?EID=127207

To find out when a connection is opened, attach the ConnectionListener to the


Transport you are using to open the connetion. This means you can't use the static
Transport.send() method, as you don't have access to the specific Transport you are
using. Instead, you need to get the specific transport, and then attach the listener.
This is demonstrated in the following example.
import java.util.Properties;
import javax.mail.*;
import javax.mail.event.*;
import javax.mail.internet.*;

public class ConnectionExampleListener {


public static void main (String args[])
throws Exception {
String host = args[0];
String from = args[1];
String to = args[2];

// Get system properties


Properties props = System.getProperties();

// Setup mail server


props.put("mail.smtp.host", host);

// Get session
Session session =
Session.getInstance(props, null);

// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("Hello JavaMail");
message.setText("Welcome to JavaMail");

// Define transport
Transport transport =
session.getTransport("smtp");
ConnectionListener listener =
new ConnectionListener() {
public void opened(ConnectionEvent e) {
System.out.println("Opened");
}
public void disconnected(ConnectionEvent e) {
System.out.println("Disconnected");
}
public void closed(ConnectionEvent e) {
System.out.println("Closed");
}
};
transport.addConnectionListener(listener);
transport.connect(host, "", "");
transport.sendMessage(message,
message.getAllRecipients());
transport.close();
Thread.sleep(1000);
}
}

How do I use JavaMail API to send multipart/alternative mails? I want to


send an html-mail, but if the recipiant dont know how to parse them, they
will see a text/plain version.
Location: http://www.jguru.com/faq/view.jsp?EID=132654
Created: Aug 23, 2000 Modified: 2001-11-12 17:07:21.276
Author: Andrea Pompili (http://www.jguru.com/guru/viewbio.jsp?EID=51802)
Question originally posed by Stefan Mellberg
(http://www.jguru.com/guru/viewbio.jsp?EID=127183

You have to build the message using a MimeMultipart object as content.


If you have attachments you have to set the first part of the message with a
MimeMultipart object .

To build a multipart/alternative object with a plain content and an html one follow
this code:
String plain_text = ... ;
String html_text = ... ;
MimeMultipart content = new MimeMultipart("alternative");
MimeBodyPart text = new MimeBodyPart();
MimeBodyPart html = new MimeBodyPart();
text.setText(plain_text);
html.setContent(html_text, "text/html");
content.addBodyPart(text);
content.addBodyPart(html);
To parse a message with a content multipart/alternative you have to use the
MimeMultipart class and then choose from the parts inside the one you prefer
according to its content type.
Comments and alternative answers

Example Code Doesn't Work


Author: David Rosner (http://www.jguru.com/guru/viewbio.jsp?EID=439252), Jun
14, 2001
I tried the following code and the resulting message displayed both the text and the
html within the email body. In addition looking at the mail headers it doesn't look like
my mail client is recognizing the message as a MimeMultipart.

Thoughts as to why?

MimeMultipart content = new MimeMultipart("alternative");


MimeBodyPart text = new MimeBodyPart();
MimeBodyPart html = new MimeBodyPart();
text.setText( this.strBody );
html.setContent(this.strHTMLBody, "text/html");
content.addBodyPart(text);
content.addBodyPart(html);
message.setContent( content );

Re: Example Code Doesn't Work


Author: Jin Bal (http://www.jguru.com/guru/viewbio.jsp?EID=516078), Nov 5,
2001
I am having exactly the same problem. What seems to be happening is that the
header is not being changed from text/plain by the setContent(Multipart)
method, so that when the client reads it it thinks that it is text. I have no solution to
this currently and I've been trawling the mail archives for a fix - somebody please
help!!

Re: Re: Example Code Doesn't Work


Author: david rosner (http://www.jguru.com/guru/viewbio.jsp?EID=539421),
Nov 5, 2001
Hi, Don't know why the following works, but it does. It appears that there is
either a bug in the JavaMail implementation, or its a typo in the docs. Here is
the code that I used to mail HTML and Text multipart emails:

MimeMultipart content = new


MimeMultipart("alternative");
MimeBodyPart text = new MimeBodyPart();
MimeBodyPart html = new MimeBodyPart();

text.setText( oMail.getStrBody() );
text.setHeader("MIME-Version" , "1.0" );
text.setHeader("Content-Type" , text.getContentType()
);

html.setContent(oMail.getStrHTMLBody(), "text/html");
html.setHeader("MIME-Version" , "1.0" );
html.setHeader("Content-Type" , html.getContentType()
);

content.addBodyPart(text);
content.addBodyPart(html);

message.setContent( content );
message.setHeader("MIME-Version" , "1.0" );
message.setHeader("Content-Type" ,
content.getContentType() );
message.setHeader("X-Mailer", "Recommend-It Mailer
V2.03c02");
message.setSentDate(new Date());
About sending Multipart text and html mail.
Author: Kevin Russell (http://www.jguru.com/guru/viewbio.jsp?EID=896483), Sep
18, 2002
Is it possible to either post a code example that does 2 things, is clear to understand
and actually works. The examples provided do not clearly define what happens where
and when. This looks like something Microsoft would post as an answer to a question.

Re: About sending Multipart text and html mail.


Author: Kevin Bridges (http://www.jguru.com/guru/viewbio.jsp?EID=1119238),
Oct 2, 2003

I found that the above was useless for me as well. Here is what I needed to do to
send a multi-part text/html email. You may need to edit the line:
props.put("mail.smtp.host", "localhost");

You will need to edit the from and to emails.

// Create the message to send


Properties props = new Properties();
props.put("mail.smtp.host", "localhost");
Session session = Session.getInstance(props,null);
MimeMessage message = new MimeMessage(session);

// Create the email addresses involved


InternetAddress from = new InternetAddress("from@from.com");
InternetAddress to = new InternetAddress("to@to.com");

// Fill in header
message.setSubject("I am a multipart text/html email" );
message.setFrom(from);
message.addRecipient(Message.RecipientType.TO, to);

// Create a multi-part to combine the parts


Multipart multipart = new MimeMultipart();

// Create your text message part


BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Here is your plain text message");

// Add the text part to the multipart


multipart.addBodyPart(messageBodyPart);

// Create the html part


messageBodyPart = new MimeBodyPart();
String htmlText = "<H1>I am the html part</H1>";
messageBodyPart.setContent(htmlText, "text/html");

// Add html part to multi part


multipart.addBodyPart(messageBodyPart);
// Associate multi-part with message
message.setContent(multipart);

// Send message
Transport.send(message);

Re[2]: About sending Multipart text and html mail.


Author: Brendan Richards
(http://www.jguru.com/guru/viewbio.jsp?EID=1148403), Feb 23, 2004
I had just one problem with this code:

It correctly setup two message parts, one text and one html but it gave the main
message a mime type of multipart/mixed.
This resulted in it being displayed as a plain text email with the HTML body
attached as a HTML file.

I corrected it by setting the main mime type to multipart/alternavive by


replacing this line:
Multipart multipart = new MimeMultipart();

to read:

Multipart multipart = new MimeMultipart("alternative");

This then worked as expected with only one of the body parts being displayed
on the client.

Re[3]: About sending Multipart text and html mail.


Author: Asish Law
(http://www.jguru.com/guru/viewbio.jsp?EID=1152755), Mar 9, 2004
I am having some problems getting "alternative" to work. Here is the
section of my code that creates the content (no attachments):
MimeMessage message = new MimeMessage(session);

// Create a multi-part to combine the parts


MimeMultipart multipart = new
MimeMultipart("alternative");

// Create text message part


MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(textBody);
multipart.addBodyPart(messageBodyPart);

// Create html part


messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(htmlBody, "text/html");
multipart.addBodyPart(messageBodyPart);

// Associate multi-part with message


message.setContent(multipart);
message.saveChanges();

The above works great for browsers/servers that support html content.
Internet services that don't support the used character set give the following
error. I've seen postings mentioning this error, and have tried to follow the
suggestions. Not sure what I am missing in the code above. Also, if I
change "alternative" to "mixed", both (html and text) browsers receive text
email with html as an attachment (as pointed out in an earlier message in
this thread). Thanks for any help that you can provide.

This message uses a character set that is not supported by the Internet
Service. To view the original message content, open the attached message.
If the text doesn't display correctly, save the attachment to disk, and then
open it using a viewer that can display the original character set.
<<message.txt>>

Where can I find the API documentation for JavaMail?


Location: http://www.jguru.com/faq/view.jsp?EID=134140
Created: Aug 24, 2000 Modified: 2000-08-24 12:32:55.142
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

The JavaMail API documentation is available from Sun's J2EE API documentation
page.

Does FetchProfile work with POP providers or only IMAP?


Location: http://www.jguru.com/faq/view.jsp?EID=134639
Created: Aug 24, 2000 Modified: 2000-08-27 07:56:43.49
Author: Andrea Pompili (http://www.jguru.com/guru/viewbio.jsp?EID=51802)
Question originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

Yes, but the FetchItems that work are javax.mail.FetchProfile.Item.ENVELOPE


and javax.mail.UIDFolder.FetchProfileItem.UID.
This behaviour is for version 1.1.1 of the POP3 provider given by Sun, providers from
others may or may not.

How do I implement a mail server using Java?


Location: http://www.jguru.com/faq/view.jsp?EID=134946
Created: Aug 25, 2000 Modified: 2003-02-25 21:57:22.46
Author: Serge Knystautas (http://www.jguru.com/guru/viewbio.jsp?EID=100012)
Question originally posed by Savio D'Souza
(http://www.jguru.com/guru/viewbio.jsp?EID=110887

Check out the JAMES project at http://james.apache.org/. It is an open source 100%


Java implementation of a mail server (SMTP/POP3 for now with TLS support...
IMAP4, LDAP integration, other features coming).
FAQ Manager note: If you are truly interested in writing your own server, basically
you'll need to read up on the different RFCs for the different protocols like SMTP,
POP3, IMAP, attachments, etc. To start, http://cr.yp.to/smtp.html offers a great
place to learn about SMTP.
Comments and alternative answers

IMAP4 Server SDK by GoodServer


Author: David Rauschenbach (http://www.jguru.com/guru/viewbio.jsp?EID=486029),
Aug 28, 2001
GoodServer offers commmercial server SDK's for creating your own IMAP4, POP3
or SMTP servers. http://www.goodserver.com

Are there any resources to help someone create a service provider? Either
for my own protocol or creating my own POP3/IMAP/SMTP provider.
Location: http://www.jguru.com/faq/view.jsp?EID=135882
Created: Aug 27, 2000 Modified: 2000-08-27 07:54:29.706
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

Sun offers a roughly 40 page Service Provider Guide to help you create a provider.
You can get either the PDF or PostScript version of the file.

How can I find out what messages are marked for deletion (the expunge
action)?
Location: http://www.jguru.com/faq/view.jsp?EID=136460
Created: Aug 28, 2000 Modified: 2000-08-28 07:29:29.361
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Sampat Jena
(http://www.jguru.com/guru/viewbio.jsp?EID=136186

You need to attach a MessageChangedListener to the folder. Then, in the


messageChanged() method, you can find out if/when the flags changed. You'll have
to check specifically if the deleted flag is set, or assuming that's the only one you are
changing, you don't. The following listener is basically what you need:
// Attach listener
MessageChangedListener listener =
new MessageChangedListener() {
public void messageChanged(MessageChangedEvent e) {
try {
Message m = e.getMessage();
System.out.println("Flagged: " + m.getSubject());
int type = e.getMessageChangeType();
System.out.println("\tFlags Changed? " +
(type == MessageChangedEvent.FLAGS_CHANGED));
} catch (MessagingException me) {
System.out.println("Oops: " + me);
}
}
};
folder.addMessageChangedListener(listener);
Comments and alternative answers

You can use the following satements to find the message...


Author: v sirisha (http://www.jguru.com/guru/viewbio.jsp?EID=106368), Aug 30,
2000
You can use the following satements to find the message marked for deletion.
msg=folder.getMessage(msgNum);

if (msg.isSet(Flags.Flag.DELETED)) {
}

I am a little confused about the differences, advantages, and disadvantages


of using JavaMail, JMS, and James Apache. Could someone please help me
by clarifying these to decide which is the best solution to implement?
Location: http://www.jguru.com/faq/view.jsp?EID=136666
Created: Aug 28, 2000 Modified: 2000-08-28 12:07:35.052
Author: Jerry Smith (http://www.jguru.com/guru/viewbio.jsp?EID=9) Question
originally posed by Armando Noval
(http://www.jguru.com/guru/viewbio.jsp?EID=136009

The JavaMail API is a mail user agent (MUA) for creating programs for a user to
get/send email messages, using standard mail protocols.

James (and others) is a mail server / mail transfer agent (MTA). It is responsible for
the actual sending and delivery of mail messages, as well as queueing messages
when something is down, holding them for the user to receive, etc.

The Java Message Service (JMS) is a Java API for interclient messaging. JMS provides
a general-purpose facility for sending messages among distributed application
components. It does not provide email functionality.

When getting mail with a large attachment JavaMail tries to download the
attachment when getCount() is called on the multipart. Is there a way to
avoid downloading the attachment if it isn't needed?
Location: http://www.jguru.com/faq/view.jsp?EID=138349
Created: Aug 30, 2000 Modified: 2001-11-12 17:08:14.716
Author: Serge Knystautas (http://www.jguru.com/guru/viewbio.jsp?EID=100012)
Question originally posed by Manmohan Garg
(http://www.jguru.com/guru/viewbio.jsp?EID=106106

The MIME specification does not include meta data on the number of sections or any
information on each section, so the only way to know the number of sections in a
message is to download the whole message and count each part.

FAQ Manager Note: If you'd like to avoid downloading the attachments altogether,
you can use a FetchProfile.
How can I implement automail responders using the JavaMail API?
Location: http://www.jguru.com/faq/view.jsp?EID=138355
Created: Aug 30, 2000 Modified: 2000-08-30 08:50:24.582
Author: Serge Knystautas (http://www.jguru.com/guru/viewbio.jsp?EID=100012)
Question originally posed by vamshi krishna
(http://www.jguru.com/guru/viewbio.jsp?EID=16658

You could create a FolderListener object and listen for new messages, create a new
message as a reply, and send it out using the JavaMail API. However, this approach
requires you to keep a connection open to your IMAP account at all times, and would
not work with a POP account as you can only have one connection at a time with a
POP account.

You might want to check out JAMES, an all Java implementation of an SMTP and
POP3 server (IMAP coming) that offers a mailet API. Mailets allow you to process
incoming mail messages and do tasks such as autorespond to incoming messages.

To write a program that automatically responds to email, is it best to use an


MUA approach (like JavaMail API) or to do something with the mail server
(MTA)?
Location: http://www.jguru.com/faq/view.jsp?EID=138358
Created: Aug 30, 2000 Modified: 2000-08-30 08:40:21.02
Author: Serge Knystautas (http://www.jguru.com/guru/viewbio.jsp?EID=100012)
Question originally posed by Muhammad Qureshi
(http://www.jguru.com/guru/viewbio.jsp?EID=87763

I think the MTA approach works better as it is more reliable. You can channel all
messages through your MTA and fire actions accordingly. With the MUA approach,
you consume network resources by keeping connections open and risk failure if the
connection is temporarily down. With the MTA approach, if your MTA goes down, the
messages will queue in the previous hop until your system is restored, and you only
use a connection when a message is actually transfered.

How do I send out mail using the JavaMail API without using an SMTP host
provider?
Location: http://www.jguru.com/faq/view.jsp?EID=138360
Created: Aug 30, 2000 Modified: 2000-08-30 08:38:57.931
Author: Serge Knystautas (http://www.jguru.com/guru/viewbio.jsp?EID=100012)
Question originally posed by Kian Hui Teo
(http://www.jguru.com/guru/viewbio.jsp?EID=64456

You cannot send out mail without any knowledge of who is receiving it. In JavaMail if
you do not explicitly specify the outbound mail server, it will assume localhost. If you
want to avoid using a single SMTP host provider to send outgoing messages, you can
use a DNS library package (such as http://www.xbill.org/dnsjava/) to query the MX
records of the recipients of their message, and send the mail directly to their server.

What is James?
Location: http://www.jguru.com/faq/view.jsp?EID=141585
Created: Sep 4, 2000 Modified: 2000-10-09 21:20:39.026
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
James stands for Java Apache Mail Enterprise Server. It is part of the Apache effort.
As the acronym expansion may show, it is a mail server, written in Java. It supports
extending the mail server by creating little programs called mailets.

What is a mailet?
Location: http://www.jguru.com/faq/view.jsp?EID=141586
Created: Sep 4, 2000 Modified: 2003-02-25 21:57:50.641
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

A mailet is a Java program that extends Apache's James mail server. Think of it as a
servlet, but for a mail server, where you can easily extend the capabilities with
functionality like auto-responders.

Where can I find help for how to setup and use James?
Location: http://www.jguru.com/faq/view.jsp?EID=141588
Created: Sep 4, 2000 Modified: 2000-09-04 10:42:55.499
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Carfield Yim
(http://www.jguru.com/guru/viewbio.jsp?EID=4648

There really isn't much documentation on James yet. The only documentation
Apache makes available at the moment is a single page. You can try searching the
James mail archives, though its mostly for developers or try to submit something to
Sun's JavaMail mailing list.

There is a topic in this FAQ on James, but the content is a little slim. Hopefully, it will
build up over time.

Comments and alternative answers

See this article at JavaWorld


Author: Ramon Gonzalez (http://www.jguru.com/guru/viewbio.jsp?EID=728508),
May 29, 2002
There is an article at Javaworld that describes how to use Apache James. Look at
http://www.javaworld.com/javaworld/jw-10-2001/jw-1026-jamesmail.html

James is based on something called Avalon. What is Avalon?


Location: http://www.jguru.com/faq/view.jsp?EID=141600
Created: Sep 4, 2000 Modified: 2002-03-30 19:43:10.647
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Avalon is the Java Apache Server Framework. According to its description: The Java
Apache Server Framework project is an effort to create, design, develop and
maintain a common framework for server applications written using the Java
language.

Where can I get the James mailet API docs?


Location: http://www.jguru.com/faq/view.jsp?EID=141670
Created: Sep 4, 2000 Modified: 2003-02-25 21:56:34.986
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
The javadocs for the mailet API are available from
http://james.apache.org/mailet/index.html.

How do I query a DNS server for the MX (or other) records it holds on a
domain?
Location: http://www.jguru.com/faq/view.jsp?EID=200612
Created: Sep 7, 2000 Modified: 2001-06-26 13:30:36.88
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by Monty Dickerson
(http://www.jguru.com/guru/viewbio.jsp?EID=141678

The DNS protocol is described in RFC 1035 (http://www.faqs.org/rfcs/rfc1035.html),


with clarifications in RFC 2181 (http://www.faqs.org/rfcs/rfc2181.html).

Operating system libraries usually provide a way to find out the A records, e.g.
gethostbyname() - this same functionality is in the java.net.InetAddress class in
Java via getByName() and related methods. I've never encountered a system
function to get the MX records, and the same is true in Java. To find the MX records
you will need to open a socket to the DNS server and form a proper query. Refer to
the above RFCs for details of the protocol.

Comments and alternative answers

Instead of brewing your own DNS library from scratch,...


Author: Serge Knystautas (http://www.jguru.com/guru/viewbio.jsp?EID=100012),
Sep 8, 2000
Instead of brewing your own DNS library from scratch, I would suggest you use
existing DNS libraries. A mature open source Java implementation of the DNS
protocol is available at http://www.xbill.org/dnsjava/. JavaSoft has also come out with
an early implementation of using DNS through JNDI, which should support MX
record lookups. This is available at
http://developer.java.sun.com/developer/earlyAccess/jndi/.

See also the code from Java Network Programming, 2nd...


Author: Monty Dickerson (http://www.jguru.com/guru/viewbio.jsp?EID=141678),
Nov 13, 2000

See also the code from Java Network Programming, 2nd edition found at
http://www.manning.com/Hughes/index.html.

Check website http://www.xbill.org/dnsjava and the download the jar file. You
can get all you need.
Author: Ken Tan (http://www.jguru.com/guru/viewbio.jsp?EID=1024686), Nov 12,
2002
For example, for email test@yahoo.com, throuth the provided function in the
package, you can find mx1.mail.yahoo.com, mx2.mail.yahoo.com,
mx4.mail.yahoo.com are the mail servers for your javamail. That's it.
Where can I find a detailed code example of sending non-ASCII messages
(Japanese in my case)?
Location: http://www.jguru.com/faq/view.jsp?EID=200627
Created: Sep 7, 2000 Modified: 2000-09-07 19:32:36.94
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by mike claiborne
(http://www.jguru.com/guru/viewbio.jsp?EID=136752

You need to be sure to set the character set when you set the content. The following
example demonstrates. The message content is the numbers from 1-10.

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendJIS {


public static void main (String args[]) throws Exception {
String host = args[0];
String from = args[1];
String to = args[2];

// Get system properties


Properties props = System.getProperties();

// Setup mail server


props.put("mail.smtp.host", host);

// Get session
Session session = Session.getInstance(props, null);

// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("Hello JIS JavaMail");

String jisText =
"\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E
5D\u5341";

message.setContent(jisText, "text/plain; charset=JIS");

// Send message
Transport.send(message);
}
}
For some reason this only displays 1-6 okay as far as the content. I don't know why
7-10 is messed up. As I don't use Japanese that much, it could be my configuration.
Comments and alternative answers

Thanks a lot! This still leaves several unanswered...


Author: mike claiborne (http://www.jguru.com/guru/viewbio.jsp?EID=136752), Sep
7, 2000
Thanks a lot! This still leaves several unanswered questions.
1. According to the JavaMail docs, in order to use MimeMessage.setContent(Object
o, String s), the parm o should be a DataHandler object and there should be a
DataContentHandler in the environment which is able to handle that type
2. Which RFC determines "charset=JIS" (I may need to encode differently for my
target client)
3. Per RFC 821 & 822 , all content in an e-mail should be encoded into ascii. When I
ran your code, it sent out chars outside this range.

I got the character set encoding list from http://...


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Sep 7,
2000
I got the character set encoding list from
http://java.sun.com/j2se/1.3/docs/guide/intl/encoding.doc.html. Regarding the rest of
your comments, I'm not sure. I just played around until I got something to work
(showing Japanese characters in my email program, at the receiving end).

Re: I got the character set encoding list from http://...


Author: Mukund Ramadoss
(http://www.jguru.com/guru/viewbio.jsp?EID=820071), Apr 1, 2002
John, We are having an UTF-8 database and all our HTML form data are UTF-8
encoded.
All our clients are under SOLARIS environment.
When we use JavaMail to send email, the dtmail in Solaris displays only when we
login to Solaris in Unicode language/locale. When we login with EUCJP or
ShijtJis, we are seeing only junk in dtmail. I tried with Contenttype set as ISO-
2022-jp, JIS, etc but to no avail.
Should I do any conversion before doing a setContent?
Will appreciate your help.

Regards Mukund

1>try -------------------------------------- String...


Author: marx0207 wang (http://www.jguru.com/guru/viewbio.jsp?EID=268565), Dec
4, 2000
1>try
--------------------------------------
String myMsg="hi,MyAnswer";
MimeMessage msg=new MimeMessage();
msg.setText(myMsg,"JIS");
--------------------------------------
2>If your enviroment is Japanese Default Charset, you could use
--------------------------------------
String DefaultCharset=
MimeUtility.getDefaultJavaCharset();
String myMsg="hi,MyAnswer";
MimeMessage msg=new MimeMessage();
msg.setText(myMsg,DefaultCharset);
Both method succeed in my case: I sent Big5- charset message to myself notice: (You
Have to set the message type to 'MimeMessage' otherwise you can't find the method)

I have tried with my application ....


Author: Mustafa D (http://www.jguru.com/guru/viewbio.jsp?EID=921024), Jul 7,
2002
Hi,

I am following the same procedure as you have mentioned in your code snippet of
setting the charset to a particular language type. In my situation I want to send text
in arabic. So I have used the following syntax:
msg.setText(msgSend, "Windows-1256");
But I am not able to view the contents at the target address in arabic.
So what could be the possible error. Please advice.
Thanking you.

With Kind Regards,


Mustafa D.

Re: I have tried with my application ....


Author: Ravi Ramachandra
(http://www.jguru.com/guru/viewbio.jsp?EID=1144339), Feb 7, 2004
Hi, We are also facing similar problem in Arabic. We are using javamail for
composing and sending arabic messsags. We will appreciate if anybody could
send us code snippet for arabic messages. Thanks a lot in advance. Ravi

How can I get a list of newsgroups on my NNTP server?


Location: http://www.jguru.com/faq/view.jsp?EID=205467
Created: Sep 13, 2000 Modified: 2000-09-13 22:04:39.359
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The non-standard sun.net.nntp.NntpClient class lets you get this information.


import sun.net.nntp.*;
import java.io.*;

public class ListGroups {


public static void main(String args[]) throws Exception {
String server = args[0];
NntpClient nc = new NntpClient(server);
String line;
nc.serverOutput.println("list newsgroups");
BufferedReader br =
new BufferedReader(
new InputStreamReader(nc.serverInput));
while ((line = br.readLine()) != null) {
if (line.equals(".")) break;
System.out.println(line);
}
nc.askServer("QUIT");
nc.closeServer();
}
}

Where can I get the JavaMail example programs from Elliotte Rusty Harold's
2nd edition of Java Network Programming?
Location: http://www.jguru.com/faq/view.jsp?EID=205473
Created: Sep 13, 2000 Modified: 2000-09-13 22:13:16.916
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The last chapter of Elliotte's book covers JavaMail. You can get the examples from
http://www.ibiblio.org/javafaq/books/jnp2e/examples/19/.

What causes a "AXX NO Mailbox name is invalid" MessagingException?


Location: http://www.jguru.com/faq/view.jsp?EID=206226
Created: Sep 14, 2000 Modified: 2000-09-14 18:11:09.717
Author: Josephine Zhao (http://www.jguru.com/guru/viewbio.jsp?EID=202695)
Question originally posed by Josephine Zhao
(http://www.jguru.com/guru/viewbio.jsp?EID=202695

Make sure the getFolder() call has a valid/complete IMAP folder name.

The A part of the response is a counter for commands executed, that is why that
number changes.

What do all of the different abbreviations and acronyms (i.e., der, p7b,
p12/pfx, etc.) associated with S/MIME actually mean?
Location: http://www.jguru.com/faq/view.jsp?EID=211514
Created: Sep 20, 2000 Modified: 2000-09-20 19:12:04.721
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4) Question
originally posed by Evan Owens
(http://www.jguru.com/guru/viewbio.jsp?EID=123877

The canonical place to learn about S/MIME is directly from the IETF RFCs themselves.
S/MIME version 2 is in S/MIME Version 2 Message Specification and S/MIME Version
2 Certificate Handling. S/MIME version 3 is in S/MIME Version 3 Certificate Handling,
S/MIME Version 3 Message Specification, and Enhanced Security Services for
S/MIME.

How do I get a raw input stream of the message content?


Location: http://www.jguru.com/faq/view.jsp?EID=214065
Created: Sep 23, 2000 Modified: 2002-03-30 19:45:09.009
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
The getInputStream() method returns the content based upon the Content-Transfer-
Encoding header. Prior to the 1.2 API, there was no easy way to get the raw content.
The 1.2 version of the API introduces the getRawInputStream() method to get the
raw form of the content from the MimeMessage or MimeBodyPart class.

Where do I get a list of the JavaMail 1.2 API changes?


Location: http://www.jguru.com/faq/view.jsp?EID=214067
Created: Sep 23, 2000 Modified: 2000-09-23 21:00:09.946
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The http://java.sun.com/products/javamail/JavaMail-1.2-changes.txt file provides a


list of the new capabilities.

How does JavaMail handle thread management? Looks like by default, most
of the threads created by JavaMail while fetching the messages from a
Store/Folder object are not being released automatically. Do I need to
explicitely invoke any method so that these threads get released?
Location: http://www.jguru.com/faq/view.jsp?EID=214263
Created: Sep 23, 2000 Modified: 2000-09-23 21:47:33.747
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Shashidhar Mudigonda
(http://www.jguru.com/guru/viewbio.jsp?EID=100253

Closing the Folder, Store, or Transport should cause the thread to terminate itself
after delivering any pending events to listeners.

Using JavaMail, our Exchange Server sends mail fine internally, but doesn't
send mail externally. What could be the problem?
Location: http://www.jguru.com/faq/view.jsp?EID=224085
Created: Oct 6, 2000 Modified: 2000-12-13 13:25:21.262
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by justin whitehead
(http://www.jguru.com/guru/viewbio.jsp?EID=43079

The problem has to do with the relaying configuration of the mail server. You'll need
to talk to your mail admin to enable relaying.

How can I keep a copy of sent mails in my Netscape Mail folder?


Location: http://www.jguru.com/faq/view.jsp?EID=225020
Created: Oct 9, 2000 Modified: 2000-10-09 08:27:54.137
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by baskar arunachalam
(http://www.jguru.com/guru/viewbio.jsp?EID=91625

JavaMail knows nothing about your Netscape mail folder. There is no magic that
saves things there. If you want to save a copy, you have to build that in yourself. The
easiest way to do this is to just add yourself to the CC or BCC list of the message.

How can I log the debug messages to a file when I session.setDebug(true)?


Location: http://www.jguru.com/faq/view.jsp?EID=225934
Created: Oct 10, 2000 Modified: 2000-10-10 15:38:24.587
Author: Stefan Ritter (http://www.jguru.com/guru/viewbio.jsp?EID=217777)
Question originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

Don't how if it helps you, but I think it works.

1. Solution Start your program from a console with: java myProgramm >output.txt

Now all System.out's should by found in the file output.txt.

2. Solution You can also start your programm within the texteditor Textpad
(www.textpad.com) and all the outputs are automatically in a new document which
you can save to harddisk.

3. Solution Overwrite the OutputStream. Use something like


System.setOut(PrintStream myFileOutputStream)

What books are available for learning about the Internet Email protocols
and the JavaMail API?
Location: http://www.jguru.com/faq/view.jsp?EID=226205
Created: Oct 10, 2000 Modified: 2000-10-10 20:37:56.749
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

First, as far as the JavaMail APIs go, there is no book out dedicated to just that.
About the best coverage I've seen is the single chapter on the topic in Elliotte Rusty
Harold's 2nd edition of Java Network Programming.

As far as learning about the mail protocols, there are three available, and none are
too code centric.

• Programming Internet Email by David Wood from O'Reilly


• Programmer's Guide to Internet Mail by John Rhoton from Digital Press
• Internet Email Protocols: A Developer's Guide by Kevin Johnson from Addison
Wesley

How do I fire events when new messages arrive in my Inbox folder?


Location: http://www.jguru.com/faq/view.jsp?EID=232638
Created: Oct 20, 2000 Modified: 2000-10-20 06:35:32.546
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by vijay kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=232594

You can attach a MessageChangedListener to the folder. Then in the listener, the
public void messagesAdded(MessageCountEvent e) will be called when a message is
added and public void messagesRemoved(MessageCountEvent e) will be called when
deleted.

Now the bad news. This only works with IMAP, not POP3. With POP, messages can't
be added to the folder while its open.

Comments and alternative answers


Changed in 1.4
Author: Simon Pearce (http://www.jguru.com/guru/viewbio.jsp?EID=1102555), Jul
20, 2003
The folder method is addMessageCountChanged(MessageCountListener listener) in
version 1.4. So you implement a MessageCountListener.
And it doesn't seem to work for MS Exchange (albeit a locked down version).
Simon

How can I use JavaMail with a database?


Location: http://www.jguru.com/faq/view.jsp?EID=235890
Created: Oct 24, 2000 Modified: 2000-10-24 23:00:21.987
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by back hyejin
(http://www.jguru.com/guru/viewbio.jsp?EID=235836

There is nothing special about using the JavaMail API with a database. The database
accessing is completely separate from the JavaMail code. Get the information from
the database with JDBC. Create the message with JavaMail API. The two don't talk to
each other.

What causes an "javax.activation.UnsupportedDataTypeException: no object


DCH for MIME type xxx/xxxx javax.mail.MessagingException: IOException
while sending message;" to be sent and how do I fix this? [This happens for
known MIME types like text/html.]
Location: http://www.jguru.com/faq/view.jsp?EID=237257
Created: Oct 26, 2000 Modified: 2002-03-30 19:48:11.222
Author: Mauro Gagni (http://www.jguru.com/guru/viewbio.jsp?EID=32904) Question
originally posed by charles monica
(http://www.jguru.com/guru/viewbio.jsp?EID=13470

The Java Activation Framework used by JavaMail is not configured correctly.

It doesn't know how to handle the text/html content type.

An html handler is provided in JavaMail 1.1.3 but the mailcap file is not configured to
use it.

Add to your mailcap file the line:

text/html;; x-java-content-handler=com.sun.mail.handlers.text_html

and create a multipart message when sending html messages, otherwise it will not
be recognised as an HTML page from the client.

HTML messages does not cause this problem with the 1.2 release of the JavaMail
API.

Comments and alternative answers


Lotus Notes / Domino classloader rejects JavaMail agents
Author: Johan Känngård (http://www.jguru.com/guru/viewbio.jsp?EID=313126), Dec 13, 2002

The same error messages is produced when trying to run a JavaMail agent in Lotus Notes or
Domino, because the static initializer blocks of the default DataHandlers are not run correctly. The
problem can be avoided by adding the JAR files of the Java Activation Framework and the
JavaMail API to the JavaUserClasses in the notes.ini, like this:

JavaUserClasses=.;D:\Lotus\Notes\lib\activation.jar;D:\Lotus\Notes\lib\mail.jar;

I have another solution


Author: Frank Jorga (http://www.jguru.com/guru/viewbio.jsp?EID=1165554), Apr 23,
2004
Configuration didn't help me. Solution was much simpler make sure mail.jar and
activation.jar in your IDE Project and in jour Appserver are version matching and all
the same. I had some from JDK and some different version from Tomcat mixed in my
environmet. I scanned my drive and replaced all of them with the current sun version
and voila ...

Solution to javax.activation.UnsupportedDataTypeException
Author: Antoine Diot (http://www.jguru.com/guru/viewbio.jsp?EID=1174272), May
27, 2004
I had a problem with this exception when using Tomcat. I originally had mail.jar in
the /WEB-INF/lib/ folder and activation.jar in the common/lib/ folder. When I
put them in the same folder, the problem went away. Could be an issue with the order
in which they are loaded.

Its all about having the matching jars


Author: Jens Buehring (http://www.jguru.com/guru/viewbio.jsp?EID=1211606), Nov
18, 2004

As others wrote before me, this error is all about having the matching pair of mail.jar
and activation.jar.

At our application the problem was, we had a mail.jar in the /lib directory of our
application, but no matching activation.jar. At execution the Tomcat used its own
activation.jar which was obviously not the matching pair to our mail.jar. Therefore we
got the exception thrown at sending the mail.

The solution which worked in the end was:

• to download the newest versions of the jars,


• place them into the lib directory of our application,
• sort them to top-position in the build-order and rebuild the project.

Re: Its all about having the matching jars


Author: Austin Prichard-Levy
(http://www.jguru.com/guru/viewbio.jsp?EID=1219805), Jan 6, 2005
Actually, I beg to differ. I tried all the suggestions about matching jars, but still got
errors. In my case, I was using a custom Java wrapper class I developed for the
background processing of emails from Java apps when I encountered these issues
with unhandled MIME types, specifically "text/html" and "multipart/*".

For me, the initial solution was (as suggested in this forum at the outset) providing
for these types via the mailcap file (either external or located in the META-INF
folder of the distribution jar). However, I subsequently ended up adding the
following lines to my email wrapper class:

// add handlers for main MIME types


MailcapCommandMap mc =
(MailcapCommandMap)CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-
handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-
handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-
handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-
handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-
handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);

This works fine, and keeps all the relevant dependencies in one place, so I know it
will always work irrespective of the overall Java app configuration. Another reason
was speed, as the following excerpt from the relevant javadoc proves:

(http://java.sun.com/j2ee/1.4/docs/api/javax/activation/MailcapCommandMap.html)

The MailcapCommandMap looks in various places in the user's system for mailcap
file entries. When requests are made to search for commands in the
MailcapCommandMap, it searches mailcap files in the following order:

1) Programatically added entries to the MailcapCommandMap instance.


2) The file .mailcap in the user's home directory.
3) The file <java.home>/lib/mailcap.
4) The file or resources named META-INF/mailcap.
5) The file or resource named META-INF/mailcap.default (usually found only in the
activation.jar file).

This means that the programmatic route is the fastest to execute. Any better reason
needed?! :-)

HTH Austin

What is a FileDataSource?
Location: http://www.jguru.com/faq/view.jsp?EID=237612
Created: Oct 26, 2000 Modified: 2000-10-26 10:08:07.138
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Chandra Prasad Reddy
(http://www.jguru.com/guru/viewbio.jsp?EID=231859

A FileDataSource is part of the JavaBeans Activation Framework, package


javax.activation. It represents a DataSource associated with a file, that relies on a
FileTypeMap to associate mime types with file extensions. They can be used to send
file attachments:
MimeBodyPart messageBodyPart =
new MimeBodyPart();
DataSource source =
new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(
new DataHandler(source));
messageBodyPart.setFileName(
filenameString);

The other type of predefined DataSource in the Activation Framework is the


URLDataSource.

Is there anything special about sending mail with JavaMail when using EJB?
Location: http://www.jguru.com/faq/view.jsp?EID=240549
Created: Oct 30, 2000 Modified: 2002-03-30 19:49:27.279
Author: Tim Rohaly (http://www.jguru.com/guru/viewbio.jsp?EID=10) Question
originally posed by vini vipin (http://www.jguru.com/guru/viewbio.jsp?EID=239441

The javax.mail libraries are a standard part of of J2EE, so the whole API is there.
Even the JavaBeans Activation Framework is there, which is required by JavaMail.
However, you're only allowed to send mail, not receive.

With J2EE, you are required to obtain the javax.mail.Session instance from a JNDI
lookup rather than creating it yourself, but other than that it's the same as sending
mail using JavaMail from a standalone app.

You can look at the Java Pet Store example, which does this.
Also, see What does this messaging exception mean:
javax.mail.NoSuchProviderException:
No provider for Address type: rfc822

I am running a Weblogic on a Sun...

Comments and alternative answers

With Weblogic Server 5.1, I have seen an implementation...


Author: Kian Hui Teo (http://www.jguru.com/guru/viewbio.jsp?EID=64456), Oct 31,
2000
With Weblogic Server 5.1, I have seen an implementation of a mail bean before.
Basically, just remember to include the mail.jar inside the weblogic classpath setting
if you are using service pack 5 and below.

You will also need to configure a smtp host for sending out your mail. You can set this
inside your weblogic.properties file. Actual documentations on this can be found on
the weblogic documentation website at http://www.bea.com Currently, the mail bean
has already been implemented on production systems and working fine.

How do I create two MimeMessage objects and attach the second


MimeMessage to the first MimeMessage? When the mail is received the mail
should have an attached email. The attached email should contain "from,to,
subject, content" of the 2nd MimeMessage.
Location: http://www.jguru.com/faq/view.jsp?EID=242307
Created: Nov 1, 2000 Modified: 2000-11-01 06:54:27.837
Author: Benjamin Chi (http://www.jguru.com/guru/viewbio.jsp?EID=232856)
Question originally posed by Benjamin Chi
(http://www.jguru.com/guru/viewbio.jsp?EID=232856

See code below. The significant part is using the header "message/rfc822" and
passing the Message object to the setContent() method:

MultiBodyPart.setContent(Message, "message/rfc822");

=========== Code Example. ===============


Message aMsg = // Populate this Message obj.
MimeMultipart mmp = new MimeMultipart();

// First part: Contents


MimeBodyPart mbp = new MimeBodyPart();
mbp.setText(aText);
mmp.addBodyPart(mbp);

// Second Part: Attachments


MimeBodyPart mbp2 = new MimeBodyPart();
// mimetype as forwarded attachment
mbp2.setContent(aMsg, "message/rfc822");
mmp.addBodyPart(mbp2);
======================================
How do I receive an acknowledgement that a user has received my
message?
Location: http://www.jguru.com/faq/view.jsp?EID=242335
Created: Nov 1, 2000 Modified: 2000-12-21 21:56:29.639
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

There is an SMTP extension that supports Delivery Status Notifications (DSN) defined
in RFC 1891. This may or may not be supported by the user's Mail Transport Agent
(MTA).

To receive the acknowledgements, you'll need to set two properties in the Properties
passed on when getting a Session. These are "mail.smtp.dsn.notify" and
"mail.smtp.dsn.ret". The first specifies where it goes and the second what you want.

props.put("mail.smtp.dsn.notify",
"SUCCESS,FAILURE ORCPT=rfc822;recip@foo.bar");
props.put("mail.smtp.dsn.ret", "HDRS");

For a full description of the meaning see the RFC. If you want the full message sent
back to you, use FULL instead of HDRS. recip@foo.bar is meant to the original
recipient of the email.

Be sure to change the address to send the acks to a more appropriate email.

These acks are not about when the user reads the message, only acknowledging
receipt of the message by their mail server. Its possible the mail server throws the
message away as spam for instance and the end user never actually gets the
message in their mailbox.

Another option, though something that can be ignored by the mail client / user is
setting the "Disposition-Notification-To" header to the email you'd like to send the
notification to:

message.setHeader(
"Disposition-Notification-To",
"billg@microsoft.com");

How do you force the encoding of a file attachment?


Location: http://www.jguru.com/faq/view.jsp?EID=245743
Created: Nov 5, 2000 Modified: 2000-11-06 09:13:01.216
Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708)
Question originally posed by christopher roth
(http://www.jguru.com/guru/viewbio.jsp?EID=3072

You can do following:

1. Write your own DataSource implementation that returns type, name, and an
InputStream that will read from an already encoded byte array (i.e. a
ByteArrayInputStream). See javax.activation.DataSource API for
information about the DataSource interface, and the ByteArrayDataSource
class that is one of the distribution's examples.
2. Create the array holding the encoded data (here mime base64):
3. InputStream in=new FileInputStream(file);
4. ByteArrayOutputStream bout=
5. new ByteArrayOutputStream();
6. OutputStream out=
7. MimeUtility.encode(bout,"base64");
8.
9. int i=0;
10.while((i=in.read())!=-1) {
11. //maybe more efficient with a buffer
12. //this is just demonstrative
13. out.write(i);
14.}
15.out.flush();
16.out.close();
17. Set the name, type and the byte array (or pass it on construction).
18.EncodedDataSource encds=
19. new EncodedDataSource(contenttype,
20. filename, bout.toByteArray());
21. Add the header of the encoding and a the DataHandler to a
MimeBodyPart(mbp):
22.mbp.addHeader("Content-Transfer-Encoding","base64");
23.mbp.setDataHandler(new DataHandler(encds));

The above will work, yet, as far as I realized binary parts of mail sent are encoded
anyway.

Comments and alternative answers

Do you really need the custom DataSource impl?


Author: Craig Longman (http://www.jguru.com/guru/viewbio.jsp?EID=314597), May
3, 2001

I was having trouble sending an RTF file and getting it to be base64 encoded. because
an RTF file looks mostly like regular ASCII text, the default DataSource impl was, in
fact, insisting on encoding it as 7bit. Although this works for most cases, the fax-
server I was mailing to seemed to insist on base64 encoded attachments.

So, after reading this FAQ, I started work on my own DataSource. However, I quickly
got frustrated and started looking into what was going on and how the decision to use
7bit instead of base64 was made. I knew it was capable of sending base64 encoded
attachments, as GIFs were encoded base64. I noticed that before the email was
actually sent, the getEncoding() method would always return null. And it did that for
both RTF and GIF attachments. So, after more looking, the only way I could find to
indicate what encoding I wanted was to use the setHeader() method, why the heck
isn't there a simply setEncoding() method? or setPreferredEncoding()!!???

Anyway, the following code works well for me. If I exclude the
messageBodyPart.setHeader() call, then the RTF is 7bit encoded, but with the call, it
is base64 encoded:

Properties props = new Properties();

props.put( "mail.host", "mx.domain.com" );

Session session = Session.getDefaultInstance( props, null );


Message message = new MimeMessage( session );
Multipart multipart = new MimeMultipart();
MimeBodyPart bodyPart = new MimeBodyPart();

bodyPart.setText( body );
multipart.addBodyPart( bodyPart );

bodyPart.setDataHandler( new DataHandler( new FileDataSource(


attachFile ) ) );
bodyPart.setFileName( attachFile.getName() );
// requests (forces?) base64 instead of default
bodyPart.setHeader( "Content-Transfer-Encoding", "base64" );
multipart.addBodyPart( bodyPart );

message.setContent( multipart );

Transport.send( message );

How do I get the value of a specific header, delivered-to, and the list of all
headers present?
Location: http://www.jguru.com/faq/view.jsp?EID=245745
Created: Nov 5, 2000 Modified: 2000-11-06 09:09:41.557
Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708)
Question originally posed by chandrakaladhar reddy
(http://www.jguru.com/guru/viewbio.jsp?EID=232598

The javax.mail.MimeMessage API doc shows you how to achieve this:

1. String[] delto=msg.getHeader("delivered-to");
The array will contain all present values as Strings.
2. Enumeration enum=msg.getAllHeaders();
The enumeration will contain all present headers as javax.mail.Header
objects.

What are the restrictions / limitations for adding custom, user-defined


headers?
Location: http://www.jguru.com/faq/view.jsp?EID=246463
Created: Nov 6, 2000 Modified: 2000-11-07 05:21:24.631
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
User-defined header names can consist of only printable ASCII characters, excluding
the colon. They should start with an "X-", but there is no strict requirement that they
do.

For example, the following would add a custom header to a message:

message.addHeader("X-FAQs",
"http://www.jguru.com/faq");

How can I send an attachment without having to use a physical file?


Location: http://www.jguru.com/faq/view.jsp?EID=248031
Created: Nov 7, 2000 Modified: 2000-11-08 06:56:07.377
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by KIM DUONG
(http://www.jguru.com/guru/viewbio.jsp?EID=247389

Instead of using FileDataSource, create a custom DataSource. You can find a


ByteArrayDataSource example of this in the demo directory that comes with
JavaMail.
Comments and alternative answers

Alternative solution
Author: Bas Gooren (http://www.jguru.com/guru/viewbio.jsp?EID=751897), Feb 8,
2002
I work with an application that does not know what kind of attachment it will get. Can
be binary/text, pdf/txt/doc/etc. The attachments come from a database. To deal with
this in an easy way, what I did is this:
String data_from_db = ...(get from db)
String att_type = ...(get from db)
MimeBodyPart att = new MimeBodyPart()
att.setText(data_from_db);
att.setHeader("Content-Type", att_type);
att.setHeader("Content-Transfer-Encoding", "base64");
att.setHeader("Content-Disposition", "attachment");
att.setFileName(filename_from_db);

// etc...add it to the MimeMultiPart object and send it.

What is the best way to launch the default e-mail editor from a Java
Application. Can a new message be automatically sent to the editor?
Location: http://www.jguru.com/faq/view.jsp?EID=250044
Created: Nov 9, 2000 Modified: 2000-11-10 10:14:35.843
Author: Serge Knystautas (http://www.jguru.com/guru/viewbio.jsp?EID=100012)
Question originally posed by Jon Drury
(http://www.jguru.com/guru/viewbio.jsp?EID=47899

There is no standard way to launch the default e-mail editor from a Java Application.
If you were in a Java Applet, you could leverage the showDocument() method of
AppletContext and pass it a mailto: protocol. If you could do this, in addition to
specifying the target, you could specify the initial subject and body with command
line parameters, e.g.,
mailto:address@domain.com?subject=My%20Subject&body=The%20body%20of%20m
y%20message.

Again however, there is no standard way to launch an external application like an e-


mail editor from a Java Application. If you want to check that you are running in
Windows 95/98/NT/2k, you could access the Runtime object and use its exec()
method to run start mailto:address@domain.com?subject=...... This OS-
specific command instructs Windows to open the default e-mail editor and create a
new message with the given destination and subject.

How do I remove an attachment from a MimeMessage? If I use


getContent().getParent().removeBodyPart(BodyPart part) is seems to work,
but when I write the MimeMessage to harddisk with writeTo(OutputStream)
the attachments are still in the textfile. What am I doing wrong?
Location: http://www.jguru.com/faq/view.jsp?EID=251520
Created: Nov 11, 2000 Modified: 2000-11-16 08:47:54.928
Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708)
Question originally posed by Stefan Ritter
(http://www.jguru.com/guru/viewbio.jsp?EID=217777

You start with a reference to a MimeMessage. Then you get its content, which will be
a reference to a MimeMultipart instance. Next you get its parent again, which leaves
you with the reference to the MimeMessage you started from. I wonder why there is
no MessagingException thrown if you try to remove a MimeBodyPart that is part of
the MimeMultipart instance, but at least it should return false (which tells you it did
not work out).
Here is a piece of code that should do the job:
//suppose you have a reference to a MimeMessage
//called myMessage

MimeMultipart mmp=(MimeMultipart)myMessage.getContent();

//now a loop over its body parts


for(int i=0; i<getCount(); i++) {
MimeBodyPart mbp=(MimeBodyPart)mmp.getBodyPart(i);
if(hasToBeRemoved(mbp)) {
mmp.removeBodyPart(i);
//this will shift all parts down so:
//the index of the loop needs correction
i--;
}
}

//if you want to persist that new state


myMessage.saveChanges();
//Note: only works if the folder is opened READ_WRITE !

[...]

private boolean hasToBeRemoved(MimeBodyPart mbp) {

//check according to your criteria


//and return true or false

}//hasToBeRemoved

Comments and alternative answers

Removing Body Parts


Author: Troy Shelton (http://www.jguru.com/guru/viewbio.jsp?EID=493342), Nov
14, 2001
In addition to Dieter Wimberger's answer, one needs to add one more line of code to it
in order to actually write the message to a file with the body part removed.
// Working Code Sample

if (mm.isMimeType("text/plain")) {
catalog.setMsgText((String)mm.getContent());
} else if (mm.isMimeType("multipart/*")) {
mmp=(MimeMultipart)mm.getContent();
for (int i = 0; i < mmp.getCount(); i++) {
BodyPart part = mmp.getBodyPart(i);
if (hasToBeRemoved(part)) {
mmp.removeBodyPart(i);
i--;
} // +++++ end of if (hasToBeRemoved(part))
} // +++++ end of for (int i = 0; i < mmp.getCount(); i++)

// Sets the Message's content.


mm.setContent(mmp);
mm.saveChanges();

// End of Working Code Sample

How can I read a message with Content-transfer-encoding header 8 bit


using JavaMail 1.1.3?
Location: http://www.jguru.com/faq/view.jsp?EID=251523
Created: Nov 11, 2000 Modified: 2000-11-16 08:09:00.321
Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708)
Question originally posed by Miguel Angel Medina Lopez
(http://www.jguru.com/guru/viewbio.jsp?EID=248565

According to the API Specification, 8bit is supported, because its part of the RFC2045
specification.
The MimeUtility.decode(java.io.InputStream is, java.lang.String
encoding) method should help you to "read" parts of the message.
The following code might help or at least give an idea:
//assume you have a MimeBodyPart mbp
InputStream in=mbp.getInputStream();
String[] encoding=mbp.getHeader("Content-Transfer-Encoding");
if(encoding!=null && encoding.length>0){
in=MimeUtility.decode(in,encoding[0]);
}

//use the Stream in to read from...


Note that it will retrieve the encoding from the header, so it should work for all
supported encodings.
Comments and alternative answers

8bits and 8bit


Author: Pengyu Zhu (http://www.jguru.com/guru/viewbio.jsp?EID=404670), Apr 17,
2001
By default, getContent() will return decoded text. But,some mail server will put 8bits
instead of 8bit. Javamail will throw exception when encoding is "8bits". In that case,
you will have to decode the message by yourself, force using "8bit".

Does the SmtpClient class support sending mail to mulitple recipients, like
with CC?
Location: http://www.jguru.com/faq/view.jsp?EID=255297
Created: Nov 16, 2000 Modified: 2000-11-16 07:11:29.609
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Jane Ng (http://www.jguru.com/guru/viewbio.jsp?EID=112489

There is no concept of CC'ing anyone. However, you can have a comma delimited list
in the to field.

String to = "foo1@bar.com, foo2@bar.com";


SmtpClient smtp = new SmtpClient(host);
smtp.from(from);
smtp.to(to);

How to deploy a servlet that includes javax.mail.* on Tomcat?


Location: http://www.jguru.com/faq/view.jsp?EID=259166
Created: Nov 21, 2000 Modified: 2000-11-21 07:12:13.22
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Zuofeng Zeng
(http://www.jguru.com/guru/viewbio.jsp?EID=240547

Just place the mail.jar and activation.jar files (and possibly the pop.jar file if you are
using POP3) in the CLASSPATH of the web server. The simplest way to do this is to
rely on the Java extensions framework. Add them to the JAVA_HOME/jre/lib/ext
directory. Just copy the files there. Otherwise, set the CLASSPATH environment
variable before starting Tomcat. The startup scripts retain the existing CLASSPATH,
adding the Tomcat-specific stuff to the end.

See What do I need to acquire in order to get started with JavaMail? to see where to
get these files.

Comments and alternative answers

Application-divided JavaMail providers


Author: Eugene Kuleshov (http://www.jguru.com/guru/viewbio.jsp?EID=442441),
Nov 19, 2001
To make JavaMail providers available only for the concrete applications you can add
those jar's into particular WEB-INF/lib folder.

Where do I get the POP3 provider for use with JavaMail 1.2?
Location: http://www.jguru.com/faq/view.jsp?EID=261551
Created: Nov 23, 2000 Modified: 2000-11-23 21:11:57.71
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The POP3 provider is now included with the 1.2 release. Finally, you no longer need
to get it separately.

How to sort the messages in JavaMail?


Location: http://www.jguru.com/faq/view.jsp?EID=266225
Created: Nov 30, 2000 Modified: 2000-11-30 09:31:57.594
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by guan ho (http://www.jguru.com/guru/viewbio.jsp?EID=126860

Within the JavaMail classes there is no support for this. However, once you get the
array of messages back from a folder, you can call the Arrays.sort() method in the
collections framework to sort the messges. Since MimeMessage doesn't implement
Comparable, you'll need to provide your own Comparator specifying how you want
the messages to be sorted.
Comments and alternative answers

Could you post some example code on this....?


Author: Kevin Baker (http://www.jguru.com/guru/viewbio.jsp?EID=882634), Oct 9,
2002
Could you post some example code on this....?

Re: Could you post some example code on this....?


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Oct 9,
2002
The Compartor interface requires you to implement the compareTo method, which
accepts two args (the messages to compare for here). Compare the two fields of
the message you want to sort by. If message1 comes first, return -1, if equal, return
0, if message2 comes first, return 1.

How can I create a folder on my mail server?


Location: http://www.jguru.com/faq/view.jsp?EID=266420
Created: Nov 30, 2000 Modified: 2000-11-30 20:22:01.063
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by manash ray
(http://www.jguru.com/guru/viewbio.jsp?EID=266333

First, POP3 doesn't support folders so if you are using POP3, then forget it, can't be
done. If you are using IMAP, just call the create() method of Folder after naming the
Folder object by calling the constructor with the name.
How do I store messages locally using JavaMail? provides information about storing
messages locally.

How do I display the image sent as an attachment with the mail in JSP while
retrieving the mails?
Location: http://www.jguru.com/faq/view.jsp?EID=268259
Created: Dec 3, 2000 Modified: 2000-12-03 20:18:09.615
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Amit Kaushik
(http://www.jguru.com/guru/viewbio.jsp?EID=50383

If the message came across as text/html content, just send the HTML out as the
output of the JSP request. All the different IMG tags will make separate requests to
the server to display the images.

The only real problem is if the images come across with the JavaMail message and
have a URL that begins with a cid: URL (as demonstrated in How do you send HTML
mail with images?). If that is the case, then you deal with sending the image yourself
(and saving it locally). You can try to create a protocol handler for cid, but I think
the best way is to convert the URL into one that is handled by default, like any other
image, with an HTTP request.

How do I move messages between folders?


Location: http://www.jguru.com/faq/view.jsp?EID=268755
Created: Dec 4, 2000 Modified: 2000-12-04 05:49:38.48
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by shams Tabrez
(http://www.jguru.com/guru/viewbio.jsp?EID=264911

First, if you are using POP, you can't. There is only one folder, the INBOX.

If you happen to be using IMAP, the way to move messages between folders is with
the appendMessages() or the copyMessages() method of Folder. In either case, you
would need to delete the message from the original folder yourself.

How can I set the transfer encoding type??? I wish to send an HTML mail
using MimeMessage class and encode it to "base64". but I couldn't set the
Content-Transfer-Encoding value of mail header.
Location: http://www.jguru.com/faq/view.jsp?EID=268864
Created: Dec 4, 2000 Modified: 2000-12-14 17:36:31.691
Author: marx0207 wang (http://www.jguru.com/guru/viewbio.jsp?EID=268565)
Question originally posed by Jae Cheol Kim
(http://www.jguru.com/guru/viewbio.jsp?EID=265863

Encode the Html in "Base64", for example:


String Html="<html><body>"+
"this is a test"+
</body></html>";
MimeMessage msg =new MimeMessage();
String DefaultCharSet=
MimeUtility.getDefaultJavaCharset();
msg.setText(MimeUility.encodeText(Html,DefaultCharSet,"B"));
msg.send();
Q short for Quoted Printable
B short for Base64

<explain>

I use MimeUtility.encodeText(,,) for encode process, you could use that method
encode your HTML string in "B"--Base64 and be set on the message part.

for details check in JavaMail Api javax.mail.internet.Mimeutility section.

Comments and alternative answers

perhaps fixed in a new version of JavaMail?


Author: Craig Longman (http://www.jguru.com/guru/viewbio.jsp?EID=314597), May
3, 2001

The following worked for me:

Properties props = new Properties();

props.put( "mail.host", "mx.domain.com" );

Session session = Session.getDefaultInstance( props, null );

Message message = new MimeMessage( session );

message.setFrom( InternetAddress.parse( "<name@domain.com>" )


[0] );
message.setSubject( "test" );
message.setSentDate( new Date() );
message.addRecipients( Message.RecipientType.TO,
InternetAddress.parse( "<name@domain.com>" ) );

message.setText( body );
message.setHeader( "Content-Transfer-Encoding", "base64" );

Transport.send( message );

Notice that the message.setHeader() call is after the setText() call. This is critical, if
you call setHeader() before you call setText(), then the message is still sent as 7bit
encoded.

One last point, if you try this at home, you will probably find that the email that
arrives is encoded as 7bit or probably 8bit. This is because most email servers, when
they see a base64 encoded, non-multipart email, will automatically convert the email
to a different format, normally 8bit. However, you should be able to verify that it
arrived as base64 by examining the headers and see what the server did to the email
before delivering it. Any decent email server should put headers in explaining any
modifications that were made to the email contents. My email server adds this:

X-MIME-Autoconverted: from base64 to 8bit by mx.domain.com id


MAA17541

How can I set the timeout length for the different SMTP, IMAP, and POP
connections?
Location: http://www.jguru.com/faq/view.jsp?EID=270916
Created: Dec 6, 2000 Modified: 2000-12-06 16:56:00.159
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The JavaMail 1.2 API adds a system property


mail.{smtp,imap,pop3}.connectiontimeout to add this capability. Prior to 1.2, you
couldn't do this.

How do I restrict the size of the Mail attachment to be sent? For example, I
want to sent a document only if its size less <= 300K.
Location: http://www.jguru.com/faq/view.jsp?EID=275027
Created: Dec 11, 2000 Modified: 2000-12-11 10:47:29.372
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Ram Prasad.K
(http://www.jguru.com/guru/viewbio.jsp?EID=108201

When creating the mail message to send, check the size of the attachment before
'attaching'. If it is too large, don't attach it. There is nothing that is part of the
JavaMail API to limit this for you, though you're SMTP server might reject the
message if too large.

Keep in mind that the attachment size is the 7-bit encoded size, not necessarily the
original 8-bit encoded size. The Part interface has a getSize() method so you can find
out its size.

How do I send e-mail through Oracle triggers?


Location: http://www.jguru.com/faq/view.jsp?EID=276261
Created: Dec 12, 2000 Modified: 2000-12-13 00:32:53.091
Author: Mark Bradley (http://www.jguru.com/guru/viewbio.jsp?EID=276260)
Question originally posed by Rajagopalan Varadarajan
(http://www.jguru.com/guru/viewbio.jsp?EID=273011

A good set of responses I've seen is from the Oracle Magazine. From there select the
"Ask Tom" column. You can search his articles for "JavaMail" or just "mail". It has
responses for Oracle 8i and previous releases. Versions prior to 8.1.5 rely on Oracle
packages instead of Java.

The questions and answers on that page are, naturally, heavily Oracle-specific!

It describes a way to load the activation.jar and mail.jar files (which cannot be
compressed) into the database using the "loadjava" program.
There is Java and PL/SQL sample code which supports attachments using BLOBs. It
has the repackaged JAR files.

You will need to modify the code to handle your specific needs. Load this code, then
just call the PL/SQL function from the trigger.

How can I get email addresses out of an MS Outlook database, and add
knew ones?
Location: http://www.jguru.com/faq/view.jsp?EID=276923
Created: Dec 13, 2000 Modified: 2000-12-13 11:50:41.384
Author: Jorge Jordão (http://www.jguru.com/guru/viewbio.jsp?EID=275762)
Question originally posed by nitin dubey
(http://www.jguru.com/guru/viewbio.jsp?EID=249436

You can access MS Outlook via a Java-COM bridge, and use the Outlook COM
interface variables and methods in your Java program.
I know 2 products that can help you with that:

• JIntegra, which is commercial


• JACOB, which is open-source

Accessing a Microsoft Exchange server with just my username doesn't let


me read my mail, what's wrong?
Location: http://www.jguru.com/faq/view.jsp?EID=277179
Created: Dec 13, 2000 Modified: 2000-12-13 13:17:54.505
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

This seems to be an issue when NT authentication is enabled. If your username is


foo, your mailbox name is Foo.Bar and your server is FUBAR, your username for
connecting to your mailbox is not foo. Instead, it would be
FUBAR\foo\Foo.Bar

Where can I find all of the RFCs related to e-mail?


Location: http://www.jguru.com/faq/view.jsp?EID=283013
Created: Dec 20, 2000 Modified: 2000-12-20 15:43:10.852
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

The Internet Mail Consortium maintains a page which lists and tracks all of the IETF
Requests for Comments (RFCs) related to internet mail standards.

Comments and alternative answers

RFC Website
Author: Mohammad Khan (http://www.jguru.com/guru/viewbio.jsp?EID=419921),
May 11, 2001
Please goto this website for your answers: http://www.rfc-editor.org/.

Where can I find all of the RFCs for securing email?


Location: http://www.jguru.com/faq/view.jsp?EID=283018
Created: Dec 20, 2000 Modified: 2000-12-20 13:30:03.284
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

The Internet Mail Consortium maintains a list of all of the internet mail RFCs and part
of that page is a section on Message and Transmission Security. That section covers
MIME, S/MIME, Diffie-Hellman, LDAP, PKCS, MD5, CAST, RC2, TLS, SMTP, IMAP,
POP3, SASL, PEM, PGP, OpenPGP, SecureID, CMS, Skipjack, etc.

Where can I find a free, Java implementation of OpenPGP?


Location: http://www.jguru.com/faq/view.jsp?EID=284603
Created: Dec 22, 2000 Modified: 2000-12-22 14:34:08.872
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Well, a first cut has been made in the Cryptix OpenPGP package.

What is OpenPGP?
Location: http://www.jguru.com/faq/view.jsp?EID=284604
Created: Dec 22, 2000 Modified: 2000-12-22 17:14:38.335
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

OpenPGP is an IETF specification for a standard, completely open PGP (Pretty Good
Privacy). OpenPGP is defined in RFC 2440 as providing "data integrity services for
messages and data files" via encryption (symmetric and asymmetric), digital
signatures, compression, radix-64 (aka ASCII armoring), and certificate and key
mangement services.

What OpenPGP solutions are available?


Location: http://www.jguru.com/faq/view.jsp?EID=284612
Created: Dec 22, 2000 Modified: 2000-12-22 14:36:27.861
Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Commercially: Network Associate's PGP Security

Free for non-commercial use: PGP Freeware

Free:

• GNU Privacy Guard (gnupg)


• Cryptix OpenPGP

Does the JavaMail API provide any facility to create an Address book, so
that address lookup can be developed?
Location: http://www.jguru.com/faq/view.jsp?EID=288191
Created: Dec 28, 2000 Modified: 2000-12-28 14:23:34.15
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Shankar GS
(http://www.jguru.com/guru/viewbio.jsp?EID=287967

There is no capabilities for creating or accessing an address book as part of the


JavaMail API.
If you were interested in creating your own, consider using JDBC, property files, or
some other mechanism to create / access an address book. Using JNI/COM to access
an Outlook address book is another option, but then your program won't work on
Linux, Solaris, or most other non-Windows machines.

How can I specify where bounce messages should go, if I don't want them
to come back to the from/replyTO field?
Location: http://www.jguru.com/faq/view.jsp?EID=289446
Created: Dec 29, 2000 Modified: 2000-12-29 18:44:50.981
Author: Ellen Spertus (http://www.jguru.com/guru/viewbio.jsp?EID=289445)
Question originally posed by balasundar ramammorthi
(http://www.jguru.com/guru/viewbio.jsp?EID=283122

Bounce messages (and other errors) are sent to the SMTP FROM (also called
ENVELOPE FROM) attribute, not the MESSAGE FROM attribute, which is what is set
with Message.setFrom(). You can set the SMTP FROM as follows:

Properties props = System.getProperties();


props.put("mail.smtp.from", "bouncer@foo.com");
If you do not provide a value for SMTP FROM, the MESSAGE FROM value is used.

See also Sun's JavaMail FAQ.

Comments and alternative answers

To be clear, the question implies something that is...


Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4), Dec 29,
2000

To be clear, the question implies something that is imprecise (if not incorrect)...
Bounce messages are sent to the mail's envelope return path (ERP) address. The ERP
is specified in the MAIL FROM SMTP command.

Yes, that's often the same address as the message body's From: field but they are by
no means required to be the same. For example, mailing list programs often specify
the ERP as a special, list specific address... Sometimes it's the list owner's alias but,
good mailng list programs such as ezmlm use a trick called VERP (Variable Envelope
Return Path) wherein every messsage is sent to each user using a different ERP.
Therefore, any bounce messages to the VERPs directly identify the problem
subscriber address. Ezmlm can use that information to do things like automatically
unsubscribe bad addresses. Obviously, to implement VERPs requires a bit of tracking
and the cooperation between the mailing list programs and the MTA. In this particular
case, ezmlm only works with qmail.

How do I determine what my SMTP server name is?


Location: http://www.jguru.com/faq/view.jsp?EID=296352
Created: Jan 8, 2001 Modified: 2001-01-08 05:22:44.089
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Vishnu Kumar Prasad
(http://www.jguru.com/guru/viewbio.jsp?EID=296273

If you are in a corporate environment, you would ask the IT support group for your
company. For individuals (usually from home), you should have received this
information from your ISP.

In either case, if you are already sending and receiving mail from a mail tool like
Outlook, Eudora, pine... , you should already have this information configured in your
mail tool and can just copy the information from that setup.

In many cases, it is just prefixing smtp with your domain. If your domain was
microsoft.com, a good guess at the server might be smtp.microsoft.com.

Comments and alternative answers

For an automated guess first find the URL of your ...


Author: Mark Thornton (http://www.jguru.com/guru/viewbio.jsp?EID=276034), Jan
8, 2001
For an automated guess first find the URL of your machine (via getLocalHost()) and
then use DNS (with a JNDI DNS provider) to look for MX records which should give
the mail server address if one exists. If you don't find one, take off the first part of the
domain name and repeat. So if your machine was fred.microsoft.com, first search for
an MX record associated with fred.microsoft.com, and then search microsoft.com.
While this may not work, system administrators could easily configure DNS servers
so that it did.

If we use a web-based email provider like Yahoo Mail, how can we find out
what the SMTP / POP server is to get / send mail from JavaMail?
Location: http://www.jguru.com/faq/view.jsp?EID=296361
Created: Jan 8, 2001 Modified: 2004-01-08 06:05:50.354
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by zameer sait
(http://www.jguru.com/guru/viewbio.jsp?EID=296265

To find out the SMTP and POP servers for a web-based email provider, you need to
search through the Help docs for the provider for this information to see if they even
support it. For instance, for Yahoo Mail, help is available through their Help Desk.
Specifically, How do I configure my POP3 email client to send and receive Yahoo! Mail
messages? answers your questions. Other providers should have similar help
available.

Specifically for Yahoo, the POP server is pop.mail.yahoo.com and the SMTP server is
smtp.mail.yahoo.com. You must enable POP Access & Forwarding from their Options
screen before being able to get your messages remotely.

You cannot enable this feature w/o upgrading to a fee-based access account.
How do you display an attachment file using the JavaMail package?
Location: http://www.jguru.com/faq/view.jsp?EID=298713
Created: Jan 10, 2001 Modified: 2001-01-10 07:43:09.455
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Maher Arif
(http://www.jguru.com/guru/viewbio.jsp?EID=289570

The JavaMail API provides no mechanism to display attachments. It is up to you to


decide how you want to display something.

For instance, if your attachment is a Microsoft Word file, and you happen to be on a
Windows box, you can use Runtime.exec() to fork off a process to display the file in
Microsoft Word. If your attachment is a text file, you can put the contents in a read-
only JTextArea. Either way, how to display is outside the realm of the JavaMail API.

How do you mark a message as read?


Location: http://www.jguru.com/faq/view.jsp?EID=305942
Created: Jan 18, 2001 Modified: 2001-01-18 14:57:47.154
Author: Tom Copeland (http://www.jguru.com/guru/viewbio.jsp?EID=1396)

First of all, you can't mark a message as read if you are using a POP3 server - the
POP3 protocol doesn't support that. However, the IMAP v4 protocol does.

You might think the way to do this is to get the message, set the Flags.Flag.SEEN
flag to true, and then call message.saveChanges(). Oddly, this is not the case.

Instead, the JavaMail API Design Specification, Chapter 4, section "The Flags Class"
states that the SEEN flag is implicitly set when the contents of a message are
retrieved. So, to mark a message as read, you can use the following code:

myImapFolder.open(Folder.READ_WRITE);
myImapFolder.getMessage(myMsgID).getContent();
myImapFolder.close(false);
Comments and alternative answers

To mark a message as read the JavaMail specification...


Author: Tom Copeland (http://www.jguru.com/guru/viewbio.jsp?EID=1396), Feb 20,
2001
To mark a message as read the JavaMail specification says that the client has to get
the content of the message. The first answer to this FAQ - ie, open the folder, get the
message and call Message.getContent(), and close the folder - works fine unless there
are attachments to the message. If that's the case, the client has to go recursing
through the content of the message, testing each Part to see if it's a Multipart, and, if
so, reading it and all its Parts.

The code below correctly handles email with attachments:

// other code...
javax.mail.Folder folder = _store.getFolder(folderName);
folder.open(Folder.READ_WRITE);
javax.mail.Message msg =
folder.getMessage(Integer.valueOf(msgNum).intValue());
Object content = msg.getContent();
if (content instanceof Multipart) {
readAndDiscardMultipart((Multipart)content);
}
folder.close(false);
// other code...

private void readAndDiscardMultipart(Multipart mp)


throws MessagingException, IOException {
for (int i=0; i<mp.getCount(); i++) {
BodyPart bodyPart = mp.getBodyPart(i);
Object content = bodyPart.getContent();
if (content instanceof Multipart) {
readAndDiscardMultipart((Multipart)content);
}
}
}

Another quick way to get the SEEN flag set..


Author: Drew Farris (http://www.jguru.com/guru/viewbio.jsp?EID=259441), Feb 6,
2002
.. is to use the MimeMessage copy constructor, ie:
MimeMessage source = (MimeMessage) folder.getMessage(1)

MimeMessage copy = new MimeMessage(source);


when you construct the copy, the seen flag is implicitly set for the message referred to
by source.

How can use the JavaMail API to access MS Exchange servers that are using
NTLM with POP3 and IMAP for authentication?
Location: http://www.jguru.com/faq/view.jsp?EID=309743
Created: Jan 22, 2001 Modified: 2001-01-23 04:47:35.425
Author: Neil Bacon (http://www.jguru.com/guru/viewbio.jsp?EID=309742) Question
originally posed by Jeff Mathers
(http://www.jguru.com/guru/viewbio.jsp?EID=242391

Only with great difficulty. This may not have all that you need, but it does provide a
lot of info on NTLM: http://www.innovation.ch/java/ntlm.html

How can I hardcode in my program what normally would be retrieved from


javamail.default.providers and javamail.providers files?
Location: http://www.jguru.com/faq/view.jsp?EID=311221
Created: Jan 24, 2001 Modified: 2001-01-24 09:33:07.532
Author: David Larsson (http://www.jguru.com/guru/viewbio.jsp?EID=305689)
Question originally posed by David Larsson
(http://www.jguru.com/guru/viewbio.jsp?EID=305689

I received this answer from Bill Shannon, one of the authors to JavaMail:
No. Those files should not be in your source tree. You should use mail.jar directly,
not extract the pieces of it.

When connecting to a POP inbox, I keep getting a "pop lock busy! Is


another session active?" message. What's wrong?
Location: http://www.jguru.com/faq/view.jsp?EID=312860
Created: Jan 25, 2001 Modified: 2001-01-25 19:08:22.002
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by watsawee san
(http://www.jguru.com/guru/viewbio.jsp?EID=310877

POP only supports having one reader/writer to the mailbox. If another mail program
is reading from the mailbox, you might get this error. Another cause of the error is if
your program ran, threw an exception, and didn't properly close the mailbox. In the
former case, you'll need to make sure you're not trying to read from multiple places.
In the latter case, you'll need to wait for the session to timeout.

What's necessary to setup automated bounce processing?


Location: http://www.jguru.com/faq/view.jsp?EID=314965
Created: Jan 29, 2001 Modified: 2001-01-29 07:44:24.916
Author: Martin Kuba (http://www.jguru.com/guru/viewbio.jsp?EID=244356)
Question originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

Specify a separate mail account in envelope's 'MAIL FROM:' header than in 'From:'
header. Then most of bounces will go to the first account, while replies to the second
account. (About 1% of bounces will still come to the same account as replies,
because of bad implementations of SMTP servers.)

To set the envelope header you will need JavaMail v1.2 or newer, set it using
mail.smtp.from property, as is described in another answer.

Use VERPs to track which bounce belongs to which email.

You may want to use similar technique as ezmlm-weed for differenciating real
bounces from delay notifications, replies from vacation autoresponders and another
junk.

How can I maintain the session-specific Transport / Store objects across


multiple HTTP requests, Sun's implementations aren't serializable?
Location: http://www.jguru.com/faq/view.jsp?EID=319276
Created: Feb 2, 2001 Modified: 2001-02-02 10:21:42.184
Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708)
Question originally posed by Mark K
(http://www.jguru.com/guru/viewbio.jsp?EID=302688

If you are using a Java server side solution, like the JSDK (which I suppose) then you
can store/retrieve the references in/from the HTTPSession object which you can get
from the incoming HttpRequest object.
For an example implementation you might want to take a look at:
http://www.sourceforge.net/projects/jwebmail and/or
http://www.sourceforge.net/projects/jwma

Both are open source webmail solutions written in Java.

How does one restore mail whose flag has set to deleted (unset the delete
FLAG)?
Location: http://www.jguru.com/faq/view.jsp?EID=322642
Created: Feb 6, 2001 Modified: 2001-02-07 04:35:58.99
Author: Tony Tjia (http://www.jguru.com/guru/viewbio.jsp?EID=305435) Question
originally posed by Tony Tjia (http://www.jguru.com/guru/viewbio.jsp?EID=305435

You can set the delete flag to false as follow.


message.setFlag(Flags.Flag.DELETED, false);

How do I delete a folder with IMAP4? Must I get the folder with getFolder()
before deleting?
Location: http://www.jguru.com/faq/view.jsp?EID=325993
Created: Feb 11, 2001 Modified: 2001-02-11 18:45:23.163
Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708)
Question originally posed by Tony Tjia
(http://www.jguru.com/guru/viewbio.jsp?EID=305435

Yes, you have to get the folder first. Here a small code snippet:
//I suppose some existing reference to the store
private Store myStore;

[...]
String path="mail/aFolder";
Folder afolder=myStore.getFolder(path);
if(afolder.exists() && !afolder.isOpen()) {
//the true will recurse
afolder.delete(true);
}
[...]
You should be sure the folder exists, and the operation performs only on a closed
folder. However, I suggest anyway to consult the API docs about the implications of
the delete().
javax.mail.Folder

public abstract boolean delete(boolean recurse)


throws MessagingException

I get a SendFailedException: 550 Invalid Address even when i set the


"mail.smtp.from" property. How can I tell it to ignore invalid addresses and
send to the rest?
Location: http://www.jguru.com/faq/view.jsp?EID=325996
Created: Feb 11, 2001 Modified: 2002-03-30 20:45:54.442
Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708)
Question originally posed by Asif Riaz
(http://www.jguru.com/guru/viewbio.jsp?EID=296693
The SendFailedException API documentation is explicit about your problem:
"The exception includes those addresses to which the message could not be sent as
well as the valid addresses to which the message was sent and valid addresses to
which the message was not sent."

This implies that the message will be send to any valid address and the
SendFailedException will allow you to figure out the valid (which got the message)
and the invalid addresses.

Also, look at the property mail.smtp.sendpartial : "If set to true, and a message has
some valid and some invalid addresses, send the message anyway, reporting the
partial failure with a SendFailedException. If set to false (the default), the message is
not sent to any of the recipients if there is an invalid recipient address. "

You can use

props.put("mail.smtp.sendpartial",true)

If that too fails, check your server setup.

You can also catch SendFailedException, and re-send to the addresses returned by
sfe.getValidUnsentAddresses() .

After open a folder with IMAP server, do I need to close the


connection/store before I open another folder? After I open a few folders,
the connection/user pool of the IMAP server is full and all request was
rejected by the IMAP server.
Location: http://www.jguru.com/faq/view.jsp?EID=325997
Created: Feb 11, 2001 Modified: 2001-02-11 19:15:31.128
Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708)
Question originally posed by Tony Tjia
(http://www.jguru.com/guru/viewbio.jsp?EID=305435

Basically you do not need to close a connection/store before you open another folder,
but there are certain constraints that come from the provider implementation you
are using.

In general taking care about resources is not a bad idea, open folders just when you
need them (with the right mode), and close them whenever you don't need them any
longer.

Especially when writing, because most likely implementations allow multiple readers,
but only one writer.

Why can't I open an IMAP folder in READ_WRITE mode at the same time as
having Netscape Communicator running (in IMAP mode)? I understand that
Netscape must have a lock on the folder, but how is it that other clients can
do it, like Netscape and Outlook? Is there any way of doing this?
Location: http://www.jguru.com/faq/view.jsp?EID=325998
Created: Feb 11, 2001 Modified: 2001-02-11 19:12:14.223
Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708)
Question originally posed by Phillip Beauvoir
(http://www.jguru.com/guru/viewbio.jsp?EID=222160

Most provider implementations allow multiple readers, but only one writer.
Netscape opens the folder in READ_WRITE mode, so if you try to do that too, you will
get a MessagingException.
You can only open the folder in READ_ONLY or you can try to switch to another
provider implementation.
However, it is never a good idea to write concurrently to some resource, even with
transactions you have to handle lost-update problems bubbling up.

How can I decode a Mail with JavaMail, having an UU-encoded attachment


(in a begin .. end section), when part.getContentType() returns
"text/plain"? I.e. there are no MIME-Types specified. The mail content is
like:

from: bla@hell.com
to: test@test.com
subject: uuencodetest

Hello,
this is a
uu-decode test!

begin 600 attachment.txt


,:&%L;&\@:VQA=7,*
`
end

Location: http://www.jguru.com/faq/view.jsp?EID=325999
Created: Feb 11, 2001 Modified: 2001-02-11 19:13:35.01
Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708)
Question originally posed by Klaus Battlogg
(http://www.jguru.com/guru/viewbio.jsp?EID=249705
You can try to process the plain text message by matching the start and end tokens
within it. A pattern matching toolkit (see jakarta.apache.org), and a few code as glue
will manage to extract the embedded attachment into a buffer.
Once that is achieved, you can decode it (see public static java.io.InputStream
decode(java.io.InputStream is, java.lang.String encoding)throws
MessagingException, supports "uuencode") and display it or save it to a file or
whatever.

How do I connect to an IMAP server over an SSL connection?


Location: http://www.jguru.com/faq/view.jsp?EID=329193
Created: Feb 14, 2001 Modified: 2001-02-14 12:13:59.974
Author: allen petersen (http://www.jguru.com/guru/viewbio.jsp?EID=105938)
Question originally posed by Chris Sterling
(http://www.jguru.com/guru/viewbio.jsp?EID=246502

This really isn't documented even in Sun's unsupported com.sun.mail.* packages,


now, is it?
Fortunately,you can figure it out by reading the source code for JavaMail. It turns out
that Sun's JavaMail implementation uses a SocketFetcher class which can be
configured using the Session's properties. Specifically, you can set the following
properties:

<prefix>.socketFactory.class
<prefix>.socketFactory.fallback
<prefix>.socketFactory.port
<prefix>.timeout

where <prefix> is your protocol's property prefix, such as 'mail.imap'. To use the
JSSE's SSLSocketFactory to connect to your IMAP store, you'll want to set
"mail.imap.socketFactory.class" to "javax.net.ssl.SSLSocketFactory".

Here's a sample class that uses these properties. You'll need the JSSE package
installed or in your CLASSPATH for this to work. You'll also need to have an SSL
enabled IMAP server (or something like sslwrap running) running with trusted
certificates. See the JSSE docs for more information.

public class TestSSL {

public static void main(String[] argv) {


// configure the jvm to use the jsse security.
java.security.Security.addProvider(new
com.sun.net.ssl.internal.ssl.Provider());

// create the properties for the Session


java.util.Properties props = new java.util.Properties();

// set this session up to use SSL for IMAP connections


props.setProperty("mail.imap.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
// don't fallback to normal IMAP connections on failure.
props.setProperty("mail.imap.socketFactory.fallback", "false");
// use the simap port for imap/ssl connections.
props.setProperty("mail.imap.socketFactory.port", "993");

// note that you can also use the defult imap port (including
the
// port specified by mail.imap.port) for your SSL port
configuration.
// however, specifying mail.imap.socketFactory.port means that,
// if you decide to use fallback, you can try your SSL
connection
// on the SSL port, and if it fails, you can fallback to the
normal
// IMAP port.

try {
// create the Session
javax.mail.Session session =
javax.mail.Session.getInstance(props);
// and create the store..
javax.mail.Store store = session.getStore(new
javax.mail.URLName("imap://mailtest:mailtest@localhost/"
));
// and connect.
store.connect();
System.out.println("connected to store.");
} catch (Exception e) {
System.out.println("caught exception: " + e);
e.printStackTrace();
}
}
}
Comments and alternative answers

POP3 and SSL without checking for valid certificate


Author: Cordelia Sommhammer
(http://www.jguru.com/guru/viewbio.jsp?EID=441914), Jun 20, 2001
First of all: It works for POP3 Connections over SSL too. Thanx for the useful hint.

But: My POP3S-Server doesn't have trusted certificates, and for I only want to use the
SSL- layer to encrypt the password while connecting, I'd like to tell the Socket not to
check Certificates. It seems, that there is no (documented) possibility to pass any
options to the Socket created by SSLSocketFactory.

Any idea how to solve this problem?

Re: POP3 and SSL without checking for valid certificate


Author: Donal Tobin (http://www.jguru.com/guru/viewbio.jsp?EID=47226), Aug
28, 2001
This is not a general solution but it will work for the case of a small number of
machines. The trick is to add the cert on the trusted root list for yur JVM. I have
done this for our internal developement HTTPS servers with developement certs,
so it works. However I do not remember the exact steps at this stage. If you are
really having trouble get back to me. Basically get the .cert file from the POP
server and put it on the JVM machine. Sun have a security tool that will import
from that .cert file to a Java Format. You then add the contents of that file to the
root certs file for the JVM. The sun site tells you all the steps in the JDK tools
(security) documentation.

Re: Re: POP3 and SSL without checking for valid certificate
Author: Srikanth V (http://www.jguru.com/guru/viewbio.jsp?EID=490287),
Sep 4, 2001
Hello, I'm trying to connect to an IMAP email server through SSL. I have
tryed to run the code given above. The command I'm using to run is

java -Djavax.net.ssl.trustStore=.keystore SSLEmail


I'm getting the following exception.

caught exception: javax.mail.MessagingException: Couldn't connect using


"javax.net.ssl.SSLSocketFact ory" socket factory to host, port:
imap.server.com, 993; nested exception is: java.io.IOException: Couldn't
connect using "javax.net.ssl.SSLSocketFactory" socket factory to host, port:
imap.server.com, 993 javax.mail.MessagingException: Couldn't connect using
"javax.net.ssl.SSLSocketFactory" socket factor y to host, port:
imap.server.com, 993; nested exception is: java.io.IOException: Couldn't
connect using "javax.net.ssl.SSLSocketFactory" socket factory to host, port:
imap.server.com, 993 at
com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:145) at
javax.mail.Service.connect(Service.java:227) at
javax.mail.Service.connect(Service.java:131) at
javax.mail.Service.connect(Service.java:87) at
devcon.test.SSLEmail.main(SSLEmail.java:54) could you please tell me how
you solved the problem in the past. appreciate any help. thanks

Re: Re: Re: POP3 and SSL without checking for valid certificate
Author: Donal Tobin (http://www.jguru.com/guru/viewbio.jsp?EID=47226), Sep 5, 2001
try setting "java.protocol.handler.pkgs" as well, it is usually equal to "com.sun.net.ssl.internal.w
if you have the sun JSSE "jnet.jar", "jcert.jar", and "jsse.jar" installed. Or put this in your code.
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.ww
Heres a link JSSE that may be of use.

security certificates problem


Author: Samir Kuthiala (http://www.jguru.com/guru/viewbio.jsp?EID=475549), Aug
13, 2001

i tried ur code. however i am unable to connect to my imap server. it gives me an error


saying untrusted certificates. i understad this arises because jsee supports less
certificates than ie. but is there any way around this problem? by turning off checking
for site certs or manually installing the security cert?

pls let me know


thanx
Samir
samir@linuxturf.com

Re: security certificates problem


Author: Saku Laitinen (http://www.jguru.com/guru/viewbio.jsp?EID=546516),
Nov 13, 2001
You can get rid of this problem by creating you own SocketFactory that uses a
DummyTrustManager that will accept any cert.

* WARNING * this solution will accept absolutely ANY cert.

Of course you can write more intelligense into your TrustManager.

...and then when creating the connection to the mailserver

props.setProperty("mail.imap.socketFactory.class",
"MySocketFactory");

Re[2]: security certificates problem


Author: Srinivas Kusuname
(http://www.jguru.com/guru/viewbio.jsp?EID=847037), Apr 20, 2002
How should i access the IMAP for which SSL is enabled? I am calling it like
this

javax.mail.URLName("imap://imap.myserver.net/");

But with this iam getting following error:

caught exception: javax.mail.AuthenticationFailedException


javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:265)
at javax.mail.Service.connect(Service.java:135)
at javax.mail.Service.connect(Service.java:87)
at TestSSL.main(TestSSL.java:43)

I am sure there is something missed in my IMAP call. Any help could be


appreciated.

Thanks
-srini

Re[3]: security certificates problem


Author: Rainer TRAFELLA
(http://www.jguru.com/guru/viewbio.jsp?EID=834944), Sep 18, 2002

I don't know much about the JavaMail API, but for IMAP over SSL you have
to connect to Port 993 on your IMAP Server and not to the default Port 143
for standard IMAP.
Hope this helps!

Best regards,
Rainer

How-To connect without worrying about certificates


Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708), Jun
7, 2004
It is possible to circumvent the certificate problem following the instructions outlined
by:
http://www.javaworld.com/javatips/jw-javatip115.html

Basically you need to create a dummy wrapper for the SSL Socket Factory, which
utilizes a dummy TrustManager that returns true for any check.

See article for details, it is actually a complete answer for this FAQ question.

Regards,
Dieter

When sending an attachment with JavaMail, I don't want the attachment to


have the full directory path from the source. How do I shorten the name
associated with the attachment?
Location: http://www.jguru.com/faq/view.jsp?EID=333116
Created: Feb 19, 2001 Modified: 2001-02-19 07:48:42.224
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by guruprasad vyapaka
(http://www.jguru.com/guru/viewbio.jsp?EID=302341

The MimeBodyPart class has a setFileName() method that allows you to specify
any text you want. Just set it to the name of the FileDataSource:
MimeBodyPart mbp = new MimeBodyPart();
FileDataSource fds =
new FileDataSource("c:/temp/foo.jpg");
mbp.setFileName(fds.getName());

When using JavaMail I get an NoSuchField exception on the


getContentStream() method / contentStream field of MimeMessage. What's
wrong?
Location: http://www.jguru.com/faq/view.jsp?EID=333721
Created: Feb 19, 2001 Modified: 2001-02-19 22:03:00.069
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by naveen kumar.v
(http://www.jguru.com/guru/viewbio.jsp?EID=321080
The contentStream field was added to JavaMail 1.2. Apparently, you are trying to run
a 1.2 program with the 1.1 JavaMail classes.

If I set the host and user properties before calling getDefaultInstance() are
those properties used for all successive gets to Store or Transport objects?
Location: http://www.jguru.com/faq/view.jsp?EID=337080
Created: Feb 23, 2001 Modified: 2001-02-23 13:06:09.721
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Rick DeGrande
(http://www.jguru.com/guru/viewbio.jsp?EID=333396

The properties passed into the getDefaultInstance() method are only referenced if
the method creates the session object, essentially only the first time. Future calls to
the method will ignore the argument. These properties are then used by anything
created off the session.

Do I need an SMTP server when using JavaMail?


Location: http://www.jguru.com/faq/view.jsp?EID=339926
Created: Feb 27, 2001 Modified: 2001-02-27 04:58:22.684
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by David Ha (http://www.jguru.com/guru/viewbio.jsp?EID=50426

JavaMail still needs an SMTP server. The API comes with an SMTP provider (in
smtp.jar for JavaMail 1.2). The provider provides access to YOUR SMTP server.

How can I retrieve a list of UIDs from the mail server for POP3 with
JavaMail?
Location: http://www.jguru.com/faq/view.jsp?EID=340261
Created: Feb 27, 2001 Modified: 2001-02-27 12:52:33.894
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Roger Hansson
(http://www.jguru.com/guru/viewbio.jsp?EID=277866

Use the fetch() method to prefetch information. If the FetchProfile contains


UIDFolder.FetchProfileItem.UID, POP3 UIDs for all messages in the folder are fetched
using the POP3 UIDL command. If the FetchProfile contains
FetchProfile.Item.ENVELOPE, the headers and size of all messages are fetched using
the POP3 TOP and LIST commands.

See the sundocs for the Pop3Folder for more information. [javamail-
1.2/docs/sundocs/com/sun/mail/pop3/POP3Folder.html#fetch]. These are provided
with the JavaMail 1.2 release.

How can I include a multi-line message in a mailto: URL?


Location: http://www.jguru.com/faq/view.jsp?EID=341038
Created: Feb 28, 2001 Modified: 2001-03-01 21:01:47.491
Author: Jayesh Nazre (http://www.jguru.com/guru/viewbio.jsp?EID=44356)
Question originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

Well you have to pass the parameter "body" a value.


To embed your message completely in your HTML page, you'll need to use
JavaScript's escape() method to convert the text with new lines to something that
can be used in a mailto URL.

<html>
<head>
<script language=javascript>

function send() {
var lstr_data = "FIRST LINE" + "\n" +
"SECOND LINE" + "\n" + "THIRD LINE";
window.location.href="mailto:jayesh_nazre@hotmail.com" +
"?body=" + escape (lstr_data);
}
</script>
</head>
<body>

<a href="javascript:send();">Send Message</a>


</body>
</html>

Instead, you can get the message from a TextArea on the page...

<html>
<head>
<script language=javascript>
function send() {

window.location.href="mailto:jayesh_nazre@hotmail.com" +
"?body=" + document.frm_test.ta_body.value;

}
</script>
</head>
<body>

<form id=frm_test name=frm_test>

Mail Contents:

<TEXTAREA NAME=ta_body ROWS="6" COLS="55">


HELLO1
HELLO2
</TEXTAREA>
<input type=button value=SendMail onclick=send()>
</form>
</body>
</html>
Note if you need to specify the subject then u need to pass the parameter "subject"
like this

window.location.href="mailto:jayesh_nazre@hotmail.com" +
"?subject=" + "TEST MAIL";

How can I access MS Exchange Public Folders using JavaMail? Is it


supported?
Location: http://www.jguru.com/faq/view.jsp?EID=343803
Created: Mar 3, 2001 Modified: 2001-03-05 07:25:37.99
Author: Ivo Limmen (http://www.jguru.com/guru/viewbio.jsp?EID=327483)
Question originally posed by Jack Leung
(http://www.jguru.com/guru/viewbio.jsp?EID=13166

Since there isn't any package written in Java to connect and use Microsoft Exchange
data you will have to manually connect with the Exchange server throught Sockets
and use the Microsoft Exchange protocol (IMAP) to extract the data from the
database. So to answer your second question "Is it supported?" I will have to say
"not directly.". To get information about programming Exchange look here.
Comments and alternative answers

Exchange supports the IMAP protocol. So using the Sun...


Author: Loubaresse francois (http://www.jguru.com/guru/viewbio.jsp?EID=335699),
Mar 16, 2001
Exchange supports the IMAP protocol. So using the Sun provided IMAP provider,
you can access public folders on the exchange server - no problem. It's supported by
MS on the exchange end, and (I assume) by Sun for the IMAP JavaMail
provider...and it works too, I've tried it.

Re: Exchange supports the IMAP protocol. So using the Sun...


Author: challey shin (http://www.jguru.com/guru/viewbio.jsp?EID=832206), Aug
4, 2002
it works very well....!!! look following code...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:
Folder publicFolder = store.getFolder("Public Folders/");
Folder[] folders = publicFolder.list("*");

:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"folders" is public folders of exchange server... That`s all !!! Good luck and Have
a nice day!!!

Re[2]: Exchange supports the IMAP protocol. So using the Sun...


Author: Devadas Bhukya
(http://www.jguru.com/guru/viewbio.jsp?EID=1069111), Mar 24, 2003
Hi Iam unable to access the access the public folders even after using the
following code, Store store = session.getStore("imap"); store.connect(host,
username, password); Folder publicFolder = store.getFolder("Public
Folders/"); Folder[] folders = publicFolder.listSubscribed("*"); Any one can
has solution. Deva

Re[3]: Exchange supports the IMAP protocol. So using the Sun...


Author: Devadas Bhukya
(http://www.jguru.com/guru/viewbio.jsp?EID=1069111), Mar 24, 2003
Store store = session.getStore("imap"); store.connect(host, username,
password); Folder publicFolder = store.getFolder("Public Folders/");
Folder[] folders = publicFolder.list("*"); not working unable to access
public folder any help

How can I serialize a JavaMail Message?


Location: http://www.jguru.com/faq/view.jsp?EID=345906
Created: Mar 6, 2001 Modified: 2002-01-07 10:24:05.348
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Eric Rapp (http://www.jguru.com/guru/viewbio.jsp?EID=345778

You can't. As messages are associated with folders which are associated with
sessions, Message objects are considered not serializable. Like threads and images
you need to save the pieces that are not session-specific and regenerate the object
at the other end. Save the contents to an RFC 822 formatted stream
(message.writeTo()), serialize the bytes, and recreate the message at the other end.

How do I correct getting a SendFailedException, 553 NOT A LOCAL DOMAIN


error?
Location: http://www.jguru.com/faq/view.jsp?EID=352951
Created: Mar 16, 2001 Modified: 2001-03-16 07:11:20.599
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by bhavesh desai
(http://www.jguru.com/guru/viewbio.jsp?EID=344539

This error has to do with the configuration of your mail server and has nothing to do
with how you are using the JavaMail API. Correct the mail server configuration and
your program will work fine.

How to configure your mail server depends on what mail server you are using.

If I can't change my mail server configuration, how can I get around


problems about no permission to relay and not a local domain errors?
Location: http://www.jguru.com/faq/view.jsp?EID=379908
Created: Mar 17, 2001 Modified: 2001-03-18 06:28:40.985
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7
You can manually lookup the MX record of the recipient with tools like MXLookup and
connect directly to the recipient's SMTP server, instead of your own.
Comments and alternative answers

Search MX records of the recipient's is not a good idea!


Author: Andriano Franck (http://www.jguru.com/guru/viewbio.jsp?EID=703045),
Dec 16, 2002
Since 1998 IN A records is enough, so some domains don't have MX records like
altern.org...

See RFC...

Best regards,

/Franck

How can I send a message with multiple from fields?


Location: http://www.jguru.com/faq/view.jsp?EID=379997
Created: Mar 18, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

Instead of using setFrom(), use addFrom(). This takes an array of Address objects.

How do you get JavaMail to tell SMTP to send the domain name along with
the HELO command to avoid a MessagingException "501 HELO requires
domain address"?
Location: http://www.jguru.com/faq/view.jsp?EID=380341
Created: Mar 18, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by David Chen
(http://www.jguru.com/guru/viewbio.jsp?EID=334324

From Sun's JavaMail FAQ:


The SMTP provider uses the results of InetAddress.getLocalHost().getHostName() in
the SMTP HELO command. If that call fails to return any data, no name is sent in the
HELO command. Check your JDK and name server configuration to ensure that that
call returns the correct data. Starting with JavaMail 1.1.3, you may also set the
mail.smtp.localhost property to the name you want to use for the HELO command.

I have a mail message with only a attachment. No body part. How can I
check the MIME type of that mail?
Location: http://www.jguru.com/faq/view.jsp?EID=383140
Created: Mar 20, 2001
Author: Michael Dailous (http://www.jguru.com/guru/viewbio.jsp?EID=381385)
Question originally posed by chandi hettiaratchi
(http://www.jguru.com/guru/viewbio.jsp?EID=349311
Generally speaking, any email message that contains an attachment is encoded as a
multipart/* email message. Even if there is no main "body" part, the email is still
encoded as a multipart/* email message. You would process each part of the
message just as you would any other multipart/* message. Here's a quick snippet of
code that'll go through as many levels of multipart/* sections as available (NOTE:
This is a _quick_ code snippet and does not do any error detection/correction):
// create a session
// connect to the store
// open the folder
// get the message
getPartMimeType(message.getContent());

public void getPartMimeType(Part p) {


if (p.isMimeType("multipart/*")) {
Multipart mp = (Multipart)p.getContent();
for (int x = 0; x < mp.getCount(); x++) {
if (mp.getBodyPart(x).isMimeType("multipart/*")) {
getPartMimeType(mp.getBodyPart(x).getContent());
} else {
System.out.println(mp.getBodyPart(x).getContentType());
}
}
} else {
// you should do more granular checking of other mime-types
System.out.println(p.getContentType());
}
}
This should print out the MIME type of each part of the email message, no matter
how many multipart/* parts there are.

If you'd like to determine the MIME type of just the first attachment, you could
modify the above code snippet as follows:

// create a session
// connect to the store
// open the folder
// get the message
getAttachmentMimeType(message.getContent());

public void getAttacheMimeType(Part p) {


if (p.isMimeType("multipart/*")) {
Multipart mp = (Multipart)p.getContent();
for (int x = 0; x < mp.getCount(); x++) {
if (mp.getBodyPart(x).isMimeType("multipart/*")) {
getAttachmentMimeType(mp.getBodyPart(x).getContent());
} else {
if
(checkAttachment(mp.getBodyPart(x).getDisposition())) {
System.out.println(mp.getBodyPart(x).getContentType
());
break;
}
}
}
} else {
// you should do more granular checking of other mime-types
if (checkAttachment(p.getDisposition())) {
System.out.println(p.getContentType());
}
}
}

public boolean checkAttachment(String disposition, String contentType) {


if (disposition != null &&
disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
return true;
}
return false;
}
Comments and alternative answers

The above answer is completely misleading


Author: Abid Farooqui (http://www.jguru.com/guru/viewbio.jsp?EID=325097), Jun
19, 2001
Saying that any email message that conatins an attachment is encoded as a multipart/*
is wrong, specially when there is no body whatsoever in the e-mail. I have had this
trouble and I followed this strategy (no thanks to JGURU FAQ here) and had to re-
write and rethink my code to automate processing of attachments in my code. I'll
simply quote Bill Shanon's answer from the Sun JavaMail team to my problem here:

"I don't know what requirements you've placed on the clients that send you the
attachments. If there is no requirement for a "main text body" in addition to the
"attachment", it's quite reasonable for someone to send you a message that contains
only the attachment, in which case it might not show up as a multipart message - there
is only one part after all. If you consider this case legitimate, then your program needs
to be smart enough to handle it.

Things you might want to check for to indicate that a message contains a part you
need to process are:
Content-Disposition of "attachment" filename ending in ".csv" Content-Type of
application/octet-stream If the same mailbox can contain other messages with
arbitrary data that you're not supposed to process, you might have to resort to reading
the attached data in some cases to make sure it's really the special data you're
expecting. Largely this comes down to what requirements you've placed on people
who send messages to this mailbox. What you're seeing is legal MIME."

This FAQ and the tutorial presented by JGuru really does not handle processing of the
attachment(s) well if you are writing a POP3 client or similar. In my case I was
getting messages that simply said that the content-type = application/octetstream,
content-disposition = attachment and filename = something and then simply there was
Base64 encoded file attachment there. There was no multipart anywhere and that is
considered legal MIME. If I were you, I would not go by this answer at all.
Re: The above answer is completely misleading
Author: Abid Farooqui (http://www.jguru.com/guru/viewbio.jsp?EID=325097),
Jun 19, 2001
I guess I should give some pointers as to where you can check and code for
scenarios that are not civered by the above example

Basically you would have some code here:


else {
// you should do more granular checking of other mime-types
if (checkAttachment(p.getDisposition())) {
System.out.println(p.getContentType());
// this right here would be the attachment in the case that I
// encountered and described in my previous post. Handle the attachment as
// you would handle an attachment from the multipart/* here
}

Re: Re: The above answer is completely misleading


Author: Satyamoorthy Vasudevan
(http://www.jguru.com/guru/viewbio.jsp?EID=512831), Oct 6, 2001
I tried to access a mail that had only the attachment with no main text , that is
only one body part as attachment. Now when try to get the Multipart Object I
get the ClassCastException. I tried Multipart multipart =
(Multipart)message[i].getContent(); and Part part =
(Part)message[i].getContent(); both did not work

Re[3]: The above answer is completely misleading


Author: Subhash Agrawal
(http://www.jguru.com/guru/viewbio.jsp?EID=577320), Dec 8, 2001
As the message has only one attachment without content type of multipart/*
so you can not casr it to Multipart.If u try it will give classcastexception. The
best way is to check content type and then do casting if required. I also got
same problem

Re[2]: The above answer is completely misleading


Author: Subhash Agrawal
(http://www.jguru.com/guru/viewbio.jsp?EID=577320), Dec 8, 2001
My problem is almost same but I am still struggling. Thing is that my
forwarded message(RFC822 type) has only one attachment(WAV file) content
type of AUDIO/WAV rather than multipart/*. Now when I am getting content
of this message and playing it , it does not play. player says "Not an
audio/wavform file". When I open same message in outlook express/netscape
messanger, it plays that attachment. When I checked the size of both wav
file(one downloaded by my mail client and other client) there is few byte
difference. But the strange thing is that when I get message with content type
of multipart/* with one attachement(Wav file) then my email client can play
that with no problem. Any thought ????
Re[3]: The above answer is completely misleading
Author: Abid Farooqui
(http://www.jguru.com/guru/viewbio.jsp?EID=325097), Dec 8, 2001
Subhash, I think your problem is slightly different than the subject being
discussed here. The difference primarily lies in the fact that even though
you seem to get the part even if it is not a multipart/* content type, it does
not seem to be correct whereas, we were discussing not even being able to
get the part as attachment because it won't be recognized as attachment but
simply as a body part.
Anyway, I would suggest these things.
1) After you get the supposed attachment (wav file), just put a few hundread
bytes (of the beggining) in a byte array and print them out. Then also open
your same exact wav file that you get in outlook express not in a wav player
but in "wordpad" (hopefully you will use a wav file that is not too huge) and
see if the first few hundread bytes seem to be the same as what you printed
out from your code. I bet they are not and that you are actually not grabbing
the attachment correctly when the attachment does not come in a
multipart/* content type.
2) Instead of wav files send other simpler forms like a text file without a
multipart/* content-type and see if that seems to act fine.
Hopefully these pointers will help you determine exactly what is going on.

When reading mail, how do I get just the message content without the
headers?
Location: http://www.jguru.com/faq/view.jsp?EID=386687
Created: Mar 25, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by bhavesh desai
(http://www.jguru.com/guru/viewbio.jsp?EID=380408

Use the getContent() method of the MimeMessage class to get the content, excluding
headers.

Why does folder.list() throw a MessagingException: not a directory with


POP3?
Location: http://www.jguru.com/faq/view.jsp?EID=387164
Created: Mar 26, 2001 Modified: 2001-03-27 08:50:14.85
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by A Java Programmer
(http://www.jguru.com/guru/viewbio.jsp?EID=384596

POP only supports a single folder, the INBOX.

How do I use the JavaMail API to send newsgroups messages?


Location: http://www.jguru.com/faq/view.jsp?EID=393015
Created: Apr 2, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Francesco Marchioni
(http://www.jguru.com/guru/viewbio.jsp?EID=59707

You need to get an NNTP provider, like Knife's. You must manually create an instance
of their NNTP Transport object to send the message as well as specify the
newsgroup to post to.

The following program does just that.

import javax.mail.*;
import javax.mail.internet.*;

public class PutNewsExample {


public static void main (String args[]) throws Exception {
String host = args[0];
String from = args[1];
String newsgroup = args[2];
String username = args[3];
String password = args[4];

// Get session
Session session = Session.getInstance(
System.getProperties(), null);

// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setSubject("Test Test - Ignore");
message.setText("Will this work?");
message.addHeader("Newsgroups", newsgroup);

// Define transport
Transport transport =
new dog.mail.nntp.NNTPTransport(session,
new URLName("news:" + newsgroup));

transport.connect(host, username, password);


transport.sendMessage(message,
message.getAllRecipients());

transport.close();

}
}
Comments and alternative answers
Alternate solution
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Apr 3,
2001
If you don't mind adding an entry with "protocol=nntp; type=transport;..." in your
javamail.providers file.... you can use the following code instead:

import javax.mail.*;
import javax.mail.internet.*;

public class PutNewsExample {


public static void main (String args[]) throws
Exception {
URLName url = new URLName(args[0]);
Address from = new InternetAddress(args[1]);

// Get session and transport


Session session = Session.getInstance(
System.getProperties(), null);

Transport transport =
session.getTransport(url);

// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(from);
message.addRecipients(
MimeMessage.RecipientType.NEWSGROUPS,
url.getFile());
message.setSubject("Test Test - Ignore");
message.setText("Will this work?");

transport.connect();
transport.sendMessage(message,
message.getAllRecipients());
transport.close();
}
}
This can be invoked something like

java PutNewsExample nntp://me:mypass@news/alt.test me@home

Does the Transport.send() method block until the STMP mail transaction is
completed?
Location: http://www.jguru.com/faq/view.jsp?EID=403798
Created: Apr 16, 2001
Author: Michael Wax (http://www.jguru.com/guru/viewbio.jsp?EID=242559)
Question originally posed by Ed Borejsza
(http://www.jguru.com/guru/viewbio.jsp?EID=391155

The Sun SMTPTransport class does block. Further, the JavaMail Guide for Service
Providers also does not specify that the send method not block. Therefore, if you are
concerned that you might not get a timely return, you would be prudent to spawn a
new thread.

Are there any online tutorials on the JavaMail API?


Location: http://www.jguru.com/faq/view.jsp?EID=407606
Created: Apr 21, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

jGuru created a JavaMail tutorial for Sun's Java Developer Connection.


Comments and alternative answers

Re. javamail API


Author: John Norgaard (http://www.jguru.com/guru/viewbio.jsp?EID=331034), May
6, 2001
Here are a few articles/tutorials:
http://www.jspinsider.com/beans/beans/email/BeanMailer/index.html
http://developer.java.sun.com/developer/onlineTraining/JavaMail/ - and the
specifications/FAQ: http://softwarema.usec.sun.com/products/javamail/

How do I use the Yahoo SMTP server to send mail with the JavaMail API?
Location: http://www.jguru.com/faq/view.jsp?EID=407686
Created: Apr 22, 2001 Modified: 2002-03-30 21:21:04.711
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Ashwin Parmar
(http://www.jguru.com/guru/viewbio.jsp?EID=393164

From your Yahoo mail account, you need to enable POP Access and Forwarding.
Select Options in the left gutter, then POP Access & Forwarding under Mail
Management. You need to have Web and POP Access enabled. This is not a free
service. You then MUST use your Yahoo address as the FROM address when sending
the message. The basic mail sending program with authentication is sufficient.
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class MailExample {


public static void main (String args[]) throws Exception {
String smtpHost = "smtp.mail.yahoo.com";
String popHost = "pop.mail.yahoo.com";
String from = args[0]; // with @yahoo.com
String to = args[1];
String username = args[2];
String password = args[3];
// Get system properties
Properties props = System.getProperties();

// Setup mail server


props.put("mail.smtp.host", smtpHost);

// Get session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(true);

// Pop Authenticate yourself


Store store = session.getStore("pop3");
store.connect(popHost, username, password);

// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("Hello JavaMail");
message.setText("Welcome to Yahoo's JavaMail");

// Send message
Transport.send(message);
}
}
Note: Previously, POP authentication was required. That is no longer the case.
Comments and alternative answers

how to solve client authentication


Author: sally neysky (http://www.jguru.com/guru/viewbio.jsp?EID=1012714), Oct
16, 2002
Note: Previously, POP authentication was required. That is no longer the case. how to
solve client authentication

How can I include an attachment-file (for example a txt-file) in a mailto-


URL?
Location: http://www.jguru.com/faq/view.jsp?EID=413063
Created: May 1, 2001
Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985)
Question originally posed by Osman Bulut
(http://www.jguru.com/guru/viewbio.jsp?EID=350783

You cannot. In a mailto URL you can specify the target and a subject, attachments
are not supported (and it would be a security problem if this were).

How can I add the javamail.providers in the META/INF dir in a signed jar? I
want to add my own pop3 Provider to my signed app. I use signtool create a
signed jar file with a manifest file. Now I have to add the javamail.providers
file in the META/INF dir in the jar package for using my own pop3 stuff.
When I use jar, i can not add it without destroying my signature. What are
the ways to do that ?
Location: http://www.jguru.com/faq/view.jsp?EID=426874
Created: May 23, 2001
Author: Alex [missing] (http://www.jguru.com/guru/viewbio.jsp?EID=425187)
Question originally posed by Alex [missing]
(http://www.jguru.com/guru/viewbio.jsp?EID=425187

Have found it by myself. make a Dir with the name META-INF and put the provider
file in it. then just:
jar -uf app.jar META-INF/javamail.providers
the signature will not been destroyed (plugin fell fine)

How can I send a mail message with multiple lines in the body?
Location: http://www.jguru.com/faq/view.jsp?EID=430244
Created: May 29, 2001 Modified: 2002-03-30 21:30:50.677
Author: Ivo Limmen (http://www.jguru.com/guru/viewbio.jsp?EID=327483)
Question originally posed by Bernd Hülsebusch
(http://www.jguru.com/guru/viewbio.jsp?EID=430026

You need to manually add the new lines to the message. Try the following:
...
StringBuffer sb = new StringBuffer();

sb.append("This is line 1\n\r");


sb.append("This is the second line\n\r");
sb.append("...");

msg.setText(sb.toString());
...
You must use one bodypart with text but the text can contain multiple lines. So you
need to use the \r\n.

You can also use


String newline = System.getProperty("line.separator");
to get the platform-specific line separator. Keep in mind that if you display the text
as HTML, the newline is just white space.

What are the different RFCs for the related JavaMail protocols?
Location: http://www.jguru.com/faq/view.jsp?EID=431271
Created: May 30, 2001 Modified: 2001-06-01 13:26:38.617
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

• SMTP is RFC 821, recently replaced by RFC 2821.


• POP3 is RFC 1939.
• IMAP4 is RFC 2060.
• MIME/message format is covered in RFC 822 (recently replaced by RFC
2822), RFC 2045, RFC 2046, and RFC 2047.

How do I set the character set (charset) for a content type?


Location: http://www.jguru.com/faq/view.jsp?EID=434625
Created: Jun 6, 2001
Author: Rahul kumar Gupta (http://www.jguru.com/guru/viewbio.jsp?EID=4809)
Question originally posed by back hyejin
(http://www.jguru.com/guru/viewbio.jsp?EID=235836

You can set the content type of your message like:


msg.setContent(message,"text/html;charset=\"UTF-8\"");
Comments and alternative answers

alternative?
Author: lecanard masque (http://www.jguru.com/guru/viewbio.jsp?EID=522072), Oct
17, 2001
what about : msg.setText(text,"UTF-8"); ?

How do I convert a comma delimeted string of email addresses to an array


of recipients for a message?
Location: http://www.jguru.com/faq/view.jsp?EID=439993
Created: Jun 15, 2001
Author: Travis Polland (http://www.jguru.com/guru/viewbio.jsp?EID=423797)
Question originally posed by Travis Polland
(http://www.jguru.com/guru/viewbio.jsp?EID=423797

Use the InternetAddress.parse() method:


String strName = /* request.getParameter("TO"); */
InternetAddress[] address = InternetAddress.parse(strName);
message.setRecipients(Message.RecipientType.TO, address);

How can I send a message to a folder other then the Inbox?


Location: http://www.jguru.com/faq/view.jsp?EID=442090
Created: Jun 20, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by zhou tao (http://www.jguru.com/guru/viewbio.jsp?EID=438817

The sender of a message has no control over what folder the message gets saved in.
All new messages appear in Inbox. The recipient's mail server either has to move
them, or when the recipient fetches your message, they can move them. As a
sender, you can't do anything like that.

Does Sun's IMAP service provider support the IDLE extension?


Location: http://www.jguru.com/faq/view.jsp?EID=449276
Created: Jul 3, 2001 Modified: 2001-07-03 17:02:20.428
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

According to Bill Shannon, primary engineer behind the API, no.

Where can I learn more about the IDLE command for IMAP?
Location: http://www.jguru.com/faq/view.jsp?EID=449280
Created: Jul 3, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

The IDLE command for IMAP4 is defined in RFC 2177.

Can I use IMAP4 along with POP3?

I'm trying to write a mail-account program and want to connect to an


IMAP4 server along with a POP3 server in my program. Whichever one I
connect to first works, but I can't connect to the other one then. How do I
use them together?
Location: http://www.jguru.com/faq/view.jsp?EID=454440
Created: Jul 13, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Ilya Egoshin
(http://www.jguru.com/guru/viewbio.jsp?EID=453861

Use different session objects (don't use the default). Get the session with
Session.getInstance() instead of getDefaultInstance().

Where can I find the documentation for Sun's JavaMail providers?


Location: http://www.jguru.com/faq/view.jsp?EID=462336
Created: Jul 25, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

In the JavaMail 1.2 download, there is a sundocs directory that includes


documentation on the IMAP, POP3, and SMTP-specific classes.

What properties are supported by the Sun IMAP provider?


Location: http://www.jguru.com/faq/view.jsp?EID=462885
Created: Jul 26, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The following is taken from the javadoc files for the com.sun.mail.imap package in
JavaMail 1.2:
Name Type Description
mail.imap.user String Default user name for IMAP.
mail.imap.host String The IMAP server to connect to.
The IMAP server port to connect to, if the
mail.imap.port int connect() method doesn't explicitly specify
one. Defaults to 143.
Controls whether the IMAP partial-fetch
mail.imap.partialfetch boolean
capability should be used. Defaults to true.
mail.imap.fetchsize int Partial fetch size in bytes. Defaults to 16K.
Socket connection timeout value in
mail.imap.connectiontimeout int
milliseconds. Default is infinite timeout.
mail.imap.timeout int Socket I/O timeout value in milliseconds.
Default is infinite timeout.
Timeout value in milliseconds for cache of
mail.imap.statuscachetimeout int STATUS command response. Default is 1000
(1 second). Zero disables cache.
Maximum size of a message to buffer in
memory when appending to an IMAP folder.
If not set, or set to -1, there is no maximum
and all messages are buffered. If set to 0, no
messages are buffered. If set to (e.g.) 8192,
messages of 8K bytes or less are buffered,
mail.imap.appendbuffersize int
larger messages are not buffered. Buffering
saves cpu time at the expense of short term
memory usage. If you commonly append very
large messages to IMAP mailboxes you might
want to set this to a moderate value (1M or
less).
Maximum number of available connections in
mail.imap.connectionpoolsize int
the connection pool. Default is 1.
Timeout value in milliseconds for connection
mail.imap.connectionpooltimeout int pool connections. Default is 45000 (45
seconds).
Flag to indicate whether to use a dedicated
mail.imap.separatestoreconnection boolean store connection for store commands. Default
is false.

What properties are supported by the Sun POP3 provider?


Location: http://www.jguru.com/faq/view.jsp?EID=462936
Created: Jul 26, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The following is taken from the javadoc files for the com.sun.mail.pop3 package in
JavaMail 1.2:
Name Type Description
mail.pop3.user String Default user name for POP3.
mail.pop3.host String The POP3 server to connect to.
The POP3 server port to connect to, if the connect()
mail.pop3.port int method doesn't explicitly specify one. Defaults to
110.
Socket connection timeout value in milliseconds.
mail.pop3.connectiontimeout int
Default is infinite timeout.
Socket I/O timeout value in milliseconds. Default is
mail.pop3.timeout int
infinite timeout.
mail.pop3.rsetbeforequit boolean Send a POP3 RSET command when closing the
folder, before sending the QUIT command. Useful
with POP3 servers that implicitly mark all messages
that are read as "deleted"; this will prevent such
messages from being deleted and expunged unless
the client requests so. Default is false.
Class name of a subclass of
com.sun.mail.pop3.POP3Message. The subclass
can be used to handle (for example) non-standard
mail.pop3.message.class int Content-Type headers. The subclass must have a
public constructor of the form
MyPOP3Message(Folder f, int msgno) throws
MessagingException.

What properties are supported by the Sun SMTP provider?


Location: http://www.jguru.com/faq/view.jsp?EID=462937
Created: Jul 26, 2001 Modified: 2001-08-19 06:55:22.755
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The following is taken from the javadoc files for the com.sun.mail.pop3 package in
JavaMail 1.2:
Name Type Description
mail.smtp.user String Default user name for SMTP.
mail.smtp.host String The SMTP server to connect to.
The SMTP server port to connect to, if the connect()
mail.smtp.port int method doesn't explicitly specify one. Defaults to
25.
Socket connection timeout value in milliseconds.
mail.smtp.connectiontimeout int
Default is infinite timeout.
Socket I/O timeout value in milliseconds. Default is
mail.smtp.timeout int
infinite timeout.
Email address to use for SMTP MAIL command.
This sets the envelope return address. Defaults to
mail.smtp.from String msg.getFrom() or
InternetAddress.getLocalAddress(). NOTE:
mail.smtp.user was previously used for this.
Local host name. Defaults to
InetAddress.getLocalHost().getHostName(). Should
mail.smtp.localhost String
not normally need to be set if your JDK and your
name service are configured properly.
mail.smtp.ehlo boolean If false, do not attempt to sign on with the EHLO
command. Defaults to true. Normally failure of the
EHLO command will fallback to the HELO
command; this property exists only for servers that
don't fail EHLO properly or don't implement EHLO
properly.
If true, attempt to authenticate the user using the
mail.smtp.auth boolean
AUTH command. Defaults to false.
The NOTIFY option to the RCPT command. Either
mail.smtp.dsn.notify String NEVER, or some combination of SUCCESS,
FAILURE, and DELAY (separated by commas).
The RET option to the MAIL command. Either
mail.smtp.dsn.ret String
FULL or HDRS.
If set to true, and the server supports the
8BITMIME extension, text parts of messages that
mail.smtp.allow8bitmime boolean use the "quoted-printable" or "base64" encodings
are converted to use "8bit" encoding if they follow
the RFC2045 rules for 8bit text.
If set to true, and a message has some valid and
some invalid addresses, send the message anyway,
reporting the partial failure with a
mail.smtp.sendpartial boolean
SendFailedException. If set to false (the default),
the message is not sent to any of the recipients if
there is an invalid recipient address.

When using JavaMail to encode various header fields and the message body,
what can you expect a client to handle on the other end? Which character
sets can you expect all commonly used clients to recognize? Which fields
will they decode? Do they adhere to the RFC822 and RFC2047 standards?
Location: http://www.jguru.com/faq/view.jsp?EID=470776
Created: Aug 7, 2001
Author: Jeff Gay (http://www.jguru.com/guru/viewbio.jsp?EID=468673) Question
originally posed by Mitchell Ratisher
(http://www.jguru.com/guru/viewbio.jsp?EID=277206

The MIME standards always default to the US English character set; ASCII. If you
want to guarantee that the message is going to be readable then use the default;
ASCII.

If the mail client is MIME compliant then all fields can be encoded, both delivery and
character set.

Where can I learn more about the business and legal issues of bulk mail?
Location: http://www.jguru.com/faq/view.jsp?EID=474535
Created: Aug 12, 2001
Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708)
Question originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

One of the resources known to me, that covers the legal issues of this topic to some
extent, is http://www.spamlaws.com.
However, I guess there is too much information out there to be covered by one
answer, thus it is maybe best to start and then append other sources by
commenting.

How can I get the sender email of the received mail?


Location: http://www.jguru.com/faq/view.jsp?EID=477094
Created: Aug 14, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by krishna kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=473175

The getFrom() of Message returns an array. You can't just call


aMessage.getFrom().toString().

Does JavaMail support Multipart nesting? When trying to read a "System


Administrator" rejection message (w/attachment) from Exchange, the
original getContent() returns a Multipart. However in the original message
(2nd Part of Multipart) the attachment is lumped in with the Part
(text/plain) of the original message. How do I access the attachment in this
situation?
Location: http://www.jguru.com/faq/view.jsp?EID=478719
Created: Aug 17, 2001 Modified: 2001-11-12 17:06:50.562
Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708)
Question originally posed by Sean Hignett
(http://www.jguru.com/guru/viewbio.jsp?EID=242642

It is possible to access all the parts of a message, even if they are nested multiparts.
One possible approach is to work recursively and "flatten" out the parts into one
straight list (this is the one I prefer, even if it does not reflect exactly how the
message looks like "architecturally").
You start from:
[...]
if(msg.isMimeType("multipart/*")) {
//get main body part
Multipart mp=(Multipart)msg.getContent();

//build flatlist
List partlist=new ArrayList(10); //example, use your own size idea
buildPartInfoList(partlist,mp);
}
[...]
And the recursive method is:
[...]
private void buildPartInfoList(List partlist, Multipart mp)
throws Exception {

for (int i=0; i<mp.getCount(); i++) {


//Get part
Part apart=mp.getBodyPart(i);
//handle single & multiparts
if(apart.isMimeType("multipart/*")) {
//recurse
buildPartInfoList(partlist,(Multipart)apart.getContent());
} else {
//append the part
partlist.add(apart);
}
}
}//buildPartList
[...]
The list partlist will afterwards contain all the parts that have been encountered
with the multipart message.

If you do not like this approach, you can easily extract the idea of how to retrieve a
specific nested part from the code above.

Comments and alternative answers

Is it possible to send Multipart nested messages.


Author: Owen Fellows (http://www.jguru.com/guru/viewbio.jsp?EID=489718), Sep
4, 2001
I am currently sending a text and html multipart message using the "alternative" sub
type in the MimeMultipart. Now i also want to attach an image to the email. The
problem is i can't attach the image to the alternative MimeMultipart as it doesn't show.
If i remove the "alternative" sub type the text or html attachment shows as well. Is
there a solution? Thanks in advance Owen Fellows

Re: Is it possible to send Multipart nested messages.


Author: Matt Newberry (http://www.jguru.com/guru/viewbio.jsp?EID=528009),
Oct 28, 2001
Owen: I think this will answer your question:

http://www.jguru.com/forums/view.jsp?EID=528015

Misinterpretation of Nested Multipart messages


Author: Ashok Naidu (http://www.jguru.com/guru/viewbio.jsp?EID=481705), Sep 6,
2001
I am able to interprete the nested multipart message, thanx to ur information.But the i
am not able to interprete one particular message.this message has nested multipart
upto three levels. the message looks like this.

<html> html messages...


</html>
------=_NextPart_000_4a97_1507_9e6
Content-Type: message/rfc822
X-Apparently-To: test
X-Track: 1: 40
Received: from test
Received: (from test)
Received: test
Message-ID: messge-id
From: test To: test@domain
Cc: test@domain
Subject: test
Date: test
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="----
=_NextPart_000_00CB_01C11C16.7F585C40"
X-Priority: 3
X-MSMail-Priority: Normal
X-Mailer: Microsoft Outlook Express 5.00.2314.1300
X-MimeOLE: Produced By Microsoft MimeOLE V5.00.2314.1300
Content-Length: 849839
This is a multi-part message in MIME format.
------=_NextPart_000_00CB_01C11C16.7F585C40
........................

The message having contentType as message/rcf is not taken as Multipart, but as


part.All other email service interprets it properly. Javamail seems to fail in this regard.
Can i handle this situation in javamail.

Re: Misinterpretation of Nested Multipart messages


Author: Shu Chen (http://www.jguru.com/guru/viewbio.jsp?EID=520602), Oct 15,
2001
Have you read the demo program msgshow.java in javamail/demo directory? I
think it can solve your problem.

The above main answer does answer only a part of the problem. There is more to
it.
Author: Prasad Nutalapati (http://www.jguru.com/guru/viewbio.jsp?EID=551763),
Jan 15, 2002

The problem expressed by Dieter Wimberger could also happen like this. In your
email body, you can drag and drop another email message previously sent to you.
This embedded email message might contain some two attached files. Then the
structure of the overall message would look like this.

<Multipart>

<text-plain>main body text </text-plain>

<message-rfc822>
body of the embedded mail as INLINE content.

<text-plain> file1 mentioned as ATTACHMENT </text-plain>

<text-plain> file2 mentioned as ATTACHMENT </text-plain>

</message-rfc822>

</Multipart>

Now when using either suggested flat-out method or architecturally "correct" method
of hierarchial method, you will fail to store those attached files file1, and file2. What
actually happens is since embedded email is reported as INLINE content, whole
content of the embedded email along with its attached files, will be treated as part of
the main email body. To store the attached files from the embedded email, what can
be done ? Thanks in advance.

Prasad.

multipart messages problem (text/plain text/html inline text/html)


Author: Boris Milasinovic (http://www.jguru.com/guru/viewbio.jsp?EID=483088),
Apr 3, 2002
This solution shows how to parse multipart messages but imagine this problem:
Parsing mail which consists of these parts:
text/plain
text/html
text/html
text/html
The last 2 html files are inline, and the first and second part are basicaly same
(OExpress send it in text/html format).
My question is: Is there any way to determine that first 2 parts are in fact same thing,
so I won't display both of them?
Why can't I append a message to the POP3 folder?
Location: http://www.jguru.com/faq/view.jsp?EID=479343
Created: Aug 19, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The appendMessages(Message[]) method of Sun's POP3 provider


(com.sun.mail.pop3.POP3Folder) always throws MethodNotSupportedException
because the POP3 protocol doesn't support appending messages.

How do I get the UID for a specific POP3 message?


Location: http://www.jguru.com/faq/view.jsp?EID=479346
Created: Aug 19, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

This is dependent on the provider you are using. With Sun's POP3 provider, you can
cast the Folder to a com.sun.mail.pop3.POP3Folder and ask for the UID with
getUID(Message). This will return the UID as a String, or null if not available.
Comments and alternative answers

Sample code
Author: Stephen Olaño (http://www.jguru.com/guru/viewbio.jsp?EID=28825), Nov 5,
2001
Folder folder;
folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);

...

/** gets the uid of message */


public static String getUID(Message msg) throws MessagingException {
String uid = null;
try {
FetchProfile fp = new FetchProfile();
fp.add(UIDFolder.FetchProfileItem.UID);
folder.fetch(message, fp);
uid = ((com.sun.mail.pop3.POP3Folder)folder).getUID(msg);
} catch (MessagingException me) {
throw me;
}
return uid;
}

How do I get the UID for a specific IMAP message?


Location: http://www.jguru.com/faq/view.jsp?EID=479349
Created: Aug 19, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

This is dependent on the provider you are using. With Sun's IMAP provider you can
cast the Folder to a com.sun.mail.imap.IMAPFolder and call the getUID(Message)
method. This will return the identifier as a long.
Where can I find information on the QUOTA extension of IMAP4?
Location: http://www.jguru.com/faq/view.jsp?EID=479350
Created: Aug 19, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The QUOTA extension is defined by RFC 2087.

Where can I find out more information on IMAP rights and access control
lists?
Location: http://www.jguru.com/faq/view.jsp?EID=479354
Created: Aug 19, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

RFC 2086 defines the IMAP4 ACL extension.

How do I find out the IMAP rights I have on a folder?


Location: http://www.jguru.com/faq/view.jsp?EID=479358
Created: Aug 19, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

This is specific to the IMAP provider. For Sun's IMAP provider this is done by casting
the Folder to a com.sun.mail.imap.IMAPFolder object. To find the rights for the
currently authenticated user, use myRights(), to find the rights for another
object/user, use listRights().

Where can I find a list of free open relay SMTP mail servers?
Location: http://www.jguru.com/faq/view.jsp?EID=488770
Created: Sep 2, 2001 Modified: 2001-09-02 18:37:26.884
Author: huiming Gu (http://www.jguru.com/guru/viewbio.jsp?EID=485896) Question
originally posed by huiming Gu
(http://www.jguru.com/guru/viewbio.jsp?EID=485896

http://www.sendfakemail.com/fakemail/openrelaylist.asp provides one such list.

How do I attach a database BLOB into a mail message, and send by invoking
Java classes from SQL procedures (in Oracle)?
Location: http://www.jguru.com/faq/view.jsp?EID=498439
Created: Sep 17, 2001 Modified: 2001-09-30 17:14:07.731
Author: Denis Navarre (http://www.jguru.com/guru/viewbio.jsp?EID=495283)
Question originally posed by Yogesh Kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=491071

Here is a solution (for Oracle):

1. Create a class BufferedDataSource to transform a byte array into a DataSource


used to attach the "stream" to the message.
2. Convert the BLOB (here is a BLOB from Oracle) into a byte array to be used in the
DataSource
3. Attach the stream through the DataSource

Create a BufferedDataSource to be used to attach the file:


package lu.ic.visitcard.mail;

import java.io.*;
import java.util.*;
import javax.activation.*;

/**
* DataSource from an array of bytes
* Creation date: (07/06/01 21:22:30)
*/
public class BufferedDataSource implements DataSource {

private byte[] _data;


private java.lang.String _name;

/**
* Creates a DataSource from an array of bytes
* @param data byte[] Array of bytes to convert into a DataSource
* @param name String Name of the DataSource (ex: filename)
*/
public BufferedDataSource(byte[] data, String name) {
_data = data;
_name = name;

/**
* Returns the content-type information required by a DataSource
* application/octet-stream in this case
*/
public String getContentType() {
return "application/octet-stream";

/**
* Returns an InputStream from the DataSource
* @returns InputStream Array of bytes converted into an InputStream
*/
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(_data);

/**
* Returns the name of the DataSource
* @returns String Name of the DataSource
*/
public String getName() {
return _name;

}
/**
* Returns an OutputStream from the DataSource
* @returns OutputStream Array of bytes converted into an OutputStream
*/
public OutputStream getOutputStream() throws IOException {
OutputStream out = new ByteArrayOutputStream();
out.write(_data);
return out;

How to get a byte array from a BLOB:

byte[] bytearray;
BLOB blob = ((OracleResultSet) rs).getBLOB("IMAGE_GIF");
if (blob != null) {

BufferedInputStream bis = new BufferedInputStream(blob.getBinaryStream());


ByteArrayOutputStream bao = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int length = 0;
while ((length = bis.read(buffer)) != -1) {
bao.write(buffer, 0, length);

}
bao.close();
bis.close();
bytearray = bao.toByteArray();

How to attach the file:

// Create attachment zone


MimeBodyPart att = new MimeBodyPart();
// Attach the file or buffer
BufferedDataSource bds = new BufferedDataSource(bytearray, "AttName");
att.setDataHandler(new DataHandler(bds));
att.setFileName(bds.getName());

Where can I find the JavaMail specification?


Location: http://www.jguru.com/faq/view.jsp?EID=507251
Created: Sep 30, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7
The specification is available as a PDF file from
http://java.sun.com/products/javamail/JavaMail-1.2.pdf.

How can I add S/MIME support to JavaMail?


Location: http://www.jguru.com/faq/view.jsp?EID=507254
Created: Sep 30, 2001 Modified: 2001-09-30 17:26:48.158
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

You basically need to get an S/MIME provider:

• ISNetworks

Please add additional providers as feedback.


Comments and alternative answers

More S/MiME providers


Author: Eugene Kuleshov (http://www.jguru.com/guru/viewbio.jsp?EID=442441),
Oct 3, 2001
http://www.wedgetail.com/jcsi/index.html

http://www.baltimore.com/keytools/smime/

http://jcewww.iaik.tu-graz.ac.at/products/smime/index.php

https://www.entrust.com/developer/workshop/ettkjava_relnotes.htm

Are there any ColdFusion extensions that use JavaMail?


Location: http://www.jguru.com/faq/view.jsp?EID=507256
Created: Sep 30, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

There is a replacement for CFPOP from Infranet that does this.

How can I get my POP mail from a J2ME device?


Location: http://www.jguru.com/faq/view.jsp?EID=507258
Created: Sep 30, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

Check out the J2ME Pop3 Email package from Nextel.

How do I specify a port other then the default to get my POP mail?
Location: http://www.jguru.com/faq/view.jsp?EID=507284
Created: Sep 30, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

You need to specify the port by setting the mail.pop3.port property:


props.put("mail.pop3.port", "1234");

My SMTP server supports 8-bit MIME. How can I tell JavaMail to use it?
Location: http://www.jguru.com/faq/view.jsp?EID=507286
Created: Sep 30, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

Set the mail.smtp.allow8bitmime property to true:


props.put("mail.smtp.allow8bitmime", "true");

This works with Sun's SMTP provider. Other providers may differ. According to the
docs:

If set to true, and the server supports the 8BITMIME extension, text parts of
messages that use the "quoted-printable" or "base64" encodings are converted to
use "8bit" encoding if they follow the RFC2045 rules for 8bit text.

Is it possible to send messages if some of the addresses are invalid? By


default, if any addresses are invalid the message isn't sent.
Location: http://www.jguru.com/faq/view.jsp?EID=507288
Created: Sep 30, 2001 Modified: 2002-01-01 08:04:39.616
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

You need to set the mail.smtp.sendpartial property to true:


props.put("mail.smtp.sendpartial", "true");
By default, this is false. The partial failure will trigger a SendFailedException.

This assumes the SMTP server is setup not to fail multiple recipient mail if any
address is invalid.

Is it possible to disable the caching of STATUS command responses?


Location: http://www.jguru.com/faq/view.jsp?EID=507294
Created: Sep 30, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

Setting the mail.imap.statuscachetimeout property to zero will disable the


caching. By default, the cache setting is 1 second (1000).
props.put("mail.imap.statuscachetimeout", "0");
Does the JavaMail search library simply just iterate thru a
Folder.getMessages() call and perform comparisons?
Location: http://www.jguru.com/faq/view.jsp?EID=514416
Created: Oct 8, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

For IMAP, the search turns into a command that's sent to the server, where the real
search happens, using whatever optimizations the IMAP server might implement.

For POP3, the search happens locally, as described.

How can I set the Message-ID header for a message via JavaMail?
Location: http://www.jguru.com/faq/view.jsp?EID=516514
Created: Oct 10, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Mary Jane
(http://www.jguru.com/guru/viewbio.jsp?EID=516494

You'll need to subclass MimeMessage and override the updateHeaders() method. In


the subclass, call super.updateHeaders(), then set the Message-ID header for your
custom header value.
Comments and alternative answers

How can I set the Message-ID header for a message via JavaMail? Example:
Author: Sal Ingrilli (http://www.jguru.com/guru/viewbio.jsp?EID=855210), Apr 25,
2002
MimeMessage m = new MimeMessage (session) {

protected void updateHeaders ()


throws MessagingException {

// let the base set the headers


super.updateHeaders ();

// the header name


final String messageIdName = "Message-ID";

// log javaMail generated header


String javaMailHeader = super.getHeader (messageIdName) [0];
logger.info ("JavaMail generated message id: \"" + javaMailHeader
+ "\"");
logger.info ("JavaMail generated message id changed to: \"" +
messageId + "\"");

// change the header to be our id


super.setHeader (messageIdName, messageId);
}
};

How do I get a list of available providers?


Location: http://www.jguru.com/faq/view.jsp?EID=518835
Created: Oct 12, 2001
Author: Jens Dibbern (http://www.jguru.com/guru/viewbio.jsp?EID=9896) Question
originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

The javax.mail.Session class has a method getProviders() which returns an array of


javax.mail.Provider objects.

How can you specify a group list as a recipient of a message?


Location: http://www.jguru.com/faq/view.jsp?EID=519018
Created: Oct 12, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Stephen Smith
(http://www.jguru.com/guru/viewbio.jsp?EID=289196

Short answer, with Sun's SMTP provider you can't.

Longer answer: SMTP requires the individual names within the group list to be
specified in separate RCPT commands. Sun's SMTP provider sends them as a single
command and the server rejects them. You can create an InternetAddress for the
group list, the sending though will fail.

Background:
Group lists are a specific type of valid email address in the RFC822 spec under
section A.1.5. The 'To:' header of an email sent to a group list would look like:

To: Announcements: joe@terse.org, fred@barney.edu;

To: Comment: address, address;

They allow you to provide a comment on the list of people who are receiving the
email. The comment above is "Announcements". The interesting thing is that the
addresses portion may be blank leaving you with just the comment portion:

To: Undisclosed-Recipients:;

Using a group list with a blank address section is a standard list server technique.

How can I redirect the output of session.setDebug(true) so that I can


capture it in the program that uses it?
Location: http://www.jguru.com/faq/view.jsp?EID=523526
Created: Oct 17, 2001 Modified: 2001-10-18 08:11:03.415
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Andrew Cao
(http://www.jguru.com/guru/viewbio.jsp?EID=523514

The messages are hardcoded to go to System.out. The best you can do is redirect
System.out to a ByteArrayOutputStream:
session.setDebug(true);
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os);
// save output
PrintStream old = System.out;
// change output
System.setOut(ps);
// send
...
// reset output
System.setOut(old);
System.out.println(os);

Why do I keep getting the following exception when using POP with
JavaMail?

Exception in thread "main" java.lang.NoSuchFieldError: contentStream


Location: http://www.jguru.com/faq/view.jsp?EID=523542
Created: Oct 17, 2001 Modified: 2001-10-18 08:12:08.356
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Srinivas Velivela
(http://www.jguru.com/guru/viewbio.jsp?EID=385777

This happens when you mix the JavaMail 1.1 and JavaMail 1.2 runtime classes. If I
remember correctly, you are using the 1.1 POP classes with the 1.2 core classes.
Check your CLASSPATH and remove the 1.1 classes (or the 1.2 ones). Remember
that 1.2 comes with a POP3 provider in the main mail.jar file so you don't need to
add another.

Is there anything special that must be done to send messages with JavaMail
via the MS Exchange Server?
Location: http://www.jguru.com/faq/view.jsp?EID=525071
Created: Oct 19, 2001
Author: Scott Warren (http://www.jguru.com/guru/viewbio.jsp?EID=261280)
Question originally posed by Igor Artimenko
(http://www.jguru.com/guru/viewbio.jsp?EID=520776

Check in the Managament Console that you have the Internet Mail Connector
installed and running the IMC will listen on Port 25 and allow you to use the SMTP
protocol.

The API for Exchange is MAPI. SMTP should work fine if you have the IMC installed.

If I construct a user flag by passing a String to the Flags constructor, and


then call message.setFlags(userFlag, true),
message.getFlags().contains(userFlagString) is returning false. What's up?
Location: http://www.jguru.com/faq/view.jsp?EID=526446
Created: Oct 21, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

According to Bill Shannon, the primary JavaMail engineer at Sun, this is apprarently a
bug. Instead of passing the string to the constructor, he suggests the following as a
workaround:
Flags flags = new Flags();
flags.add(userFlagString);
message.setFlags(flags, true);
Comments and alternative answers

What are user flags ?


Author: Christopher Lupton (http://www.jguru.com/guru/viewbio.jsp?EID=877975),
Sep 18, 2003
What are these Flags used for ? Where can I learn more about them and why they
would be useful in relation to JavaMail.

How can I get the full name of the recipient of a message?


Location: http://www.jguru.com/faq/view.jsp?EID=532223
Created: Oct 28, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Imran Mustafa
(http://www.jguru.com/guru/viewbio.jsp?EID=512725

You can check to see if the Address returned by methods like getFrom() or
getRecipients() is of type InternetAddress. Assuming it is, you can then call
getPersonal().

Does JavaMail support creation of mail with nested MimeMultiParts?


Location: http://www.jguru.com/faq/view.jsp?EID=532257
Created: Oct 28, 2001 Modified: 2001-11-12 17:05:46.483
Author: Matt Newberry (http://www.jguru.com/guru/viewbio.jsp?EID=528009)
Question originally posed by Matt Newberry
(http://www.jguru.com/guru/viewbio.jsp?EID=528009

Background:
To add a file attachment to multipart/alternative email (plain part + html part), I
need to create the "alternative" MimeMultiPart, adding the plain and html Parts to it;
then create a "mixed" MimeMultiPart, adding both the alternative multipart and the
file attachment Parts to it. The MultiPart.addBodyPart() method does not support
adding another MultiPart.
The solution is the create both an "alternative" MimeMultipart and a "mixed"
MimeMultipart. Add the "plain" and "html" MimeBodyParts to the alternative
MimeMultipart. Then create an empty MimeBodyPart and call it's setContent()
method, passing in the alternative MimeMultipart. Now add that MimeBodyPart to the
mixed MimeMultipart and, finally, add any attachments as additional mixed
MimeBodyParts.

Whew! Describing it is more labor than doing it. Maybe this code snippet will make it
clearer:

Message msg;
MimeBodyPart plainPart = new MimeBodyPart();
MimeBodyPart htmlPart = new MimeBodyPart();
Vector attachments = new Vector();

private void buildMessage() throws MessagingException {


Multipart alt = new MimeMultipart("alternative");
alt.addBodyPart(plainPart);
alt.addBodyPart(htmlPart);

if (attachments.size() == 0)
msg.setContent(alt);
else {
Multipart mixed = new MimeMultipart("mixed");
MimeBodyPart wrap = new MimeBodyPart();
wrap.setContent(alt); // HERE'S THE KEY
mixed.addBodyPart(wrap);
Enumeration att = attachments.elements();
while (att.hasMoreElements()) {
mixed.addBodyPart((MimeBodyPart)att.nextElement());
}
msg.setContent(mixed);
}
}

How the send the contents of a dynamically generated page by email?


Location: http://www.jguru.com/faq/view.jsp?EID=534404
Created: Oct 30, 2001
Author: Nitesh Naveen (http://www.jguru.com/guru/viewbio.jsp?EID=515443)
Question originally posed by sabu vs PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=476248

The document.body.innerText property contains the page contents, just use that in
a mailto link as the body.

Here is an example to show how you can get the contents of the html. This works in
Internet Explorer only though. I couldn't find an alternative in Netscape. Also there is
some probs with the alignment of the text in the mailer...(Microsoft Outlook)

<html>
<head>
<script>
function mailDoc() {
parent.location="mailto:mailid@example.com?body="+document.body.innerText;
}
</script>
</head>
<body>
line 1<br>
line 2<br>
line 3<br>
line 4<br>
line 5<br>
line 6<br><br>
<form>
<input type=button value="Mail Contents" onclick="mailDoc()">
</form>
</body></html>

How can I send an email to a user supplied email address with an HTML
form?
Location: http://www.jguru.com/faq/view.jsp?EID=534420
Created: Oct 30, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

<form action="" name="myform" method="post" enctype="text/plain"


onSubmit="document.myform.action = 'mailto:' +
document.myform.address.value">
Address: <input type="text" name="address"> <P>
Content: <textarea name="content"></textarea><P>
<input type="submit" value="Submit">
</form>

If I have a complete message in an InputStream, how can I construct a


Message from it?
Location: http://www.jguru.com/faq/view.jsp?EID=544230
Created: Nov 10, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Serkan Ketenci
(http://www.jguru.com/guru/viewbio.jsp?EID=509873

Just create an InputStream with the messge and call the MimeMessage constructor
that accepts the input stream. For instance, if your message was in the file
message.txt:
Subject: Testing
To: Me <foo@example.net>
From: "You" <bar@example.com>

The content.
You can send with the following program, passing in your SMTP server and filename
as args:
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;

public class MailExample {


public static void main (String args[]) throws Exception {
String host = args[0];
String filename = args[1];

// Get system properties


Properties props = System.getProperties();

// Setup mail server


props.put("mail.smtp.host", host);

// Get session
Session session = Session.getDefaultInstance(props, null);

// Get InputStream
FileInputStream fis = new FileInputStream(filename);

// Create message
MimeMessage message = new MimeMessage(session, fis);
// Send message
Transport.send(message);
}
}

How do I add a MultiPart to a MultiPart? The API only seems to allow adding
BodyPart's.
Location: http://www.jguru.com/faq/view.jsp?EID=545920
Created: Nov 12, 2001
Author: Walid "BigW" Gedeon
(http://www.jguru.com/guru/viewbio.jsp?EID=543181) Question originally posed by
didier chaumond (http://www.jguru.com/guru/viewbio.jsp?EID=12895

BodyPart implements the Part interface where you can set it's contents to be a
Multipart: setContent(Multipart).

How do I attach multiple files to a message?


Location: http://www.jguru.com/faq/view.jsp?EID=548245
Created: Nov 15, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by kdhawan dhawan
(http://www.jguru.com/guru/viewbio.jsp?EID=509463

You just need to combine them all into one MimeMultipart and add each one as its
own MimeBodyPart. The following does just this, taking a directory name as the
argument, sending everything within the directory as attachments in one message.
Use with care as the program doesn't limit the message size.
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.io.*;

public class AttachExample {


public static void main (String args[]) throws Exception {
String host = args[0];
String from = args[1];
String to = args[2];
String directory = args[3];

Properties props = System.getProperties();

props.put("mail.smtp.host", host);

Session session = Session.getInstance(props, null);

Message message = new MimeMessage(session);


message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("Directory Attachments");

BodyPart messageBodyPart = new MimeBodyPart();


messageBodyPart.setText("Directory: " + directory);

Multipart multipart = new MimeMultipart();


multipart.addBodyPart(messageBodyPart);

File dir = new File(directory);


String list[] = dir.list();

for (int i=0, n=list.length; i<n; i++) {


File f = new File(list[i]);
if (f.isFile()) {
System.out.println("Adding: " + list[i]);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(list[i]);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(list[i]);
multipart.addBodyPart(messageBodyPart);
}
}
message.setContent(multipart);

Transport.send(message);
}
}
Comments and alternative answers

H2 make it work
Author: Eric Bilange (http://www.jguru.com/guru/viewbio.jsp?EID=995147), Sep 5,
2002
Found this snippet useful and clear example. However it does not work. You should
read toward the end in the loop appending files:
for (int i=0, n=list.length; i<n; i++) {
File f = new File(directory + list[i]);
if (f.isFile()) {
System.out.println("Adding: " + list[i]);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(directory + list[i]);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(list[i]);
multipart.addBodyPart(messageBodyPart);
}
}

Since retrieved file names are just names without the path.

How do you create a new IMAPMessage? The IMAPMessage contructor is


protected. [I am copying the attributes of a source Message to a new
IMAPMessage object which will be appended to a different Store. After this
process, I need to extract the UID of the IMAPMessage which is not
available with the superclasses (Message and MimeMessage).]
Location: http://www.jguru.com/faq/view.jsp?EID=565637
Created: Nov 28, 2001
Author: allen petersen (http://www.jguru.com/guru/viewbio.jsp?EID=105938)
Question originally posed by Javi Tabemoor
(http://www.jguru.com/guru/viewbio.jsp?EID=441109

Let the Store create it for you.

No, really. Create your new MimeMessage. Call Folder.appendMessages() on the


target folder. Listen for the resulting MessageCountEvent telling you that the
message has been added. Use MessageCountEvent.getMessages() to get the newly
added message. This message will be a proper IMAPMessage, and you should be able
to use UIDFolder.getUID() on it.

How can I send a binary output stream as an attachment, without saving


the content to a file?
Location: http://www.jguru.com/faq/view.jsp?EID=566428
Created: Nov 29, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by r devserver
(http://www.jguru.com/guru/viewbio.jsp?EID=566058

You need to encode the content so that it is 7-bit safe. Use


MimeUtility.encode(OutputStream stream, String encoding) to encode the content

What encodings/decodings are supported by the JavaMail API?


Location: http://www.jguru.com/faq/view.jsp?EID=566429
Created: Nov 29, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

All the encodings defined in RFC 2045 are supported here. This includes "base64",
"quoted-printable", "7bit", "8bit", and "binary". In addition, "uuencode" is supported,
too.

What's the ALL constant of the MimeUtility used for? It has no comments in
the docs.
Location: http://www.jguru.com/faq/view.jsp?EID=566437
Created: Nov 29, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

This constant seems to just be used internally by the class, but is public. It is used
by the package private checkAscii() method to indicates that all the bytes in this
input stream must be checked.

How do I parse a comma-separated list of newsgroups into an array of


Address objects?
Location: http://www.jguru.com/faq/view.jsp?EID=566439
Created: Nov 29, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The NewsAddress class in the javax.mail.internet package can do this for you:
public static NewsAddress[] parse(String newsgroups)
throws AddressException

Does JavaMail support NAMESPACE extentions for IMAP?


Location: http://www.jguru.com/faq/view.jsp?EID=566445
Created: Nov 29, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

As of JavaMail 1.2, this is supported, if the IMAP server supports it.

Who is behind the JavaMail API?


Location: http://www.jguru.com/faq/view.jsp?EID=566449
Created: Nov 29, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The primary responsible party for the JavaMail API is Bill Shannon of Sun. If you
have a question that you suspect is a bug, send it to the mailing list and he'll be sure
to address it.

Where can I find information about JavaMail support for quotas?


Location: http://www.jguru.com/faq/view.jsp?EID=571367
Created: Dec 3, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Quota support is specific to IMAP. The specific support depends on the provider. For
the Sun IMAP provider, package com.sun.mail.imap, you'll find a Quota class and a
getQuota() method for the IMAPStore.

Why am I getting a parsing exception when the content type is something


like "Content-Type: text/html;"?
Location: http://www.jguru.com/faq/view.jsp?EID=571368
Created: Dec 3, 2001 Modified: 2001-12-21 21:27:43.149
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Having a trailing semicolon violates the MIME specification. The JavaMail libraries do
not compensate for this violation. It is supposed to look like the following:
content := "Content-Type" ":" type "/" subtype
*(";" parameter)
parameter := attribute "=" value

Does the JavaMail API provided disconnected support?


Location: http://www.jguru.com/faq/view.jsp?EID=581208
Created: Dec 11, 2001
Author: allen petersen (http://www.jguru.com/guru/viewbio.jsp?EID=105938)
Question originally posed by John Zukowski PREMIUM
(http://www.jguru.com/guru/viewbio.jsp?EID=7

JavaMail provides disconnected support for both IMAP and POP3 in a similar fashion:
access to the messages on the mail server is provided, as is the ability to identify
different instances of a single message across separate connections to the mail store
(using the message's UID). You can also get providers, such as the ones for mbox
and mh, which let you store messages on local filesystems.
That's all that JavaMail itself gives you. When it comes to other operations, such as
copying messages from the server to the local machine and synchronizing the server
and local copies of the mailboxes, the work is left to the applications.

The same may be said for composing messages offline. You can use JavaMail to
create the Message object that will be sent. If, however, you want to save said
message to disk to be sent later, then your application will have to do so explicitly. If
you want all of the queued messages to be sent automatically as soon as your
network connection is back up, then you'll have to write the code that gets your
messages from wherever they've been stored and calls send() on them, too.

Given this information, the question of whether or not the JavaMail API actually
provides disconnected support is up to the interpretation of the individual. :)

Get part of a message .. How can I use the optional POP3 command TOP to
get the beginning of a message?
Location: http://www.jguru.com/faq/view.jsp?EID=581537
Created: Dec 12, 2001
Author: allen petersen (http://www.jguru.com/guru/viewbio.jsp?EID=105938)
Question originally posed by Serkan Ketenci
(http://www.jguru.com/guru/viewbio.jsp?EID=509873

You can't. At least, with the Sun POP3 provider, you can't.

In JavaMail 1.2, the Sun POP3 provider only uses the TOP command to get the
headers of the Message. Any content that is also returned with that usage of the
command is ignored. So there's no really good way for an application using JavaMail
to get the beginning of a message from TOP.

As always with POP3 questions, it is possible that another, third-party POP3 provider
might have that functionality.

How can you use BodyTerm to do a case sensitive search? The superclass'
constructor that enables this isn't exposed.
Location: http://www.jguru.com/faq/view.jsp?EID=582959
Created: Dec 12, 2001
Author: allen petersen (http://www.jguru.com/guru/viewbio.jsp?EID=105938)
Question originally posed by Mahesh Kuruba
(http://www.jguru.com/guru/viewbio.jsp?EID=293288

There are two issues here. The first is the question of getting a SearchTerm whose
match() method will do a case sensitive search. Unfortunately, as you've noticed,
StringTerm's ignoreCase attribute is protected, and none of the subclasses that are
provided in the JavaMail package make it available. To make matters more difficult,
all of StringTerm's non-abstract subclasses are final, so you can't just subclass
them and set the ignoreCase flag to false.

So that pretty much means that we have to write our own subclass of StringTerm. A
trivial example, which doesn't even handle messages with attachments, would be

import javax.mail.*;
import javax.mail.search.*;

public class CaseSensitiveBodyTerm extends StringTerm {

public CaseSensitiveBodyTerm(String pattern) {


super(pattern, false);
}

public boolean match(Message msg) {


try {
Object content = msg.getContent();
if (content instanceof String) {
return super.match((String)content);
} else {
return false;
}
} catch (Exception e) {
return false;
}
}

Now, there is a second problem that you may run into. If you're using IMAP, the
IMAP provider will use the IMAP SEARCH functionality to do a Folder.search() call
for you. This is much more efficient than downloading every message in your folder
to your client and then doing the search on the local messages. Unfortunatley, since
the IMAP SEARCH command is defined to be case insensitive, that latter method is
exactly what the search call will fall back to if you use this custom case sensitive
SearchTerm. For large folders, this search could take upwards on forever. In cases
like that, you're probably better off making a special case that does the case
insensitive search on the server, and then filters the responses by the case sensitive
search.

Where can I get the JavaMail API docs?


Location: http://www.jguru.com/faq/view.jsp?EID=705106
Created: Dec 29, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

These come with the download of the implementation of the JavaMail API or J2EE.
You can view the 1.2 API javadocs online at
http://java.sun.com/products/javamail/1.2/docs/javadocs/. The older 1.1 version are
not available online.

Where can I find the API docs for the JavaBeans Activation Framework?
Location: http://www.jguru.com/faq/view.jsp?EID=705108
Created: Dec 29, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

These come with the implementation download and with J2EE. They do not come
with the JavaMail implementation. You can view them online at
http://java.sun.com/products/javabeans/glasgow/javadocs/.
Where can I find out about LDAP support with JAMES?
Location: http://www.jguru.com/faq/view.jsp?EID=705109
Created: Dec 29, 2001 Modified: 2003-02-25 21:58:30.898
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

http://james.apache.org/usingLDAP_v1_2.html provides a guide to the experimental


LDAP support available.

Where can I find a JSP tag library for sending mail from JSP pages via the
JavaMail API?
Location: http://www.jguru.com/faq/view.jsp?EID=705110
Created: Dec 29, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Sourceforge provides a library at http://sourceforge.net/projects/jsptags/. There is


also an article at Sun that discusses this:
http://java.sun.com/jdc/technicalArticles/javaserverpages/emailapps/.

Where can I find an MH provider?


Location: http://www.jguru.com/faq/view.jsp?EID=705111
Created: Dec 29, 2001
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

You can store your mail messages locally with the local store provider available at
http://trustice.com/java/icemh/.

I'm sure there are others out there. Please add feedback if you are aware of them.

What's the parameter to the message.reply(boolean) method for?


Location: http://www.jguru.com/faq/view.jsp?EID=708369
Created: Jan 3, 2002
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Minh Tri Tran
(http://www.jguru.com/guru/viewbio.jsp?EID=706455

Passing in a value of true is like reply to all. Assuming the message was addressed to
you, you would get a copy back. In addition, everyone else on the TO, CC and FROM
list would get a copy. Otherwise, only who the message was from would get the
reply.

If I want to manually create a reply message, how do I find out where to


direct the message?
Location: http://www.jguru.com/faq/view.jsp?EID=708371
Created: Jan 3, 2002
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

While you could call getFrom() directly, the better thing to do is call the getReplyTo()
method of Message.

How do I clone a JavaMail message (MimeMessage)?


Location: http://www.jguru.com/faq/view.jsp?EID=711834
Created: Jan 7, 2002
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Joey Bernsen
(http://www.jguru.com/guru/viewbio.jsp?EID=587278

MimeMessage newOne = new MimeMessage(oldOne);

Is there a limitation to the email headers that are settable from JavaMail?
For instance, can you set the 'Received' header, indicating which server
you're sending from?
Location: http://www.jguru.com/faq/view.jsp?EID=721460
Created: Jan 15, 2002
Author: Jeff Gay (http://www.jguru.com/guru/viewbio.jsp?EID=468673) Question
originally posed by J Craig (http://www.jguru.com/guru/viewbio.jsp?EID=339297

There's no limitation as to the headers you can set using the JavaMail API. You can
set any headers desired. Of course, once the message is sent, mail servers will add
and change headers themselves, and ignore headers previously set. You can get
more information on which "agents" set headers by reading the MIME standards.

How do I find out the mail message size before sending?


MimeMessage.getSize() keeps reporting -1.
Location: http://www.jguru.com/faq/view.jsp?EID=726102
Created: Jan 18, 2002
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The simplest way is to write the message to a ByteArrayOutputStream and check its
size:
ByteArrayOutputStream bais = new ByteArrayOutputStream();
message.writeTo(bais);
System.out.println(bais.size());

How do I change the content of a mime message bodypart and send out the
updated message without having to copy it into a new message object?
.saveChanges() doesn't help here...
Location: http://www.jguru.com/faq/view.jsp?EID=727496
Created: Jan 20, 2002
Author: Jeff Gay (http://www.jguru.com/guru/viewbio.jsp?EID=468673) Question
originally posed by matthias hofschen
(http://www.jguru.com/guru/viewbio.jsp?EID=305010

You can't. You have to make a new message because the saveChanges() method
only affects the message within it's scope, i.e. the original provider's session.

Where can I find a list of known bugs for JavaMail?


Location: http://www.jguru.com/faq/view.jsp?EID=732255
Created: Jan 23, 2002
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by sharona feinberg
(http://www.jguru.com/guru/viewbio.jsp?EID=581672

Same as the rest of Java.


Go to http://java.sun.com/jdc/bugParade/. Search for JavaMail.

When sending mail through MS Exchange 200, I keep getting


421 Too many errors on this connection -- closing Any idea???
Location: http://www.jguru.com/faq/view.jsp?EID=740981
Created: Jan 30, 2002
Author: julien cool (http://www.jguru.com/guru/viewbio.jsp?EID=473366) Question
originally posed by julien cool
(http://www.jguru.com/guru/viewbio.jsp?EID=473366

Exchange has a limit on the number of mail messages that can be sent across a
single SMTP connection. If you hit this limit, then you'll get this message.

In MS Exchange 2000 (and it seems in SMTP Server coming with IIS), there is a
properties panel in the Default SMTP Server named "Messages" where you can tune :

• size of one message


• number of mails by connection (default is 20)
• total size of messages in one session
• recipients by message

See
http://www.microsoft.com/technet/treeview/default.asp?url=/TechNet/prodtechnol/e
xchange/deploy/depovg/exinfflo.asp for more information.

Where can I find out about the format of the Outlook Contacts database and
the Exchange and Outlook Message and Public folders?
Location: http://www.jguru.com/faq/view.jsp?EID=740997
Created: Jan 30, 2002
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

See the MSDN article at http://msdn.microsoft.com//library/en-


us/dnout98/html/olexcoutlk.asp that describes how to access Microsoft Exchange
and Outlook data using Visual Basic.

I'm getting a javax.mail.MessagingException: 501 unacceptable mail


address thrown from my program, what can the problem be?
Location: http://www.jguru.com/faq/view.jsp?EID=741012
Created: Jan 30, 2002
Author: Florin Rapan (http://www.jguru.com/guru/viewbio.jsp?EID=385219)
Question originally posed by Florin Rapan
(http://www.jguru.com/guru/viewbio.jsp?EID=385219

Some SMTP servers require that the FROM user be registered with the domain.

If "anonymous" does not work, than try a registered user.

How can I create an HTML message which will contain multiple images?
Location: http://www.jguru.com/faq/view.jsp?EID=741046
Created: Jan 30, 2002 Modified: 2002-09-16 04:53:57.576
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by anthony nolan
(http://www.jguru.com/guru/viewbio.jsp?EID=242190

Extending the single image FAQ to multiple images works fine. The extra images
should not be treated as attachments, vs. inline images:
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class HtmlImageExample {


public static void main (String args[]) throws Exception {
String host = args[0];
String from = args[1];
String to = args[2];
String file = args[3];
String file2 = args[4];

// Get system properties


Properties props = System.getProperties();

// Setup mail server


props.put("mail.smtp.host", host);

// Get session
Session session = Session.getDefaultInstance(props, null);

// Create the message


Message message = new MimeMessage(session);

// Fill its headers


message.setSubject("Embedded Image");
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new
InternetAddress(to));

// Create your new message part


BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<H1>Hello</H1>" +
"<img src=\"cid:memememe\"><p>" +
"<img src=\"cid:youyouyou\">";
messageBodyPart.setContent(htmlText, "text/html");

// Create a related multi-part to combine the parts


MimeMultipart multipart = new MimeMultipart("related");
multipart.addBodyPart(messageBodyPart);

// Create part for the image


messageBodyPart = new MimeBodyPart();

// Fetch the image and associate to part


DataSource fds = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID","<memememe>");

// Add part to multi-part


multipart.addBodyPart(messageBodyPart);

// Create 2nd part for the image


messageBodyPart = new MimeBodyPart();

// Fetch the image and associate to part


DataSource fds2 = new FileDataSource(file2);
messageBodyPart.setDataHandler(new DataHandler(fds2));
messageBodyPart.setHeader("Content-ID","<youyouyou>");

// Add part to multi-part


multipart.addBodyPart(messageBodyPart);

// Associate multi-part with message


message.setContent(multipart);

// Send message
Transport.send(message);
}
}
Comments and alternative answers

Suggestion
Author: Virgil Mocanu (http://www.jguru.com/guru/viewbio.jsp?EID=861598), Apr
30, 2002
I would suggest to set the multipart as "alternative" (i.e. MimeMultipart multipart =
new MimeMultipart("alternative");) because this option will let you to add a
plain/text version of the message. Using "related" and adding a plain/text message
will make the mail client to display the plain/text version of message instead of the
HTML.

What is the disposition of a message?


Location: http://www.jguru.com/faq/view.jsp?EID=750764
Created: Feb 7, 2002
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Content disposition is an optional header (Content-Disposition) that can be used for


an entire message or each part of the message. It can be used to indicate a part is
an attachment, but it is not the only way to indicate a part is an attachment. For
additional information on disposition, you can read RFC 2183.

After marking a message as deleted, is it possible to undo the deletion?


Location: http://www.jguru.com/faq/view.jsp?EID=760799
Created: Feb 15, 2002
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Jeya Selliah
(http://www.jguru.com/guru/viewbio.jsp?EID=743366

Messages aren't deleted until you expunge the folder. If you don't want to the
messages deleted, call close() with a value of false, and/or don't call expunge().
Once you've closed the folder with close(true) or called expunge(), the message is
gone.

How reliably can JavaMail parse messages?


Location: http://www.jguru.com/faq/view.jsp?EID=761125
Created: Feb 16, 2002
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Bob Dickinson of Brute Squad Labs wrote up an article that describes the reliableness
of the API, along with a handful of problems he identified.

What is folding?
Location: http://www.jguru.com/faq/view.jsp?EID=764371
Created: Feb 19, 2002
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

According to RFC 822, folding is the process of splitting a header field into multiple
lines.

How do I fold a ParameterList?


Location: http://www.jguru.com/faq/view.jsp?EID=764373
Created: Feb 19, 2002
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The default (no-arg) toString() method returns the list unfolded. If you need the list
folded, you can pass an int into the toString() method to indicate folding should be
done and how many character positions should be counted for where to start folding.

How do I know about the SMTP and POP3 addresses of the mail service
providers?
Location: http://www.jguru.com/faq/view.jsp?EID=772830
Created: Feb 26, 2002 Modified: 2002-12-26 20:42:15.484
Author: Chandra Patni (http://www.jguru.com/guru/viewbio.jsp?EID=33585)
Question originally posed by Ananthalakshmi Subramaniyam
(http://www.jguru.com/guru/viewbio.jsp?EID=768989

Not every service may provide POP3/IMAP/SMTP support. Even if so, they may
choose to guard it for various reason. You need to contact a particular service
provider for the details.

How to get access to the mailbox where user id contains space in it? I got
few mail users created with space char in it (MS Exchange and Lotus Notes
both). While same code works for the mail users without space char in their
name but it throws AuthenticationFailedException for the mail users with
space char in their name
Location: http://www.jguru.com/faq/view.jsp?EID=772832
Created: Feb 26, 2002
Author: Chandra Patni (http://www.jguru.com/guru/viewbio.jsp?EID=33585)
Question originally posed by AK Sharma
(http://www.jguru.com/guru/viewbio.jsp?EID=759200
For JavaMail 1.2, you don't have do anything for imap authentication if username
contains white spaces. You should add double quotes around user name for
InternetAddress and for client which doesn't do this automcatically. For example, an
imap session using telnet on port 143 would be as follows.
Client>
a001 LOGIN "Chandra Patni" javaiscool
Server>
a001 OK LOGIN completed.
Client>
a002 SELECT INBOX
Server>
* 4 EXISTS
* 0 RECENT
* FLAGS (\Seen \Answered \Flagged \Deleted \Draft)
* OK [PERMANENTFLAGS (\Seen \Answered \Flagged \Deleted \Draft)]
* OK [UNSEEN 2] Is the first unseen message
* OK [UIDVALIDITY 1803] UIDVALIDITY value.
a002 OK [READ-WRITE] SELECT completed.
Client>
a003 LOGOUT
However, the SMTP server seem to have problem with such addresses. I could not
make sendmail/reply work. The following example connects to an Exchange server
and creates a Message which is appended to INBOX.
import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class TestMail1 {


public static void main (String args[]) throws Exception {
String username = "Java Duke";
String password = "welcomeduke";
String host = "myimap.domain.com";
if(args.length == 3) {
username = args[0];
password = args[1];
host = args[2];
}
Session session = Session.getInstance(new Properties(), null);
MimeMessage message = new MimeMessage(session);
InternetAddress from = new InternetAddress("\"Java Duke\"@"+ host);
InternetAddress to = new InternetAddress("\"Java Duke\"@"+ host);
message.setFrom(from);
message.addRecipient(Message.RecipientType.TO, to);
message.setSubject("This message is just added");
message.setText("Welcome Duke");

Store store = session.getStore("imap");


store.connect(host, username, password);

Folder folder = store.getFolder("INBOX");


folder.open(Folder.READ_WRITE);
folder.appendMessages(new Message[] {message});
Message messages[] = folder.getMessages();
for (int i=0, n=messages.length; i<n; i++) {
System.out.println(i + ": " + messages[i].getFrom()[0] + "\t" +
messages[i].getSubject());
}
}
}
The output and command is as follows
>java TestMail1 "Chandra Patni" welcome1 localhost
0: Chandra Patni <"Chandra Patni"@localhost> test
1: <"Java Duke"@localhost> This message is just added
2: <"Java Duke"@localhost> This message is just added
3: <"Java Duke"@localhost> This message is just added

Is there a common solution for checking if a user has email on an Exchange


server from Java code?
Location: http://www.jguru.com/faq/view.jsp?EID=773197
Created: Feb 26, 2002
Author: Eugene Kuleshov (http://www.jguru.com/guru/viewbio.jsp?EID=442441)
Question originally posed by Jason Rosenblum
(http://www.jguru.com/guru/viewbio.jsp?EID=740621

The only pure Java solution for your situation is to enable IMAP gateway at your MS
Exchange server and use the IMAP provider.

You can also develop your own JavaMail provider (i.e. using any Java-to-COM bridge
and native MS MAPI availabe through COM).

Does anyone know of a JavaMail API implementation for Lotus Notes R5?
Location: http://www.jguru.com/faq/view.jsp?EID=774727
Created: Feb 27, 2002
Author: Søren Mathiasen (http://www.jguru.com/guru/viewbio.jsp?EID=278838)
Question originally posed by JOnathan Chapman
(http://www.jguru.com/guru/viewbio.jsp?EID=767315

Since the mailbox in lotus notes is just a notes database, you could use the Notes
Java API supplied by lotus.
Check out: http://www.lotus.com/developers/devbase.nsf/homedata/homejava.

Also, Chandra Patni reports that Lotus supports imap protocol. So you can use the
basic JavaMail API for Lotus.

Comments and alternative answers

Lotus Domino R5 Supports IMAP


Author: Venkat Subramanian (http://www.jguru.com/guru/viewbio.jsp?EID=418608),
Mar 13, 2002
Lotus Domino R5 supports IMAP and seems to work decently with our JavaMail
code. We do extensive Lotus Email processing with JavaMail, and the system seems
to be holding on well. There are couple of implementation bugs in Lotus like -
Copying email in the same Folder does not generate MessageCount event on it etc...
See my posts in this board on it.

Re: Lotus Domino R5 Supports IMAP


Author: JOnathan Chapman
(http://www.jguru.com/guru/viewbio.jsp?EID=767315), Mar 26, 2002
Thanks for your reply. We have enabled IMAP on our R5 server and we can
connect and receive messages using JavaMail. However, if there are lines in the
body of the message longer than 72 characters, then the line gets split at the first
space before the 72nd character, and a newline inserted. This is causing the
processing of data in the message to fail. Have you come across this problem, and
if so what can be done about it?

Re[2]: Lotus Domino R5 Supports IMAP


Author: Venkat Subramanian
(http://www.jguru.com/guru/viewbio.jsp?EID=418608), Mar 27, 2002
We don't deal too much with the body of the message. So I haven't seen that
problem. Thanks for informing anyway! We also work with MS Exchange 5.5
and 2000 - Exchange seems to fold subjects which inserts white spaces if the
subject is long. Lotus Domino R5 IMAP server seem to degrade in performance
as the mail database size grows in size. This is because the IMAP
implementation depends extensively on Lotus views. { For example an IMAP
'EXISTS' which in turn becomes a java mail event gets delayed up to a minute
as database size grows, typically it comes back within a second).

Re[2]: Lotus Domino R5 Supports IMAP


Author: Mario Fernandez
(http://www.jguru.com/guru/viewbio.jsp?EID=848120), Apr 22, 2002
Hi everybody, I still have a problem with Lotus Notes R5 and JavaMail access.
I´ve got a lot of Notes User with Notes Mail System. So now the problem is
that in order to make JavaMail access work, the protocol must be POP3 or
IMAP, because there´s no Notes provider. Changing every user mail system to
Notes would be neraly impossible, so any ideas please? Thanks in advance.

Re: Lotus Domino R5 Supports IMAP


Author: ATUL MADNE (http://www.jguru.com/guru/viewbio.jsp?EID=1036993),
Dec 12, 2002
Hi I'm trying to connect IMAP on Lotus Daomino R5 with javamail. But its giving
error in authentication. Can u send me some sample code. Thanks in advance Atul

Rmail with Lotus


Author: Jaume Ba (http://www.jguru.com/guru/viewbio.jsp?EID=827369), Jul 9,
2002
There are some pleople using Rmail with notes in order to send mails. See:
http://www.java4less.com/mail_e.htm

Re:Problems while accessing Mails for IMAP Account from Lotus Domino
Server using JavaMail API.
Author: Ananthalakshmi Subramaniyam
(http://www.jguru.com/guru/viewbio.jsp?EID=768989), Dec 24, 2002
Hi, Does JavaMail is robust to Lotus Notes Mail Database? Since, we have
developed a EMail Client application which works perfectly with MS-Exchange
Server and when we have tested with Lotus Domino Server, we've faced the
following problems: 1. Cannot able to get Mail Priority(High/Low) Flag 2.
Sometimes, cannot able to get Mails from the InBox.NoContentException is
thrown. 3. and sometimes, not able to view attachments,etc. Can anyone tell me
the solution on this! Settings: 1. IMAP Account 2. IMAP task is running in Lotus
Domino Server Thanks, Ananthalakshmi.H

Re: Re:Problems while accessing Mails for IMAP Account from Lotus
Domino Server using JavaMail API.
Author: Thiadmer Sikkema
(http://www.jguru.com/guru/viewbio.jsp?EID=1079811), Apr 28, 2003

NoContentException means probably that the content is Notes-RTF encoded


instead of MIME.

The Classes for Notes require pretty much custom coding to get the same
result, but are far more flexible.

How to get message id of the mail that is sent (not read)?


Location: http://www.jguru.com/faq/view.jsp?EID=775190
Created: Feb 27, 2002
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by tolga evren
(http://www.jguru.com/guru/viewbio.jsp?EID=530061

You'll need to subclass MimeMessage and get the id from the subclass after the
header has been created. I believe you'll be able to get the generated header/id from
updateHeaders().
Comments and alternative answers

Or just use MimeMessage itself


Author: Peter Hewitt (http://www.jguru.com/guru/viewbio.jsp?EID=578744), Apr 13,
2002
I just used MimeMessage's getMessageID() to get the message id after sending the
message and it worked for me.
...
MimeMessage message = new MimeMessage(session);
transport.sendMessage(message, message.getAllRecipients());
transport.close();

System.out.println("message id = " + message.getMessageID());


How can I access my Hotmail account through the JavaMail API?
Location: http://www.jguru.com/faq/view.jsp?EID=787604
Created: Mar 7, 2002 Modified: 2002-04-11 11:14:30.661
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Hotmail doesn't use POP / IMAP. Instead, it uses a WebDAV based protocol (aka
HTTPMail). There is a provider under development at SourceForge at
http://sourceforge.net/projects/jhttpmail/.
Comments and alternative answers

JDAVMail: a HotMail JavaMail service provider


Author: Luc Claes (http://www.jguru.com/guru/viewbio.jsp?EID=103699), Apr 11,
2002
JDAVMail is a JavaMail service provider allowing JavaMail-compliant clients to
access HotMail mailboxes (read/delete/move/copy mail, create/rename/delete folders,
...). The package was published under the LGPL licence and is available at
http://jdavmail.sourceforge.net.

Does the JavaMail API support embedded uuecoded blocks?


Location: http://www.jguru.com/faq/view.jsp?EID=787899
Created: Mar 7, 2002
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Not directly, though there is nothing to stop you from extending the library to
support it.

What's new for JavaMail 1.3?


Location: http://www.jguru.com/faq/view.jsp?EID=808326
Created: Mar 22, 2002
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The proposed changes for JavaMail 1.3 are listed at


http://java.sun.com/products/javamail/JavaMail-1.3-changes.txt.

Where can I find the sun.net.smtp.SmptClient class?


Location: http://www.jguru.com/faq/view.jsp?EID=818683
Created: Mar 30, 2002 Modified: 2002-12-08 06:56:40.252
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

This class comes with the Sun runtime. As the package name of sun.net implies, it is
non-standard and should not be used directly.

How can I remove headers in JavaMail?


Location: http://www.jguru.com/faq/view.jsp?EID=921226
Created: Jun 20, 2002
Author: Dieter Wimberger (http://www.jguru.com/guru/viewbio.jsp?EID=25708)
Question originally posed by rajesh m
(http://www.jguru.com/guru/viewbio.jsp?EID=473123
The MimeMessage has a method called
removeHeader(String name)
This will remove all headers with a given name.
Note that the folder the message is in will have to be opened READ_WRITE at the
point of modification.
Probably you will want to make a copy and work on the copy
MimeMessage(MimeMessage source)

How can I convert an Outlook mailbox/data file to Linux mbox format?


Location: http://www.jguru.com/faq/view.jsp?EID=935049
Created: Jul 2, 2002
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

There is a project over at Sourceforge that does exactly this for you. Never tried it
myself, but you can grab it from http://sourceforge.net/projects/ol2mbox.

How do I send a mail message at a certain time?


Location: http://www.jguru.com/faq/view.jsp?EID=951553
Created: Jul 16, 2002 Modified: 2002-07-16 11:58:45.935
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Rahul gidwani
(http://www.jguru.com/guru/viewbio.jsp?EID=950302

The java.util.Timer class permits timed execution of events. It is completely


unrelated to what you want to do, like send mail.
Comments and alternative answers

send mail
Author: Andrew Sun (http://www.jguru.com/guru/viewbio.jsp?EID=877680), Jul 19,
2002
An easy way is to create your own runnable mail message object by extending
java.mail.Message, add your own sendTime attribute. Then all you have to do is to
start a timer, constantly checking for this sendTime value, Once System time pass this
sendTime you can create a new thread and send this message off.

Sending timed email


Author: Mark Nuttall (http://www.jguru.com/guru/viewbio.jsp?EID=462679), Jul 23,
2002
Use a scheduler like Quartz.

Re: How do I send a mail message at a certain time?


Author: Daniel Szwalkiewicz (http://www.jguru.com/guru/viewbio.jsp?EID=804798),
Jan 23, 2003
I have been using JCrontab for several months now for similar functionality and
more. Everything from cleaning up log files, to uploading csv files to a database. I
haven't had any issues with it and find it very reliable. If you think a unix-like cron
system would help you out in your timed events, check out
http://jcrontab.sourceforge.net
How to move message from one folder to another?
Location: http://www.jguru.com/faq/view.jsp?EID=1010890
Created: Oct 10, 2002
Author: Asif Sajjad (http://www.jguru.com/guru/viewbio.jsp?EID=1010057)
Question originally posed by chirag patel
(http://www.jguru.com/guru/viewbio.jsp?EID=1006915

Here is the code I am using to move the messages to another folder. In findFolder
method I search for the folder name and then open the folder to read-write.
CurrentFolder is the folder from where the messages are copied to the destination
folder.
public void saveMessages(Message[] mArray, String folderName) throws
Exception{
Folder f = findFolder(folderName);
currentFolder.copyMessages(mArray, f);

// Now the delete the messages from Current Folder


for ( int i = 0; i < mArray.length; i++){
mArray[i].setFlag(Flags.Flag.DELETED, true);
}
currentFolder.expunge();
}

[Keep in mind this is for IMAP only. POP doesn't support folders.]
Comments and alternative answers

How do you get the new UID for the moved message?
Author: Grace L (http://www.jguru.com/guru/viewbio.jsp?EID=1235917), May 9,
2005
Once the message is moved from one folder to another, the UID or message ID is
changed. How do you get the new UID for that message? Thanks, Grace

I want to use formating characters like tab (\t) in my mail messages but
they are having no effect when the MIME type is text. How can I format my
mail message?
Location: http://www.jguru.com/faq/view.jsp?EID=1019675
Created: Oct 30, 2002
Author: Christopher Koenigsberg
(http://www.jguru.com/guru/viewbio.jsp?EID=722897) Question originally posed by
Jagadishwar Reddy Jannapureddy
(http://www.jguru.com/guru/viewbio.jsp?EID=1019000

Tab characters in a text document can be interpreted differently by the program


rendering the document, with different "tab stop" settings rendering them by
different numbers of actual "blank space" characters (4 fixed spaces per tab, 8 fixed
spaces, even possibly variable spacing, or even no spaces at all, as you are seeing,
also depending on the fixed or variable font currently used in the rendering display
program etc.).

So if you are committed to plain text (yay for you!) I would perhaps insert a specific
number of spaces, not a tab character.
If I am sending a signed mail to an end user, whose mailserver doesn't
support S/MIME, what would happen to the message?
Location: http://www.jguru.com/faq/view.jsp?EID=1022010
Created: Nov 5, 2002
Author: Christopher Koenigsberg
(http://www.jguru.com/guru/viewbio.jsp?EID=722897) Question originally posed by
shital mhatre (http://www.jguru.com/guru/viewbio.jsp?EID=965620

Servers traditionally aren't supposed to look inside the content of a message (well
nowadays they do often filter for viruses).

The S/MIME stuff only is in the headers and body of the message, not in the
envelope. It's for use by the client MUA run by the recipient user, not by their server.
So unless a filtering server thinks it's a virus or something, it should just get
delivered to the recipient's mailbox, just like any other message.

Why do I get a NullPointer exception when I create an InternetAddress?


Location: http://www.jguru.com/faq/view.jsp?EID=1023591
Created: Nov 9, 2002
Author: Michael Dean (http://www.jguru.com/guru/viewbio.jsp?EID=805382)
Question originally posed by Luiz Augusto Dzis
(http://www.jguru.com/guru/viewbio.jsp?EID=945999

The InternetAddress(String) constructor method will throw a


NullPointerException if the String reference passed to it is null.

So, you might ask, why doesn't the documentation list that exception? Well,
according to javadoc documentation standards, runtime exceptions (like
NullPointerException) should never be listed in the "Throws" section of the
javadoc. (Sun did this right. :) Instead, in a case like this--where the runtime
exception could occur as a result of a bad parameter value---the documentation
(method documentation or "Parameters" section) should specifically mention the
possibility. (Sun forgot to do this.)

How can you tell that you'll get a NullPointerException instead of an


AddressException? Run this program:

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;

public class Test {


public static void main(String[] args) {
try {
String test = null;
InternetAddress address = new InternetAddress(test);
System.out.println(address);
} catch (MessagingException e) {
System.err.println(e);
e.printStackTrace();
}
}
}
Why do I keep getting a NULL when looking at the TO/FROM header fields?
Location: http://www.jguru.com/faq/view.jsp?EID=1029946
Created: Nov 25, 2002
Author: Christopher Koenigsberg
(http://www.jguru.com/guru/viewbio.jsp?EID=722897) Question originally posed by
bannu naidu (http://www.jguru.com/guru/viewbio.jsp?EID=1026391

Messages are not required to have anything in any of the headers. In particular, it is
OK to have no valid "From:" header (and OK to have no valid "To:" header also).
Only the SMTP envelope fields are actually used, to transmit and deliver the
message; the headers are not required.

How could I include electronic signature and encryption in a JavaMail


message?
Location: http://www.jguru.com/faq/view.jsp?EID=1032292
Created: Nov 29, 2002
Author: Lasse Koskela (http://www.jguru.com/guru/viewbio.jsp?EID=573277)
Question originally posed by Patrick Wong
(http://www.jguru.com/guru/viewbio.jsp?EID=1018115

You can find an example of this at


http://security.dstc.edu.au/projects/java/tutorials/messaging.html
Comments and alternative answers

Link for this article does not appear to be working.


Author: Christopher Lupton (http://www.jguru.com/guru/viewbio.jsp?EID=877975),
Sep 11, 2003
This link does not seem to be in operation anymore. Is there another link or mirror to
that article by any chance ? (Excellent FAQ by the way)

Re: Link for this article does not appear to be working.


Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Sep 11,
2003
Changing the original URL down to the java bit acts as a redirect to
http://www.wedgetail.com/jcsi/.

How do you send an SMS message using the JavaMail API?


Location: http://www.jguru.com/faq/view.jsp?EID=1032299
Created: Nov 29, 2002
Author: Lasse Koskela (http://www.jguru.com/guru/viewbio.jsp?EID=573277)
Question originally posed by mahadev hoolikeri
(http://www.jguru.com/guru/viewbio.jsp?EID=1006902

First of all, you need an SMS gateway for sending SMS messages (unless you plan to
code one yourself...)

Take a look at, for example, www.kannel.org for an open source SMS gateway.
The way you actually send messages via a gateway is largely dependent on the
gateway software's APIs. Some permit just using standard SMTP commands to send
(and thus permit just using the regular JavaMail API).

Comments and alternative answers

The Java solution would be to use SDK from www.simplwire.com


Author: Shaji Kalidasan (http://www.jguru.com/guru/viewbio.jsp?EID=1015374),
Dec 2, 2002
You can use the Java SDK from www.simplewire.com ( remember it is not a freeware
but there is limited trial period and is very easy to implement ). There are lots of demo
source code available.

Alternatively you can try sending email ( now more GSM service providers accept
SMTP email which can be send as SMS to mobile phones )

This is the SMS API I have worked. Consider other providers also.

Thanks & regards,


Shaji Kalidasan,
shajiindia@yahoo.com

SMS from Java


Author: Maxim Khukhro (http://www.jguru.com/guru/viewbio.jsp?EID=1076363),
Apr 14, 2003
Hi!

Take a look at
SMLib tool - sending SMS via Java.
http://www.unipro.ru/mobiles/smlib.html
This can help you

How do I send multiple messages using the same SMTP connection? When I
use Transport.send(message), this always opens a new connection.
Location: http://www.jguru.com/faq/view.jsp?EID=1035380
Created: Dec 8, 2002
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Gregory Ledenev
(http://www.jguru.com/guru/viewbio.jsp?EID=1034651

The send method is static and doesn't care if you have connected or not. Use
sendMessage.

How do I deal with uuencoded attachments?


Location: http://www.jguru.com/faq/view.jsp?EID=1041227
Created: Dec 26, 2002
Author: Christopher Koenigsberg
(http://www.jguru.com/guru/viewbio.jsp?EID=722897) Question originally posed by
Rohan Desai (http://www.jguru.com/guru/viewbio.jsp?EID=1033718

First, uuencode/uudecode is not reliable (several characters vary in different


implementations, and it is easy to damage, or incorrectly calculate/incompletely
insert, the encoding). That's why MIME's base64 was invented.

Second, uuencoded content is simply pasted in the main message body and is not a
"multipart" message (has no MIME structure) and hence does not contain
"attachments" (multiple body parts), from the MIME point of view.

As far as actually doing the uuencode/decode operations... see the encode and
decode methods of the MimeUtility class of the javax.mail.internet package.

Comments and alternative answers

How to decode uuencoded attachments


Author: Robert White (http://www.jguru.com/guru/viewbio.jsp?EID=1041462), Dec
27, 2002
Here's a utility class.
class UUEncodedBodyPart
{
private InputStream _inStreamBodyPart = null;
private String _sBodyPart = null;
private String _sPossibleFileName = null;
private int _headerIndex = -1, _endIndex = -1;

public UUEncodedBodyPart( String bodyPart ) throws Exception


{
this._sBodyPart = bodyPart;
if ( ! findUUEncodedAttachmentPosition() )
{
throw new Exception( "UUEncodedBodyPart.ctor():BodyPart does
not seem to be uuEncoded" );
}
else
{
ByteArrayInputStream bStream =
new ByteArrayInputStream( bodyPart.substring( _headerIndex,
_endIndex + 3 ).getBytes() );
try
{
_inStreamBodyPart = MimeUtility.decode( bStream,
"uuencode" );
}
catch ( MessagingException e )
{
// This just to show what kind of exception can occur
throw e;
}
}
}
private boolean findUUEncodedAttachmentPosition()
{
int beginIndex = -1;
String sSearch = _sBodyPart;
if ( ( beginIndex = sSearch.lastIndexOf( BEGIN ) ) != -1 )
{
int eolIndex = sSearch.indexOf( LINE_SEPARATOR, beginIndex );
String possibleHeader = sSearch.substring( beginIndex, eolIndex
);
StringTokenizer st = new StringTokenizer( possibleHeader );
String possibleFileSize;
st.nextToken();// this should be the begin

try
{
possibleFileSize = st.nextToken();
int fileSize = Integer.parseInt( possibleFileSize );
_sPossibleFileName = st.nextToken();

// now we know we have a UUencode header.


_headerIndex = beginIndex;
_endIndex = sSearch.indexOf( END, beginIndex );
return true;
}
catch ( NoSuchElementException nsee )
{
// there are no more tokens in this tokenizer's string
}
catch ( NumberFormatException nfe )
{
// possibleFileSize was non-numeric
}
}
return false;
}

/**
* Gets the fileName attribute of the UUEncodedBodyPart object
*
* @return The fileName value
*/
public String getFileName()
{
return ( _sPossibleFileName );
}

/**
* Gets the inputStream attribute of the UUEncodedBodyPart object
*
* @return The inputStream value
*/
public InputStream getInputStream()
{
return ( _inStreamBodyPart );
}
}

Now, to use the utility class... ... First, we have to recognize whether the JavaMail
Part we are dealing with has String content (which means it may be UUencoded). If it
is, we'll call a method to attempt to decode the attachment and save it as a file. If it
cannot be decoded, it might just be a plain old text Part, such as the body of a text e-
mail. And, of course, if it's not String content that's a whole other ball o' wax.
private Message classifyPart( Part part )
throws MessagingException, IOException
{
Object oContent = part.getContent();
if ( oContent instanceof String )
{
String sPart = (String)oContent;
// check for uuencoded files...
if ( detachUUencodedFile( sPart ) )
{
// file was written!
}
else
{
// error decoding Part or it's not uuencoded
}
}
else if ( oContent instanceof Multipart )
{
// snip...
}
else if ( oContent instanceof Message )
{
// snip...
}
else
{
// unknown Part content
}
}

Here's the part that writes the attachment as a file.


private boolean detachUUencodedFile( String sPart )
throws IOException
{
try
{
// c'tor throws exception if string is not uuencoded,
// or if there is a problem decoding the string.
UUEncodedBodyPart bp = new UUEncodedBodyPart( sPart );
File file = new File( bp.getFileName() );
save( file, bp.getInputStream() );
return true;
}
catch ( IOException exIO )
{
dbgOut( "detachUUencodedFile: " + exIO.getMessage() );
throw exIO;
}
catch ( Exception ex )
{
dbgOut( "detachUUencodedFile: " + ex.getMessage() );
}
return false;
}

static public long save( File file, InputStream is ) throws


IOException
{
if ( ! file.createNewFile() )
{
file.delete();
if ( file.exists() )
{
throw new IOException( "file exists and cannot be deleted: '"
+ file.getAbsolutePath() + "'");
}
}
BufferedOutputStream bos = null;
long lFileSize = 0;
StringBuffer sb = new StringBuffer();
try
{
bos = new BufferedOutputStream( new FileOutputStream( file ) );
int iChar;
while ( ( iChar = is.read() ) != -1 )
{
sb.append((char)iChar);
bos.write( iChar );
lFileSize++;
System.out.println( sb.toString() );
}
}
catch ( IOException exIO )
{
// explicitly close our output stream before deleting partial
file
if ( null != bos )
{
bos.flush();
bos.close();
bos = null;
}
// don't leave behind any partial files
if ( file.exists() ) file.delete();

// throw the exception again


throw exIO;
}
finally
{
// explicitly close our output stream
if ( null != bos )
{
bos.flush();
bos.close();
}
}
return lFileSize;
}

Re: How to decode uuencoded attachments


Author: ratheesh nair (http://www.jguru.com/guru/viewbio.jsp?EID=1056362), Feb
12, 2003
Please tell me what is this BEGIN, END etc,.,

Re: How to decode uuencoded attachments


Author: Dor Perl (http://www.jguru.com/guru/viewbio.jsp?EID=1060216), Feb
25, 2003
This is a nice code. However, it is dangerous to use it in a production server. The
UUEncodedBodyPart constructor accepts a String and therefore an
OutOfMemoryException might occur when the UUEncoded attachment is very
big as this code requires keeping all of it in the memory. Maybe one attachment
can not exceed an avarage amount of memory that a nowadays server has, but
think about what might happen when several Threads in the same server handles
some big UUEncoded attachments at the same time.

BEGIN END LINE..


Author: beyler olivier (http://www.jguru.com/guru/viewbio.jsp?EID=1230141), Mar
1, 2005
What is the associated string to this constante ? Best regards

How do I send email to a POP server?


Location: http://www.jguru.com/faq/view.jsp?EID=1041233
Created: Dec 26, 2002
Author: Christopher Koenigsberg
(http://www.jguru.com/guru/viewbio.jsp?EID=722897)

You don't send email to a POP server. You send email to an address which is handled
by an SMTP server. Then there may be a POP server which clients can use, to read
the mail, after it is accepted and delivered locally, by the associated SMTP server.

How can I tell the JavaMail API where to create a mail folder on my IMAP
server?
Location: http://www.jguru.com/faq/view.jsp?EID=1041237
Created: Dec 26, 2002
Author: Christopher Koenigsberg
(http://www.jguru.com/guru/viewbio.jsp?EID=722897) Question originally posed by
Narayan Joshi (http://www.jguru.com/guru/viewbio.jsp?EID=965315
The JavaMail API, for an IMAP server, sends the IMAP command, to create a new
folder, to the IMAP server. JavaMail does not create anything; the IMAP server
creates the folder, when requested to by the JavaMail API's IMAP client commands.

And then it's up to the IMAP server, where it wants to create this new folder, given its
own configuration, in the underlying local filesystem, for folder locations relative to
users' home directories (e.g. "/path/to/user1/path/to/folder1").

The IMAP server has to be able to FIND a folder, so it can't just create a folder
anywhere; it has to create the folder in the place it knows to look for them, for a
particular user. Either this is a single fixed location (e.g. "/home/user1/folder1") or it
might have a folder search path taking multiple alternative possibilities, and this
depends on the IMAP server. This has nothing to do with the JavaMail API.

When does folder.getMessages() get the messages?


Location: http://www.jguru.com/faq/view.jsp?EID=1041241
Created: Dec 26, 2002
Author: Christopher Koenigsberg
(http://www.jguru.com/guru/viewbio.jsp?EID=722897) Question originally posed by
chirag patel (http://www.jguru.com/guru/viewbio.jsp?EID=1006915

The JavaDoc for folder.getMessages says:

....Folder implementations are expected to provide light-weight Message objects,


which get filled on demand. .....

And in the JavaDoc for Message it says:

A Message object obtained from a folder is just a lightweight reference to the actual
message. The Message is 'lazily' filled up (on demand) when each item is requested
from the message. Note that certain folder implementations may return Message
objects that are pre-filled with certain user-specified items.

I'm getting my Session with Session.getDefaultInstance and its not getting


changes to the Properties passed in. What's wrong?
Location: http://www.jguru.com/faq/view.jsp?EID=1046816
Created: Jan 15, 2003 Modified: 2003-03-29 22:39:43.174
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

In getDefaultInstance(Properties props), the Properties are only used in the initial


call. Future calls ignore the setting, returning the previously created Session. If you
need to change the Properties, like to change SMTP servers, you should use
getInstance(Properties props) instead.

How are connection timeouts implemented?


Location: http://www.jguru.com/faq/view.jsp?EID=1052347
Created: Jan 31, 2003
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

According to Bill Shannon, primary JavaMail engineer: The timeout is implemented


by starting a thread to make the connection and if it doesn't complete before the
timeout, the thread is abandoned and left to die. (Unfortunately, there's no way to
actually abort the connection attempt.)

How can I log the debug messages to a file when I session.setDebug(true)?


Location: http://www.jguru.com/faq/view.jsp?EID=1052582
Created: Jan 31, 2003
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

With the 1.3 release of JavaMail, there is support for session-level output streams.
Call public void setDebugOut(java.io.PrintStream out) to change
the stream from System.out. Passing in a value of null will use System.out for
output.

How do I send a message where a character with an accent is in the


subject?
Location: http://www.jguru.com/faq/view.jsp?EID=1052586
Created: Jan 31, 2003
Author: Christopher Koenigsberg
(http://www.jguru.com/guru/viewbio.jsp?EID=722897) Question originally posed by
Alfonso Garzon (http://www.jguru.com/guru/viewbio.jsp?EID=1045052

Email headers can only contain 7-bit US ASCII characters, according to the Internet
standards (mainly RFC 2822, also 2821). For any characters outside that charset,
they have to be encoded first. Your (sender's) email client should display the proper
characters (accented etc.) to you when you are composing the message, but needs
to encode them for transmission. The recipient's email client needs to decode them,
for display at the other end.

See RFC 2047 for details about encoding characters in email headers.

Here are some classic examples, from RFC 2047, of some encoded text in email
headers:

From: =?ISO-8859-1?Q?Olle_J=E4rnefors?= <ojarnef@admin.kth.se>

From: Nathaniel Borenstein <nsb@thumper.bellcore.com> (=?iso-8859-


8?b?7eXs+SDv4SDp7Oj08A==?=)

The first example is of some iso-8859-1 characters, encoded using the "Q" encoding
(same as "quoted-printable" content-transfer-encoding for body parts). The second
example is some iso-8859-8 characters, using the "B" encoding (same as "base64"
content-transfer-encoding for body parts).

Unlike body parts which need a separate header to tell how they are encoded, in the
headers like these, as you see, the start of the escape sequence tells what encoding
scheme is used, and what character set has been encoded in it.

JavaMail 1.3 supports group addresses. What are group addresses?


Location: http://www.jguru.com/faq/view.jsp?EID=1052592
Created: Jan 31, 2003
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)
RFC 822 defines what a group address is. It allows one to prefix a list of email
addresses with a label, followed by a colon, as in:
jGurus: a@example.com, John <b@example.com>, "Joe" <c@example.com>

How can I optimize sendmail for use with JavaMail-based programs?


Location: http://www.jguru.com/faq/view.jsp?EID=1053565
Created: Feb 4, 2003
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

According to Joseph Shraibman on the JAVAMAIL-INTEREST mailing list:

JavaMail checks if the connection is good by sending a NOOP command. It does this
before sending each mail message. The problem is that after 19 NOOPs sendmail
starts slowing down. To fix this (if you control the mail server) is to set
MAXNOOPCOMMANDS to 0 in sendmail/srvrsmtp.c and recompile sendmail. If you
don't control the server you have to count how many messages you send and
reconnect after 19 of them.

Where can I get a custom JavaMail javax.mail.Store to access an RSS feed?


Location: http://www.jguru.com/faq/view.jsp?EID=1059429
Created: Feb 22, 2003
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The open source app ZOE offers one.

How can I configure sendmail to route messages through James for


filtering/scanning?
Location: http://www.jguru.com/faq/view.jsp?EID=1060659
Created: Feb 25, 2003
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

See the help document at http://james.apache.org/james_and_sendmail.html.

How can I contribute to the James project?


Location: http://www.jguru.com/faq/view.jsp?EID=1060660
Created: Feb 25, 2003
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Contribution information is available from http://james.apache.org/contribute.html.

How much does James cost?


Location: http://www.jguru.com/faq/view.jsp?EID=1060661
Created: Feb 25, 2003
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

James can be freely used and is released under the Apache Software License.
http://james.apache.org/license.html.

Can JavaMail be used from a Message Driven Bean? The EJB specifictation
requires that the bean implementation must be single-threaded. Isn't
JavaMail multi-threaded? If so, can it be used from a Message Driver Bean?
Location: http://www.jguru.com/faq/view.jsp?EID=1063436
Created: Mar 5, 2003
Author: Jens Dibbern (http://www.jguru.com/guru/viewbio.jsp?EID=9896) Question
originally posed by Shiv Kumar
(http://www.jguru.com/guru/viewbio.jsp?EID=844764

You should configure a JavaMail resource for your EJB container and access it by
JNDI. It works just like JavaMail in an application without setting up the connection
first. You just get it from the JNDI tree. This should work for your MDB just like it
workes for my stateless session bean
Comments and alternative answers

JavaMail and Message Driven Bean


Author: Ram V.L.T (http://www.jguru.com/guru/viewbio.jsp?EID=449849), Dec 17,
2004
Click Here for a good example of Working with the new Message Driven Beans
and JMS

Why do binary file attachment sizes increase by about 15-20% when


sending a message?
Location: http://www.jguru.com/faq/view.jsp?EID=1071376
Created: Mar 29, 2003
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

When included as an attachment, binary files are encoded to be 7-bit safe. This
means that what used to be 8-bits per byte is now 7, hence the increase.

Can I create a MimeMessage using one Session say session1 and send the
mail using another Session session2?
Location: http://www.jguru.com/faq/view.jsp?EID=1071379
Created: Mar 29, 2003
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by manjunath somashekar
(http://www.jguru.com/guru/viewbio.jsp?EID=1063490

Sure.
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class MailExample {


public static void main (String args[]) throws Exception {
String host = args[0];
String from = args[1];
String to = args[2];
String username = args[3];
String password = args[4];

// Get system properties


Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", host);

// Get session
Session session = Session.getInstance(props, null);

// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("Hello JavaMail");
message.setText("Welcome to JavaMail");

Session session2 = Session.getInstance(props, null);

// Send message
Transport transport = session2.getTransport("smtp");
transport.connect(host, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
}

How do I display POP3 message body properly in a browser?

When i use message.writeTO() it displays without line breaks.


Location: http://www.jguru.com/faq/view.jsp?EID=1071381
Created: Mar 29, 2003
Author: Christopher Koenigsberg
(http://www.jguru.com/guru/viewbio.jsp?EID=722897) Question originally posed by
srinivas Rao (http://www.jguru.com/guru/viewbio.jsp?EID=1062741

Of course an HTML browser is rendering HTML, meaning that it is ignoring


whitespace, including newlines.

You could try enclosing your text in a "<pre>" element. Or you could insert the HTML
for linebreaks yourself ("<br>" or else enclose in "<p>" elements).

Comments and alternative answers

How do I display POP3 message body properly in a browser? When i use


message.writeTO() it displays without line breaks.
Author: Md Razzak Sorker (http://www.jguru.com/guru/viewbio.jsp?EID=1115939),
Sep 17, 2003
First you have to check the message mimeType is text/html or not if so then you have
to read the inputsteam then make a bufferedreader and read the content line by line
and print it, the code should look somthing like this: <% if
(msg.isMimeType("text/html")) { BufferedReader reader = new BufferedReader(new
InputStreamReader(msg.getInputStream()));
while((msgText=reader.readLine())!=null) { %> <%= msgText %> <% } } %>
Formatting a brwser friendly message
Author: James Fuhr (http://www.jguru.com/guru/viewbio.jsp?EID=1140414), Jan 21,
2004
The standard linebreak in an email appears as \r\n. If you are using an IDE such as
NetBeans, set a Watch on the variable storing the line and run in debug. You should
see those escape characters. What I ended up doing, was manually insert the line
break HTML tag while reading each line of the message. The sample code below
checks the content type of the message. If it is text/plain, it creates the <BR> tags
InputStream is = messagePart.getInputStream();

BufferedReader reader = new BufferedReader(new


InputStreamReader(is));

String thisLine=reader.readLine();
StringBuffer msg = new StringBuffer();

while (thisLine!=null) {
msg.append(thisLine);

//check the content type; append


if plain text
if(mailMessage.contentType.startsWith("text/plain")) {
msg.append("<br>");
}
thisLine=reader.readLine();
}

Can someone please specify the technique of message sorting within folder
according to some criteria say Header Information?
Location: http://www.jguru.com/faq/view.jsp?EID=1071382
Created: Mar 29, 2003
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Wolverine X
(http://www.jguru.com/guru/viewbio.jsp?EID=1060213

Since the Message class doesn't implement the Comparable interface, you'll need to
create a custom Comparator. Then, you can call Arrays.sort(arrayOfMessages,
comparator).

Is it possible to send a message that identifies if the mailreader is


configurate to read HTML or text mail?
Location: http://www.jguru.com/faq/view.jsp?EID=1072695
Created: Apr 2, 2003 Modified: 2003-04-03 04:48:51.163
Author: Christopher Koenigsberg
(http://www.jguru.com/guru/viewbio.jsp?EID=722897) Question originally posed by
marcelo serra (http://www.jguru.com/guru/viewbio.jsp?EID=1071681

The MIME content-type "multipart/alternative" is intended so you can send different


versions of the same "message" all bundled together, e.g. an HTML version, a plain
text version, maybe an audio version, etc., and let the remote mail reading client
decide for itself, which one is appropriate for it, and for its current user.

Comments and alternative answers

On the multipart/alternative...
Author: Gabi Lacatus (http://www.jguru.com/guru/viewbio.jsp?EID=1071969), Aug
19, 2003
I noticed that the order of the parts count too.

If I put the text/plain first and then a text/html then pine for example opens the
text/plain part and Outlook opens the html part(But it also shows the text/plain part as
an attachment while other mail clients do not - WHY?)

If the text/html part is inserted first then even pine opens the html code :((...how
come?Could it be a server configuration matter?

Re: On the multipart/alternative...


Author: Neil Boemio (http://www.jguru.com/guru/viewbio.jsp?EID=1128781),
Nov 17, 2003
Did you ever figure out the issue with Outlook showing both the HTML part and
the Text part of the multipart/alternative e-mail?

Example Code
Author: Kevin Bridges (http://www.jguru.com/guru/viewbio.jsp?EID=1119238), Oct
2, 2003
// Create the message to send
Properties props = new Properties();
props.put("mail.smtp.host", "localhost");
Session session = Session.getInstance(props,null);
MimeMessage message = new MimeMessage(session);

// Create the email addresses involved


InternetAddress from = new InternetAddress("from@from.com");
InternetAddress to = new InternetAddress("to@to.com");

// Fill in header
message.setSubject("I am a multipart text/html email" );
message.setFrom(from);
message.addRecipient(Message.RecipientType.TO, to);

// Create a multi-part to combine the parts


Multipart multipart = new MimeMultipart();

// Create your text message part


BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Here is your plain text message");

// Add the text part to the multipart


multipart.addBodyPart(messageBodyPart);
// Create the html part
messageBodyPart = new MimeBodyPart();
String htmlText = "<H1>I am the html part</H1>";
messageBodyPart.setContent(htmlText, "text/html");

// Add html part to multi part


multipart.addBodyPart(messageBodyPart);

// Associate multi-part with message


message.setContent(multipart);

// Send message
Transport.send(message);

Re: Example Code


Author: sarah sarah (http://www.jguru.com/guru/viewbio.jsp?EID=1250544), Jun
27, 2005
This will work - both the html and plain text will be sent, but only the one
favoured by the recipient program will be displayed. BUT, you forgot to make it
multipart/alternative! the way it is, both types will be displayed. To make this
work as intended, it must be Multipart multipart = new
MimeMultipart("alternative"); Also, just thought I'd mention that apparently the
order is important. Add the plain text before the html version, since AOL users
always get both and the html doesn't display right (so they'd have to scroll all the
way to the bottom). I haven't tested this out myself though.

Re[2]: Example Code


Author: Java Buddha
(http://www.jguru.com/guru/viewbio.jsp?EID=1251857), Jul 5, 2005
Hi Sarah, If I add HTML version before Text version it works fine in most of
the clients Pine, Micorsoft outlook, gmail etc., I didn't check it in AOL as I
don't have an account. But then as you said, I tried adding the HTML version
after Text version and checked the mail sent with Pine software. Pine now
displays the HTML and Text both, previously it was displaying only Text
version. Kindly help me out of this. Thanks, Shenbag

What is the format of the Content-ID header?


Location: http://www.jguru.com/faq/view.jsp?EID=1075898
Created: Apr 12, 2003
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The Content-ID header, set with setContentID, needs to be formatted like <cid>. You
need to make sure the < and > signs are present. Some mail readers work without
them, many don't.

What's new in JavaMail 1.3.1?


Location: http://www.jguru.com/faq/view.jsp?EID=1079414
Created: Apr 25, 2003
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

JavaMail 1.3.1 includes over 20 bug fixes, as well as support for DIGEST-MD5
authentication in the SMTP provider (courtesy of Dean Gibson).

How do I configure JavaMail to work through my proxy server?


Location: http://www.jguru.com/faq/view.jsp?EID=1080812
Created: Apr 30, 2003
Author: Christopher Koenigsberg
(http://www.jguru.com/guru/viewbio.jsp?EID=722897) Question originally posed by
SKD SKD (http://www.jguru.com/guru/viewbio.jsp?EID=1077304

Proxy servers redirect HTTP connections, not JavaMail connections. In order to


connect from behind a firewall for POP3, IMAP, and SMTP access, you need to
connect to a SOCKS server. Your sys admin should provide you with SOCKS client
software, to install on your client machine. (Hummingbird, for instance, for Windows;
various clients for Solaris; I think Linux, at least RedHat, already comes with a
SOCKS client?) The SOCKS versions have to match, on the client and SOCKS server.

It's transparent to network applications, e.g. they just think they are making normal
connections, but the TCP stack internally tunnels these through SOCKS instead. So
the only thing to configure is the SOCKS client software on the host.

How do I get the size of a message that I am going to send? The getSize()
method works fine with received message but returns -1 if I use it with a
message that I am going to send!
Location: http://www.jguru.com/faq/view.jsp?EID=1080814
Created: Apr 30, 2003
Author: fernando fernandes (http://www.jguru.com/guru/viewbio.jsp?EID=400255)
Question originally posed by fernando fernandes
(http://www.jguru.com/guru/viewbio.jsp?EID=400255

Get the InputStream for the message with getInputStream() and count the bytes.

Where can I find a regular expression to validate an email address?


Location: http://www.jguru.com/faq/view.jsp?EID=1088553
Created: May 27, 2003
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

One is available at http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html.


Comments and alternative answers

Here is the regular Expression for Email validation


Author: praveen J (http://www.jguru.com/guru/viewbio.jsp?EID=1140476), Jan 21,
2004
public static boolean isValidEmailAddress(String email) { String regex = "^[_A-Za-
z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[_A-Za-z0-9-]+)" ;
return email.matches(regex) ; }
How do I find out if an IMAP server supports a particular capability?
Location: http://www.jguru.com/faq/view.jsp?EID=1093517
Created: Jun 12, 2003
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

If you have a folder open, you can do this:


import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.protocol.IMAPProtocol;

IMAPProtocol p = ((IMAPFolder)folder).getProtocol();
if (p.hasCapability("FOO"))
...
See the com.sun.mail.imap package javadocs for additional details and important
disclaimers.

How do I get rid of unused connections? Doing something like checking for
the existance of an IMAP folder leaves the connection open.
Location: http://www.jguru.com/faq/view.jsp?EID=1110073
Created: Aug 21, 2003
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by George Lindholm
(http://www.jguru.com/guru/viewbio.jsp?EID=1065564

You can set the connection pool timeout property (mail.imap.connectionpooltimeout


for imap). Then... according to JavaMail architect Bill Shannon:

Because JavaMail doesn't use a separate thread to manage the timeout, it only
checks for connections to timeout when you do something with the Store. Adding a
call to store.isConnected() after the timeout should trigger the timeout/disconnect.

How do I package a JavaMail application into a single jar file along with the
mail.jar and activation.jar?
Location: http://www.jguru.com/faq/view.jsp?EID=1111058
Created: Aug 26, 2003
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question
originally posed by Glenn Wiens
(http://www.jguru.com/guru/viewbio.jsp?EID=458756

You need to unjar all the JAR files into a single directory tree and then JAR them
back up. The trick is preserving the location of some files:

425 Fri Dec 01 00:05:16 EST 2000 META-


INF/javamail.default.providers
12 Fri Dec 01 00:05:16 EST 2000 META-
INF/javamail.default.address.map
1124 Fri Dec 01 00:05:16 EST 2000 META-
INF/javamail.charset.map
469 Fri Dec 01 00:05:16 EST 2000 META-INF/mailcap
Make sure these end up in the same location in the new JAR.
How do I calculate the size of an entire folder?
Location: http://www.jguru.com/faq/view.jsp?EID=1137806
Created: Jan 8, 2004
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

For POP3, you can get this information for the INBOx with
<size=2>com.sun.mail.pop3.POP3Folder.getSize()</size>.

For IMAP, the protocol doesn't support this feature. You would need to sum the sizes
of the contained messages.

How do I get the sender of an email?


Location: http://www.jguru.com/faq/view.jsp?EID=1251270
Created: Jun 30, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The getFrom() of Message is one way, but the getSender() method of MimeMessage
reads the RFC 822 Sender header field. A value of null is returned if the header isn't
present. Comparing the two allows you to see if someone is lying. :-)

How do I set the default character encoding for JavaMail to use?


Location: http://www.jguru.com/faq/view.jsp?EID=1251271
Created: Jun 30, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The mail.mime.charset system property is used. If unset, file.encoding is


used instead.

How do I find out the number of deleted messages in a folder?


Location: http://www.jguru.com/faq/view.jsp?EID=1251272
Created: Jun 30, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Added with JavaMail 1.3, the getDeletedMessageCount() method of Folder


gets this for you. A -1 may be returned if the server doesn't support the operation.

How is JavaMail licensed?


Location: http://www.jguru.com/faq/view.jsp?EID=1255606
Created: Jul 29, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

As of July 2005, JavaMail is licensed with GlassFish under Sun's CDDL open source
license.

What version of JavaMail does GlassFish contain?


Location: http://www.jguru.com/faq/view.jsp?EID=1255607
Created: Jul 29, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

According to Bill Shannon of Sun, the July 2005 release of GlassFish contains JAF
1.1ea and a version of JavaMail slightly newer than 1.3.3ea.
What is GlassFish?
Location: http://www.jguru.com/faq/view.jsp?EID=1255621
Created: Jul 29, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The GlassFish Project is Sun's open source application server project. Found at
https://glassfish.dev.java.net/, you can participate in the development of the latest
version of Sun's Java System Application Server PE 9.0. It is based on Java
Enterprise Edition 5.

What string do I pass to SimpleDateFormat to format the message date to


spec - getSentDate() method of Message?
Location: http://www.jguru.com/faq/view.jsp?EID=1259133
Created: Aug 22, 2005
Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

There is no need to create a custom DateFormat. The MailDateFormat class found in


the javax.mail.internet handles all this for you. It formats and parses the date based
on the draft-ietf-drums-msg-fmt-08 dated January 26, 2000. This is a followup spec
to RFC-822.

You might also like