All About Java Mail
All About Java Mail
Location: http://www.jguru.com/faq/JavaMail
Ownership: http://www.jguru.com/misc/user-agree.jsp#ownership.
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.
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 -
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.
The following scriptlet makes use of the SmtpClient class to send an email from
within a JSP page.
Read the LICENSE.txt file that comes with the tools for complete redistribution
information. Basically you are free to redistribute the unmodified packages.
Between the DATA line and the . (period) line is the message. The period is alone on
the line following the end of the message.
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
NOTE: Make sure you are appending a CRLF to the end of each line sent.
Instructions
------------
Below is the transmission log from a typical session. For your testing, type in all lines
that start with the word Sent:
From socket(128)--> 252 Cannot VRFY user, but will take message for smith
Sent: DATA
Sent: .
Sent: QUIT
Note:
For CRLF
CR stands for carriage return
LF stands for linefreed
Use '\r' for carriage return and '\n' for line feed.
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
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
The following program will send a mail message. It requires three command line
arguments:
• SMTP Server
• From Email Address
• To Email Address
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
// 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);
}
}
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;
smtp.closeServer();
}
}
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
import javax.mail.*;
import javax.mail.internet.*;
// Get session
Session session = Session.getInstance(
System.getProperties(), null);
// 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();
}
}
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.
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.*;
// Get session
Session session = Session.getInstance(
System.getProperties(), null);
// Get folder
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
// 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(true);
store.close();
}
}
You can also expunge() the Folder. However, the POP3 server from Sun does not
support this operation.
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.*;
// 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());
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.
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.
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.
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
// Get session
Session session = Session.getInstance(
System.getProperties(), null);
// 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();
}
}
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
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.*;
// Get session
Session session = Session.getDefaultInstance(props, null);
// 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;
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.
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.*;
// Get session
Session session = Session.getInstance(
new Properties(), null);
// 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());
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);
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!
Best regards,
/Franck
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
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 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");
//fill message
messageBodyPart.setText("Hi");
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)
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).
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.
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.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
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.
String addressString =
"[email protected]";
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","[email protected]"); 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.
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
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:
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
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:
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
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
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
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.
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.
props.put("mail.smtp.auth", "true");
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.
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.
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:
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");
If you want you can write your own search term extending one of these classes and
writing inside your own searching logic.
You have to extract directly the Content Type Header from the Message and extract it
manually (or using the ContentType class):
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
So I think the future release of JavaMail 1.2 will support this protocol.
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?
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.
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.
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
First of all, you have to create a javax.mail.Session like you would in accessing other
resources such as JDBC connections:
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 :
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
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 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.
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.*;
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);
}
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);
mp.setSubType("related");
mbp1.setContent(html,"text/html");
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 [email protected] .
* 111.222.1.21 is the SMTP Server
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.*;
// 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);
}
}
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
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);
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.
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.
import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
// Get session
Session session = Session.getInstance(
props, null);
// Get folder
Folder folder = store.getFolder(newsgroup);
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());
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();
}
}
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!
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:
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
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);
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.
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.
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. [email protected]
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!
;)
d:\weblogic\bin\wlconfig.exe -classpath
d:\weblogic\classes\mail.jar;d:\weblogic\classes\activation.jar
The following URL contains a long list of mail servers(with descriptions and links)
from http://www.davecentral.com/mailserv.html.
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:
out.print(
"From: [email protected]"+"\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();
}
}
}
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.
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.
// 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);
}
}
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
Thoughts as to why?
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.
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");
// Fill in header
message.setSubject("I am a multipart text/html email" );
message.setFrom(from);
message.addRecipient(Message.RecipientType.TO, to);
// Send message
Transport.send(message);
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.
to read:
This then worked as expected with only one of the body parts being displayed
on the client.
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>>
The JavaMail API documentation is available from Sun's J2EE API documentation
page.
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
if (msg.isSet(Flags.Flag.DELETED)) {
}
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.
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.
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.
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
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.
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 [email protected], 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.*;
// 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";
// 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
Regards Mukund
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.
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/.
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 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.
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.
1. Solution Start your program from a console with: java myProgramm >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.
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.
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.
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.
An html handler is provided in JavaMail 1.1.3 but the mailcap file is not configured to
use it.
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.
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;
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.
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.
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:
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:
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
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
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.
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");
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;[email protected]");
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. [email protected] 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",
"[email protected]");
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.
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:
bodyPart.setText( body );
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
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.
message.addHeader("X-FAQs",
"http://www.jguru.com/faq");
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);
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:[email protected]?subject=My%20Subject&body=The%20body%20of%20m
y%20message.
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();
[...]
}//hasToBeRemoved
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++)
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]);
}
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.
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.
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.
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
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.
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
<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.
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:
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)
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.
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:
The Internet Mail Consortium maintains a page which lists and tracks all of the IETF
Requests for Comments (RFCs) related to internet mail standards.
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/.
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.
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.
Free:
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
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:
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.
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.
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
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.
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
// 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...
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
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.
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.
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.
You may want to use similar technique as ezmlm-weed for differenciating real
bounces from delay notifications, replies from vacation autoresponders and another
junk.
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
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
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
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. "
props.put("mail.smtp.sendpartial",true)
You can also catch SendFailedException, and re-send to the addresses returned by
sfe.getValidUnsentAddresses() .
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.
from: [email protected]
to: [email protected]
subject: uuencodetest
Hello,
this is a
uu-decode test!
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.
<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.
// 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
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.
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
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.
props.setProperty("mail.imap.socketFactory.class",
"MySocketFactory");
javax.mail.URLName("imap://imap.myserver.net/");
Thanks
-srini
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
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
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());
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.
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
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.
<html>
<head>
<script language=javascript>
function send() {
var lstr_data = "FIRST LINE" + "\n" +
"SECOND LINE" + "\n" + "THIRD LINE";
window.location.href="mailto:[email protected]" +
"?body=" + escape (lstr_data);
}
</script>
</head>
<body>
Instead, you can get the message from a TextArea on the page...
<html>
<head>
<script language=javascript>
function send() {
window.location.href="mailto:[email protected]" +
"?body=" + document.frm_test.ta_body.value;
}
</script>
</head>
<body>
Mail Contents:
window.location.href="mailto:[email protected]" +
"?subject=" + "TEST MAIL";
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
:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"folders" is public folders of exchange server... That`s all !!! Good luck and Have
a nice day!!!
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.
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.
See RFC...
Best regards,
/Franck
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
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());
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());
"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
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.
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.
import javax.mail.*;
import javax.mail.internet.*;
// 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.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.*;
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
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.
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.*;
// Get session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(true);
// 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
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();
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.
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
alternative?
Author: lecanard masque (http://www.jguru.com/guru/viewbio.jsp?EID=522072), Oct
17, 2001
what about : msg.setText(text,"UTF-8"); ?
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.
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
Use different session objects (don't use the default). Get the session with
Session.getInstance() instead of getDefaultInstance().
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.
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.
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.
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 {
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.
http://www.jguru.com/forums/view.jsp?EID=528015
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>
<message-rfc822>
body of the embedded mail as INLINE content.
</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.
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);
...
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)
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)
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
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
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 {
/**
* 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;
byte[] bytearray;
BLOB blob = ((OracleResultSet) rs).getBLOB("IMAGE_GIF");
if (blob != null) {
}
bao.close();
bis.close();
bytearray = bao.toByteArray();
• ISNetworks
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
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
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
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.
This assumes the SMTP server is setup not to fail multiple recipient mail if any
address is invalid.
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.
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
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) {
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:
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.
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?
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.
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
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().
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();
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);
}
}
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:[email protected]?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)
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 <[email protected]>
From: "You" <[email protected]>
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.*;
// 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).
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.*;
props.put("mail.smtp.host", host);
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.
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.
The NewsAddress class in the javax.mail.internet package can do this for you:
public static NewsAddress[] parse(String newsgroups)
throws AddressException
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.
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.
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
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.*;
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.
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)
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)
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.
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.
While you could call getFrom() directly, the better thing to do is call the getReplyTo()
method of Message.
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.
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.
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 :
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)
Some SMTP servers require that the FROM user be registered with the domain.
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.*;
// Get session
Session session = Session.getDefaultInstance(props, null);
// 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.
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.
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.
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.*;
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.
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
The Classes for Notes require pretty much custom coding to get the same
result, but are far more flexible.
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
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
Not directly, though there is nothing to stop you from extending the library to
support it.
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.
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.
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.
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);
[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
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.
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.)
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
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.
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).
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.
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.
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.
try
{
possibleFileSize = st.nextToken();
int fileSize = Integer.parseInt( possibleFileSize );
_sPossibleFileName = st.nextToken();
/**
* 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
}
}
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.
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.
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.
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:
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 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.
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
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.*;
// 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 transport = session2.getTransport("smtp");
transport.connect(host, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
}
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).
String thisLine=reader.readLine();
StringBuffer msg = new StringBuffer();
while (thisLine!=null) {
msg.append(thisLine);
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).
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?
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);
// Fill in header
message.setSubject("I am a multipart text/html email" );
message.setFrom(from);
message.addRecipient(Message.RecipientType.TO, to);
// Send message
Transport.send(message);
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.
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).
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.
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
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:
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.
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. :-)
As of July 2005, JavaMail is licensed with GlassFish under Sun's CDDL open source
license.
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.