Exception in java mail API when parsing email
I am receiving the following exception when receiving some emails that contain attachments with java mail (irrelevant part of stack trace omitted):
javax.mail.internet.ParseException: Expected ';', got ","
at javax.mail.internet.ParameterList.<init>(ParameterList.java:289)
at javax.mail.internet.ContentDisposition.<init>(ContentDisposition.java:100)
at javax.mail.internet.MimeBodyPart.getFileName(MimeBodyPart.java:1136)
The header of a message the causes the problem is:
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) ------------ Message headers ------------
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Received: from mail2.uscourts.gov ([10.170.250.2])
by ushub06.uscmail.dcn (Lotus Domino Release 8.5.2FP1 HF3)
with SMTP id 2011042514392620-733724 ;
Mon, 25 Apr 2011 14:39:26 -0400
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Received: from (unknown [63.174.91.123]) by avms-usc-04c-02vh.ibmta.uscourts.gov with smtp
id 191c_067d_57fad3b8_6f6b_11e0_8de9_00265519f638;
Mon, 25 Apr 2011 18:39:24 +0000
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) X-WSS-ID: 0LK815L-05-67D-02
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) X-M-MSG:
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Received: from kcmexclaim.Our-Firm.com (unknown [10.42.5.222])by mail4.stinson.com (Axway MailGate 3.8.1) with ESMTP id 27239A12C1D; Mon, 25 Apr 2011 13:39:20 -0500 (CDT)
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Received: from KCME2K7-HUB02.Our-Firm.com ([10.42.5.19]) by kcmexclaim.Our-Firm.com with Microsoft SMTPSVC(6.0.3790.4675); Mon, 25 Apr 2011 13:39:23 -0500
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Received: from FIRMCMS01.Our-Firm.com ([fe80::81d0:dd2b:9983:1126]) by KCME2K7-HUB02.Our-Firm.com ([::1]) with mapi; Mon, 25 Apr 2011 13:39:22 -0500
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) From:
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) To:
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Cc:
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Disposition-Notification-To:
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Date: Mon, 25 Apr 2011 13:39:21 -0500
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Subject: Order Regarding Application To Employ SMH as Debtor's Counsel
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Thread-Topic: Order Regarding Application To Employ SMH as Debtor's Counsel
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Thread-Index: AcwDb/bpRQlxt/eTQC6BA7G10hdWJQAB99vQ
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Message-ID: <[email protected]>
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Accept-Language: en-US
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) X-MS-Has-Attach: yes
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) X-MS-TNEF-Correlator:
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) acceptlanguage: en-US
2011-04-25 14:39:48,060 INFO [STDOUT] (WorkManager(2)-97) Importance: Normal
2011-04-25 14:39:48,061 INFO [STDOUT] (WorkManager(2)-97) Priority: normal
2011-04-25 14:39:48,061 INFO [STDOUT] (WorkManager(2)-97) X-MimeOLE: Produced By Microsoft MimeOLE V6.00.3790.4841
2011-04-25 14:39:48,061 INFO [STDOUT] (WorkManager(2)-97) MIME-Version: 1.0
2011-04-25 14:39:48,061 INFO [STDOUT] (WorkManager(2)-97) Return-Path:
2011-04-25 14:39:48,061 INFO [STDOUT] (WorkManager(2)-97) X-OriginalArrivalTime: 25 Apr 2011 18:39:23.0526 (UTC) FILETIME=[18E10260:01CC0378]
2011-04-25 14:39:48,061 INFO [STDOUT] (WorkManager(2)-97) X-MIMETrack: Itemize by SMTP Server on USHUB06/H/US/USCOURTS(Release 8.5.2FP1 HF3|December 21, 2010) at 04/25/2011 02:39:26 PM, Serialize by POP3 Server(Release 8.0.2FP3 HF28|December 28, 2009) at 04/25/2011 02:39:47 PM
2011-04-25 14:39:48,061 INFO [STDOUT] (WorkManager(2)-97) Content-Transfer-Encoding: 7bit
2011-04-25 14:39:48,061 INFO [STDOUT] (WorkManager(2)-97) Content-Class: urn:content-classes:message 2011-04-25 14:39:48,061 INFO [STDOUT] (WorkManager(2)-97) Content-Type: multipart/mixed; boundary="_004_52835C1F7A6C8D4F989C433DCC611CA06F252D6682FIRMCMS01OurF_"
2011-04-25 14:39:48,061 INFO [STDOUT] (WorkManager(2)-97) Content-Language: en-US
the client/OS combination of the mail sender is Windows XP service Pack 3/Outlook 2007 , Java Mail version 1.4.3
Any help would be appreciated
Edited by: 854778 on Apr 26, 2011 8:28 AM
The exception is occurring when parsing the Content-Disposition header.
I don't see that header in the list of headers you provided.
Can you save the entire message to a text file using
msg.writeTo(new FileOutputStream("msg.txt"));
Then look for the Content-Disposition header in msg.txt. Most likely you'll
find that it is incorrectly formatted - as the exception says, there's a comma
in a place that a semicolon is expected.
Similar Messages
-
String "iso-8859-1" found in subject line of java mail API(when German char
We have written a mail client using java mail API and it works fine. Some body sends the email with subject line contains German chars(using some other mail client like outlook)
and our mail client is running on the machine whose Local has been set 'German'.
Now, while getting the subject line
Javax.mail.Message email; //local variable
// some how I am intializing email.
String str = email.getSubject();
the value of str returns "Bitte die 4 Items I�schen. Kein Bedarf. Ich kann die=?iso-8859-1?Q?_L=F6schung_nic?="
but actual value subject line was "Bitte die 4 Items I�schen. Kein Bedarf. Ich kann die L�schung nic"
So '�' char was repalced by some arbit chars.
Moreover, Charset.defaultCharset().name() returns 'windows-1252'
Please suggest me how I can get the actual subject line
Thanks
-Sanjeevhttp://forum.java.sun.com/thread.jspa?threadID=741111&messageID=4250621
visit it
by ghanshyam -
Message Exception and Internet Address exception in Java mail API
Hi,
Using JAVA mail api while using sendmessage method i am getting Invalid address exception..TO address and from address are same as my mail id..Someone please tell why these exceptions come.
Thanks..To prevent spammers using your system's mail transfer agent as a channel for spam most MTAs are set up to send message either from a recognised local address to a remote address, or from remote to local. "Unable to relay" generally means that your MTA doesn't recognise the machine that tried to send the e-mail as "local".
You probably need to make changes to the configuration of the MTA (Sendmail or whatever) that runs on the machine you've designated as mail host. -
Error while sending mail when using Java Mail API
Hi Experts,
I am trying to execute a webdynpro application which uses the Java Mail API to send emails. The exception that I get on executing the application is :
Sending failed; nested exception is: javax.mail.SendFailedException: Invalid Addresses; nested exception is: javax.mail.SendFailedException: 550 5.7.1 Unable to relay for [email protected]
Can anybody please help me sort out the issue.
Regards
AbdullahHi,
Usually one get this error if the SMTP server is configured not to relay mails (a security measure) or the SMTP server need the mail to be sent from a trusted IP or with proper authentication. Some SMTP servers are configured to block junk mails.
Pls check with your mail server administrator.
Regards -
Java mail api: SendFailedException when trying to send Mail via SMTP
Hello,
I'm trying to send a mail via java mail api using a server that requires smtp authentication.
I'm currently using the following code:
protocol = "smtp";
host = "auth.smtp.profimailer.de";
port = 25;
String from="[email protected]";
String to="[email protected]";
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Authenticator auth = new PopupAuthenticator();
session=Session.getInstance(props,auth);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from,"[email protected]"));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to,"ToName"));
message.setSubject("Hello JavaMail");
message.setText("Welcome to JavaMail");
Transport.send(message);
static class PopupAuthenticator extends Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("e12345676", "mypass");
}When trying to run this code, I get the following exception:
D:\eclipse30RC1\workspace\ClassifyIt\bin>java -cp .;../lib/javamail.jar de.jwannenmacher.classify.TestMail > test.txt
javax.mail.SendFailedException: Send failed;
nested exception is:
javax.mail.SendFailedException: Sender "[email protected]" <jens
@jens-wannenmacher.de> was rejected: 501
at javax.mail.Transport.doSend(Transport.java:223)
at javax.mail.Transport.send(Transport.java:92)
at de.jwannenmacher.mail.pop3client.POP3Client.getAllNewMessages(POP3Cli
ent.java:176)
at de.jwannenmacher.classify.TestMail.main(TestMail.java:22)
Any suggestions on this?
Thanks and best regards,
JensHi,
yes smtp is a standard and I think you could use this with almost every smtp server.
If your smtp server doesn't require authentication you can access it without an authenticator
I think...
Best regards,
Jens -
Problem in retrieving email using java mail api
hi,
In my project,i am retrieving mails from a particular email id.
I am able to retrieve the latest mails and save it in a folder in my system.
The problem is whenever i run the program eventhough the most recently received mail in inbox is retrieved and saved,again it is retrieving the same one and saving it in the same folder(not repeating).
I tried to check the newmessages in the inbox using the folder.hasNewMessage() method in java mail api,but the method is returning false only regardless new mail is there in inbox or not.
I want to read the unread messages only.Dont want to retrieve the already read mails.
I got the mail retrieving code from the below site.(sorry not posting the code because it is so long and having 4 classes)
http://www.builderau.com.au/program/java/soa/Getting_the_mail_in_receiving_in_JavaMail/0,39024620,39228060,00.htm
Can anyone tell me how to read unread mails in the inbox?
Thanks a lothi parvathi
i think your mail program is receving mails using imap
the imap is only receve the mail from server but the pop is deleting the mails after receving
use the following sample code
package com.sfrc.mail.pop;
import javax.mail.*;
import javax.mail.internet.*;
import com.sun.mail.handlers.message_rfc822;
import java.util.*;
import java.io.*;
* Owner: SFRC IT Solutions Pvt Ltd
* Author:Arunkumar Subramaniam
* Date :12-06-2006
* File Name: AttachRecive.java
public class AttachRecive
public static void main(String args[])
try
String popServer="192.168.1.1";
String popUser="pl";
String popPassword="password";
// Create empty properties
Properties props = new Properties();
// Get session
Session session = Session.getDefaultInstance(props, null);
// Get the store
Store store = session.getStore("pop3");
store.connect(popServer, popUser, popPassword);
// Get folder
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
// Get directory
Message message =folder.getMessages();
Multipart mp = (Multipart)message.getContent();
for (int i=0, n=mp.getCount(); i<n; i++) {
Part part = mp.getBodyPart(i);
String disposition = part.getDisposition();
// Close connection
folder.close(false);
store.close();
catch (Exception ex)
System.out.println("Usage: "
+" popServer popUser popPassword");
System.exit(0);
Regards
Arunkumar Subramaniam
SFRC IT Solutions Pvt Ltd
Chennai -
Oracle Java Mail API exception in Jdev 11.1.15
we are using java mail api to send out emails. and wrap it in java embedding with in our webservice.
we are using jdeveloper 11.1.1.5 for this and the Java API is failing with the below error, we have included all the java libraries. As code is working fine in Jdeveloper 11.1.2
we tried different version of jdeveloper ( 11.1.1.5, 11.1.1.7 ) but its still the same. Can some one please suggest
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Can't send command to SMTP host;
nested exception is:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at bts.mail.SendMailTLS.main(SendMailTLS.java:50)
Caused by: javax.mail.MessagingException: Can't send command to SMTP host;
nested exception is:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1420)
at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1408)
at com.sun.mail.smtp.SMTPTransport.ehlo(SMTPTransport.java:847)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:384)
at javax.mail.Service.connect(Service.java:297)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:105)
at javax.mail.Transport.send0(Transport.java:168)
at javax.mail.Transport.send(Transport.java:98)
at bts.mail.SendMailTLS.main(SendMailTLS.java:45)Can Some body help me with this please
-
Save Attachment from exchange server 2010 from oracle using java mail API
Hello,
I want to read email from microsoft exchangeserver 2010 and save attachement into a folder.I created an Java program to import attachments from a exchange server mailbox using "POP3S".It works fine when run as a java application.But when i put this inside Oracle11g R2 using load java and while executing from a procedure it gives an error at parsing message into Multipart
Error at line : Multipart mp = (Multipart)m.getContent();
Error:
Content-Type: multipart/mixed;
boundary="_002_A0C2E09A..................................."
java.lang.ClassCastException
at mailPop3.checkmail(mailPop3:71)
My Java Class is as follows,
import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Date;
The function i used to check for attachments is given below.
public static boolean hasAttachments(Message m) throws java.io.IOException, MessagingException
Boolean hasAttachments = false;
try
// if it is a plain/html text - no attachements
if (m.isMimeType("text/*"))
return hasAttachments;
else if (m.isMimeType("multipart/alternative"))
return hasAttachments;
else if (m.isMimeType("multipart/*"))
Multipart mp = (Multipart)m.getContent();
if (mp.getCount() > 1)
hasAttachments = true;
return hasAttachments;
catch (Exception e) {
e.printStackTrace();
} finally {
return hasAttachments;
My Java Details as follows
java Version :1.5.0_10
java.vm.specification.version:1.0
java.vm.version :1.5.0_01
java.specification.version:1.5
java.class.version:48.0
Java mail API:javamail-1.4.4
Used Jars:mail.jar
Could someone explain why I am getting this error? What can I do to resolve this error?
Is any other Jar need other than mail.jar?
Any help would be much appreciated.
Regards,
NisanthHai EJP,
Thanks for your reply,
My full java class as follows,
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Part;
import javax.mail.Multipart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeMessage;
public class Newmail
public Newmail()
super();
public static int mailPOP3(String phost,
String pusername,
String ppassword)
Folder inbox =null;
Store store =null;
int result = 1;
try
String host=phost;
final String username=pusername;
final String password=ppassword;
System.out.println("Authenticator");
Authenticator auth=new Authenticator()
protected PasswordAuthentication getPasswordAuthentication()
return new PasswordAuthentication(username, password);
System.out.println("Certificate");
String filename="D:\\Certi\\jssecacerts";
String password2 = "changeit";
System.setProperty("javax.net.ssl.trustStore",filename);
System.setProperty("javax.net.ssl.trustStorePassword",password2);
Properties props = System.getProperties();
System.out.println("host-----"+props);
props.setProperty("mail.pop3s.port", "993");
props.setProperty("mail.pop3s.starttls.enable","true");
props.setProperty("mail.pop3s.ssl.trust", "*");
Session session = Session.getInstance(props,auth);
session.setDebug(true);
store = session.getStore("pop3s");
System.out.println("store------"+store);
store.connect(host,username,password);
System.out.println("Connected...");
inbox = store.getDefaultFolder().getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message[] msgs = inbox.getMessages();
System.out.println("msgs.length-----"+msgs.length);
result = 0;
int no_of_messages = msgs.length;
for ( int i=0; i < no_of_messages; i++)
System.out.println("msgs.count-----"+i);
System.out.println("Attachment....>"+msgs.getContentType());
Multipart mp = (Multipart)msgs[i].getContent();
System.out.println("Casting Success" + mp.getContentType());
catch(Exception e)
e.printStackTrace();
finally
try
if(inbox!=null)
inbox.close(false);
if(store!=null)
store.close();
return result;
catch(Exception e)
e.printStackTrace();
return result;
Please check it
Regards,
Nisanth -
Complete working code for Gmail POP3 & SMTP with SSL - Java mail API
Finally, your code-hunt has come to an end!!!!
I am presenting you the complete solution (with code) to send and retrieve you mails to & from GMAIL using SMTP and POP3 with SSL & Authenticaion enabled. [Even starters & newbies like me, can easy try, test & understand - But first download & add JAR's of Java Mail API & Java Activation Framework to Netbeans Library Manager]
Download Java Mail API here
http://java.sun.com/products/javamail/
Read Java Mail FAQ's here
http://java.sun.com/products/javamail/FAQ.html
Download Java Activation Framework [JAF]
http://java.sun.com/products/javabeans/jaf/downloads/index.html
Also, The POP program retrieves the mail sent with SMTP program :) [MOST IMPORTANT & LARGELY IN DEMAND]okey.. first things first... all of your thanks goes to the following and not a s@!te to me :)
hail Java !!
hail Java mail API !!
hail Java forums !!
hail Java-tips.org !!
hail Netbeans !!
Thanks to all coders who helped me by getting the code to work in one piece.
special thanks to "bshannon" - The dude who runs this forum from 97!!I am just as happy as you will be when you execute the below code!! [my 13 hours of tweaking & code hunting has paid off!!]
Now here it is...I only present you the complete solution!!
START OF PROGRAM 1
SENDING A MAIL FROM GMAIL ACCOUNT USING SMTP [STARTTLS (SSL)] PROTOCOL OF JAVA MAIL APINote on Program 1:
1. In the code below replace USERNAME & PASSWORD with your respective GMAIL account username and its corresponding password!
2. Use the code to make your Gmail client [jsp/servlets whatever]
//Mail.java - smtp sending starttls (ssl) authentication enabled
//1.Open a new Java class in netbeans (default package of the project) and name it as "Mail.java"
//2.Copy paste the entire code below and save it.
//3.Right click on the file name in the left side panel and click "compile" then click "Run"
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class Main
String d_email = "[email protected]",
d_password = "PASSWORD",
d_host = "smtp.gmail.com",
d_port = "465",
m_to = "[email protected]",
m_subject = "Testing",
m_text = "Hey, this is the testing email.";
public Main()
Properties props = new Properties();
props.put("mail.smtp.user", d_email);
props.put("mail.smtp.host", d_host);
props.put("mail.smtp.port", d_port);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true");
//props.put("mail.smtp.debug", "true");
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SecurityManager security = System.getSecurityManager();
try
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
//session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
msg.setText(m_text);
msg.setSubject(m_subject);
msg.setFrom(new InternetAddress(d_email));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
Transport.send(msg);
catch (Exception mex)
mex.printStackTrace();
public static void main(String[] args)
Main blah = new Main();
private class SMTPAuthenticator extends javax.mail.Authenticator
public PasswordAuthentication getPasswordAuthentication()
return new PasswordAuthentication(d_email, d_password);
END OF PROGRAM 1-----
START OF PROGRAM 2
RETRIVE ALL THE MAILS FROM GMAIL INBOX USING Post Office Protocol POP3 [SSL] PROTOCOL OF JAVA MAIL APINote:
1.Log into your gmail account via webmail [http://mail.google.com/]
2.Click on "settings" and select "Mail Forwarding & POP3/IMAP"
3.Select "enable POP for all mail" and "save changes"
4.In the code below replace USERNAME & PASSWORD with your respective GMAIL account username and its corresponding password!
PROGRAM 2 - PART 1 - Main.java
//1.Open a new Java class file in the default package
//2.Copy paste the below code and rename it to Mail.java
//3.Compile and execute this code.
public class Main {
/** Creates a new instance of Main */
public Main() {
* @param args the command line arguments
public static void main(String[] args) {
try {
GmailUtilities gmail = new GmailUtilities();
gmail.setUserPass("[email protected]", "PASSWORD");
gmail.connect();
gmail.openFolder("INBOX");
int totalMessages = gmail.getMessageCount();
int newMessages = gmail.getNewMessageCount();
System.out.println("Total messages = " + totalMessages);
System.out.println("New messages = " + newMessages);
System.out.println("-------------------------------");
//Uncomment the below line to print the body of the message. Remember it will eat-up your bandwidth if you have 100's of messages. //gmail.printAllMessageEnvelopes();
gmail.printAllMessages();
} catch(Exception e) {
e.printStackTrace();
System.exit(-1);
END OF PART 1
PROGRAM 2 - PART 2 - GmailUtilities.java
//1.Open a new Java class in the project (default package)
//2.Copy paste the below code
//3.Compile - Don't execute this[Run]
import com.sun.mail.pop3.POP3SSLStore;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.FetchProfile;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.ContentType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.ParseException;
public class GmailUtilities {
private Session session = null;
private Store store = null;
private String username, password;
private Folder folder;
public GmailUtilities() {
public void setUserPass(String username, String password) {
this.username = username;
this.password = password;
public void connect() throws Exception {
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties pop3Props = new Properties();
pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
pop3Props.setProperty("mail.pop3.port", "995");
pop3Props.setProperty("mail.pop3.socketFactory.port", "995");
URLName url = new URLName("pop3", "pop.gmail.com", 995, "",
username, password);
session = Session.getInstance(pop3Props, null);
store = new POP3SSLStore(session, url);
store.connect();
public void openFolder(String folderName) throws Exception {
// Open the Folder
folder = store.getDefaultFolder();
folder = folder.getFolder(folderName);
if (folder == null) {
throw new Exception("Invalid folder");
// try to open read/write and if that fails try read-only
try {
folder.open(Folder.READ_WRITE);
} catch (MessagingException ex) {
folder.open(Folder.READ_ONLY);
public void closeFolder() throws Exception {
folder.close(false);
public int getMessageCount() throws Exception {
return folder.getMessageCount();
public int getNewMessageCount() throws Exception {
return folder.getNewMessageCount();
public void disconnect() throws Exception {
store.close();
public void printMessage(int messageNo) throws Exception {
System.out.println("Getting message number: " + messageNo);
Message m = null;
try {
m = folder.getMessage(messageNo);
dumpPart(m);
} catch (IndexOutOfBoundsException iex) {
System.out.println("Message number out of range");
public void printAllMessageEnvelopes() throws Exception {
// Attributes & Flags for all messages ..
Message[] msgs = folder.getMessages();
// Use a suitable FetchProfile
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
folder.fetch(msgs, fp);
for (int i = 0; i < msgs.length; i++) {
System.out.println("--------------------------");
System.out.println("MESSAGE #" + (i + 1) + ":");
dumpEnvelope(msgs);
public void printAllMessages() throws Exception {
// Attributes & Flags for all messages ..
Message[] msgs = folder.getMessages();
// Use a suitable FetchProfile
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
folder.fetch(msgs, fp);
for (int i = 0; i < msgs.length; i++) {
System.out.println("--------------------------");
System.out.println("MESSAGE #" + (i + 1) + ":");
dumpPart(msgs[i]);
public static void dumpPart(Part p) throws Exception {
if (p instanceof Message)
dumpEnvelope((Message)p);
String ct = p.getContentType();
try {
pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
} catch (ParseException pex) {
pr("BAD CONTENT-TYPE: " + ct);
* Using isMimeType to determine the content type avoids
* fetching the actual content data until we need it.
if (p.isMimeType("text/plain")) {
pr("This is plain text");
pr("---------------------------");
System.out.println((String)p.getContent());
} else {
// just a separator
pr("---------------------------");
public static void dumpEnvelope(Message m) throws Exception {
pr(" ");
Address[] a;
// FROM
if ((a = m.getFrom()) != null) {
for (int j = 0; j < a.length; j++)
pr("FROM: " + a[j].toString());
// TO
if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < a.length; j++) {
pr("TO: " + a[j].toString());
// SUBJECT
pr("SUBJECT: " + m.getSubject());
// DATE
Date d = m.getSentDate();
pr("SendDate: " +
(d != null ? d.toString() : "UNKNOWN"));
static String indentStr = " ";
static int level = 0;
* Print a, possibly indented, string.
public static void pr(String s) {
System.out.print(indentStr.substring(0, level * 2));
System.out.println(s);
}END OF PART 2
END OF PROGRAM 2
P.S: CHECKING !!
STEP 1.
First compile and execute the PROGRAM 1 with your USERNAME & PASSWORD. This will send a mail to your own account.
STEP 2.
Now compile both PART 1 & PART 2 of PROGRAM 2. Then, execute PART 1 - Main.java. This will retrive the mail sent in step 1. njoy! :)
In future, I hope this is added to the demo programs of the Java Mail API download package.
This is for 3 main reasons...
1. To prevent a lot of silly questions being posted on this forum [like the ones I did :(].
2. To give the first time Java Mail user with a real time working example without code modification [code has to use command line args like the demo programs - for instant results].
3. Also, this is what google has to say..
"The Gmail Team is committed to making sure you always can access your mail. That's why we're offering POP access and auto-forwarding. Both features are free for all Gmail users and we have no plans to charge for them in the future."
http://mail.google.com/support/bin/answer.py?answer=13295
I guess bshannon & Java Mail team is hearing this....
Again, Hurray and thanks for helping me make it!! cheers & no more frowned faces!!
(: (: (: (: (: GO JCODERS GO!! :) :) :) :) :)
codeace
-----Thanks for the reply,
I did checked by enabling session debuging and also checked pop settings it's enabled for all
mails, I tried deleting some very old messages and now the message count is changed to 310.
This may be the problem with gmail.
Bellow is the output i got,
DEBUG: setDebug: JavaMail version 1.4ea
DEBUG: getProvider() returning javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]
DEBUG POP3: connecting to host "pop.gmail.com", port 995, isSSL false
S: +OK Gpop ready for requests from 121.243.255.240 n22pf5432603pof.2
C: USER [email protected]
S: +OK send PASS
C: PASS my_password
S: +OK Welcome.
C: STAT
S: +OK 310 26900234
Custom output: messageCount : 310
C: QUIT
S: +OK Farewell. -
Problem using Java Mail API with WLS 7.0
Hi All,
I am trying to use the Java Mail API provided by WLS 7.0. I have made the
settings metioned in the WLS 7.0 docs. However when I try to run the program I
am getting the following error:
javax.naming.NoInitialContextException: Need to specify class name in environment
or system property, or as an applet parameter, or in an application resource file:
java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:6
46)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:246
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.jav
a:283)
at javax.naming.InitialContext.lookup(InitialContext.java:350)
The code that I have written is as follows
import java.util.*;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.naming.*;
import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
public class MailTo {
public static void main(String args[])
try
//Context ic = getInitialContext();
InitialContext ic = new InitialContext();
/* My jndi name is "testSession" */
Session session = (Session) ic.lookup("testSession"); /* THE PROBLEM IS SHOWN
IN THIS LINE */
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "XX.XX.XX.XX");
/* For security reasons I have written the ip add in this format */
props.put("mail.from", "[email protected]"); /* for security reasons i have
changed the mail address */
Session session2 = session.getInstance(props);
Message msg = new MimeMessage(session2);
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]",
false));
msg.setSubject("Test Message");
msg.setSentDate(new Date());
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText("This is a mail sent to you using JAVA Mail API and Weblogic Server");
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp);
msg.setContent(mp);
Transport.send(msg);
catch(Exception e)
e.printStackTrace();
}//end of main
public static Context getInitialContext()
throws NamingException
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
p.put(Context.PROVIDER_URL, "t3://localhost:7501/testWebApp");
p.put(Context.SECURITY_PRINCIPAL, "weblogic");
p.put(Context.SECURITY_CREDENTIALS, "weblogic");
return new InitialContext(p);
}//end of class
Can anyone please tell me what is the problem. I thought that we cannot directly
do
InitialContext ic = new InitialContext();
So I had written a method getInitialContext() as shown in the above piece of code,
but that too did not work.
Eagerly awaiting a response.
Jimmy ShahYou can use InitialContext ic = new InitialContext() only if you are using a startup class, servlet or a JSP i.e
server side code.
If you are using a java client you need to use Context ic = getInitialContext();
Try this code
import java.util.*;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.naming.*;
import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
public class MailTo {
public static void main(String args[])
try {
Properties h = new Properties();
h.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
h.put(Context.PROVIDER_URL, "t3://localhost:7001");
Context ic = new InitialContext(h);
Session session = (Session) ic.lookup("testSession");
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "XX.XX.XX.XX");
props.put("mail.from", "[email protected]");
Session session2 = session.getInstance(props);
Message msg = new MimeMessage(session2);
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse("[email protected]",false));
msg.setSubject("Test Message");
msg.setSentDate(new Date());
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText("This is a mail sent to you using JAVA Mail API and Weblogic Server");
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp);
msg.setContent(mp);
Transport.send(msg);
catch(Exception e)
e.printStackTrace();
}//end of main
}//end of class
We have shipped a javamail example in the samples\server\src\examples\javamail folder.
Jimmy Shah wrote:
Hi All,
I am trying to use the Java Mail API provided by WLS 7.0. I have made the
settings metioned in the WLS 7.0 docs. However when I try to run the program I
am getting the following error:
javax.naming.NoInitialContextException: Need to specify class name in environment
or system property, or as an applet parameter, or in an application resource file:
java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:6
46)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:246
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.jav
a:283)
at javax.naming.InitialContext.lookup(InitialContext.java:350)
The code that I have written is as follows
import java.util.*;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.naming.*;
import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
public class MailTo {
public static void main(String args[])
try
//Context ic = getInitialContext();
InitialContext ic = new InitialContext();
/* My jndi name is "testSession" */
Session session = (Session) ic.lookup("testSession"); /* THE PROBLEM IS SHOWN
IN THIS LINE */
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "XX.XX.XX.XX");
/* For security reasons I have written the ip add in this format */
props.put("mail.from", "[email protected]"); /* for security reasons i have
changed the mail address */
Session session2 = session.getInstance(props);
Message msg = new MimeMessage(session2);
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]",
false));
msg.setSubject("Test Message");
msg.setSentDate(new Date());
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText("This is a mail sent to you using JAVA Mail API and Weblogic Server");
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp);
msg.setContent(mp);
Transport.send(msg);
catch(Exception e)
e.printStackTrace();
}//end of main
public static Context getInitialContext()
throws NamingException
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
p.put(Context.PROVIDER_URL, "t3://localhost:7501/testWebApp");
p.put(Context.SECURITY_PRINCIPAL, "weblogic");
p.put(Context.SECURITY_CREDENTIALS, "weblogic");
return new InitialContext(p);
}//end of class
Can anyone please tell me what is the problem. I thought that we cannot directly
do
InitialContext ic = new InitialContext();
So I had written a method getInitialContext() as shown in the above piece of code,
but that too did not work.
Eagerly awaiting a response.
Jimmy Shah--
Rajesh Mirchandani
Developer Relations Engineer
BEA Support -
Using Java Mail API from Tomcat
Hello,
Purely as an academic exercise I have written a JSP page which, upon being requested from the client's browser, should send me a default email using Java Mail Api.
here is the code :
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class TestMail {
static String msgText1 = "success this time 12";
static String msgText2 = "This is the text in the message attachment.";
public String sendIt() {
String to = "<my email";
String from = "<anything>";
String host = "<my ip address of smtp server>";
boolean debug = false;
Properties props = new Properties();
props.put("mail.smtp.host", host);
Session session = Session.getInstance(props, null);
.....The code works fine as a stand alone app but when called from JSP page it hangs on the Session.getInstance line. I can only guess that this might be a security issue with the container not allowing access to the smtp server ?
Can anyone give me a clue ???Your Tomcat log files should spell out the problem for you.
My Tomcat installation does not come with the Java Mail API. I had to add the mail and activation jar files to the server/common.lib directory (or the server's shared/lib or the WEB-INF/lib of your application.)
HTH. -
Java.lang.UnsupportedClassVersionError while using java mail api
Hi Everybody ,
I am new comer to this forum , and would like to be an active member.
I am getting this error while trying to use the java mail api to send an email using smtp.
The error is as follows :
Exception in thread "main" java.lang.UnsupportedClassVersionError: javax/mail/Message (Unsupported major.minor version 48.0)
Can Anyone please tell where I am wrong.
I am using the following code
==============================================================
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.abc.com");
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++)
addressTo[i] = new InternetAddress(recipients);
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Optional : You can also set your custom headers in the Email if you Want
msg.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
==============================================================Hi Philip ,
Thanks for the prompt reply , I had installed oracle client services which overid my jdk1.4 installation with jdk1.3 and hence the error. I changed my classpath settings to point to jdk1.4 and it owrked properly.
Thanks once again.
regards,
Rupesh Rajan -
Problem with sending mail throgh java mail api
hi folks,
We are having problem regarding sending mail using java mail api.
we are using msgsendsample.java file from demo folder contained in javamail-1.3.3_01 folder.
we are using following command at dos prompt.:
java msgsendsample [email protected] [email protected] smtp.mail.yahoo.com false
It gives following Exception:
--Exception handling in msgsendsample.java
com.sun.mail.smtp.SMTPSendFailedException: 530 authentication required - for hel
p go to http://help.yahoo.com/help/us/mail/pop/pop-11.html
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1
333) at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:906)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:535)
at javax.mail.Transport.send0(Transport.java:151)
at javax.mail.Transport.send(Transport.java:80)
at msgsendsample.main(msgsendsample.java:93)
** ValidUnsent Addresses
[email protected]
Thanking in Advance...
Please give us guidance to any alternate solution if exists.hi
the smtp server u are using should allow u to send mail to other smtp server like if u r sending mail to yahoo account u have to use yahoo smtp server only .....
bye -
Java mail api - sending mails to gmail account
Hello
I am using java mail api to send mails.when i send mails to gmail from ids which are not in gmail friends list, most of the mails are going to spam.Ofcourse, some of them go to inbox.I tried in lot of ways to analyse the problem.But nothing could help. Can anyone plzz tell me how to avoid mails going to spam in gmail, using java mail api?
Thank you in advance,
Regards,
Aradhana
Message was edited by:
Aradhanaam using the below code.
Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port","25");
props.put("mail.smtp.auth", isAuth);
Authenticator auth = new UserAuthenticator();
// Get session
Session s = Session.getDefaultInstance(props,auth);
// Define message
Message m = new MimeMessage(s);
// setting message attributes
try {
m.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
InternetAddress f_addr=new InternetAddress(from);
f_addr.setPersonal(personalName);
m.setFrom(f_addr);
m.setSubject(subject);
m.setSentDate(new Date());
m.setContent(msg,"text/plain");
m.saveChanges();
// send message
Transport.send(m);
Message was edited by:
Aradhana -
Hi
We have a requirement to create a custom e mail. For the same I am trying to use Java Mail API.I am facing an issue with the following code:
session session1 = session.getInstance(properties, null);
System gives an error Sourced file: inline evaluation of: ``Properties props = new Properties(); session session1 = session.getInstance(prop . . . '' : Typed variable declaration : Class: session not found in namespace
Is there some specific API i need to import for session class. Kindly suggest.
Regards
ShobhaHi Shobha,
I was also facing the same issue from last couple of weeks and just now i have achieved the working functionality.
Please find below working code and replace values as per your serveru2019s configuration.
import com.sap.odp.api.util.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.io.File;
import java.net.*;
// SUBSTITUTE YOUR EMAIL ADDRESSES HERE!!!
String to =<email address>;
String from =<email address>;
// SUBSTITUTE YOUR ISP'S MAIL SERVER HERE!!!
String host = <smtp host name>;
String user = <smtp user name>;
// Create properties, get Session
// Properties props = new Properties();
Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", host);
props.put("mail.debug", "false");
props.put("mail.smtp.auth", "false");
props.put("mail.user",user);
props.put("mail.from",from);
Session d_session = Session.getInstance(props,null);//Authenticator object need to be set
Message msg = new MimeMessage(d_session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("Test E-Mail through Java");
msg.setSentDate(new Date());
msg.setText("This is a test of sending a " +
"plain text e-mail through Java.\n" +
"Here is line 2.");
Transport.send(msg);
Deepak!!!
Maybe you are looking for
-
I am at a complete loss. I was at the mac store today in Covent Garden. I have a MacBook pro and was telling the guy at the genius bar that my computer is really slow and just not working in some odd ways. He checks my hard drive and tells me my com
-
Backing up iPhoto files to an external hard drive.
I cannot drag and drop, nor copy and paste photos from iPhoto to an external hard drive, whether as a copy of the complete iPhoto library or as individual photos, nor can I copy/drag a copy of the iPhoto library from the desktop to an external hard d
-
My Apple ID keeps getting disabled for security purposes and I'm not sure why. Can you help please?
-
Canvas Black Border Sizing Issue
I recorded a video using a SONY HDV camera - but recorded it in DV - which I captured into FCP. I created a Sequence and edited the video. When I look at it in the "Canvas", there is a huge black border around the video! When I exported the video to
-
Is connect part of creative cloud?
is connect part of creative cloud?