How to get the sender's address when getFrom returns null in javamail?

N

news

I wrote a program using javamail to fetch meesages from my pop3 account. The
prolem is that the getFrom always return null for the fetched messages. It
seems that no headers are attached with the fetched messages. I understand
that the getFrom may return null. Could someone tell me how to get the
sender and receiver's address from the messages received using javamail?

Thanks a lot.
 
R

Roedy Green

I wrote a program using javamail to fetch meesages from my pop3 account. The
prolem is that the getFrom always return null for the fetched messages. It
seems that no headers are attached with the fetched messages. I understand
that the getFrom may return null. Could someone tell me how to get the
sender and receiver's address from the messages received using javamail?

here is a snippet of code from the bulk emailer
http://mindprod.com/products.html#BULK

It ensures the sender is one of an authorised list.

Address[] froms = rm.getFrom();
if ( froms.length != 1 ) return false;
from = ( InternetAddress )froms[ 0 ];
String sender = from.getAddress();
if ( !validSendersSet.contains( sender ) )
{
return false;
}
 
G

GaryM

I wrote a program using javamail to fetch meesages from my pop3
account. The prolem is that the getFrom always return null for the
fetched messages. It seems that no headers are attached with the
fetched messages. I understand that the getFrom may return null.
Could someone tell me how to get the sender and receiver's address
from the messages received using javamail?

Thanks a lot.

Why not post some code? Javamail _will_ return the from address if
there is one on the Message object. That is all that can be said
definitively.
 
N

news

My code is here:

public static void receive(String popServer, String popUser, String
popPassword)
{

Store store=null;
Folder folder=null;

try
{
// -- Get hold of the default session --
Properties props = System.getProperties();
Session session = Session.getInstance(props, null);

// -- Get hold of a POP3 message store, and connect to it --
store = session.getStore("pop3");
store.connect(popServer, popUser, popPassword);
folder = store.getFolder("INBOX");
if (folder == null) throw new Exception("No POP3 INBOX");

// -- Open the folder for read only --
folder.open(Folder.READ_ONLY);
Message[] msg = folder.getMessagesfor (int i = 0; i <
folder.getMessageCount(); i++)
{
System.out.println((msg.getFrom()).length);
}

A NullPointerException always occured for the line
"System.out.println((msg.getFrom()).length);" since getFrom return null.
I don't know why. Is there othere way to get sender address?

Thank you very much.


Roedy Green said:
I wrote a program using javamail to fetch meesages from my pop3 account. The
prolem is that the getFrom always return null for the fetched messages. It
seems that no headers are attached with the fetched messages. I understand
that the getFrom may return null. Could someone tell me how to get the
sender and receiver's address from the messages received using javamail?

here is a snippet of code from the bulk emailer
http://mindprod.com/products.html#BULK

It ensures the sender is one of an authorised list.

Address[] froms = rm.getFrom();
if ( froms.length != 1 ) return false;
from = ( InternetAddress )froms[ 0 ];
String sender = from.getAddress();
if ( !validSendersSet.contains( sender ) )
{
return false;
}
 
G

GaryM

A NullPointerException always occured for the line
"System.out.println((msg.getFrom()).length);" since getFrom
return null. I don't know why. Is there othere way to get sender
address?


Looks OK except 2 things.

1. getFrom() can legitimately return a null or empty array depending
on the existence of the From attribute, or the attribute containing
email addresses respectively. The From attribute is OPTIONAL so you
should have some code to handle the possible null and empty
solutions.

2. The for-loop condition of getMessageCount(). This is an expensive
method to be calling for each iteration. Moreover it is potentially
dynamic (a message could arrive any time, changing the count and
putting it out of sync with the Message[]). Best to condition it on
the msg.length.

By the way, do you know what is null ? The getFrom(), or the msg?
I suspect it's the msg, as system.out.println would print the null
String. Are there messages in this mailbox and do these messages
definitely have From attributes?

This should be a simple problem, but I recognize it can be
infuriating to debug this. If you'd like to provide more info via
email feel free.

Gary
 
N

news

Hi Gary,

Thank you very much for your helpful comments.

I do have mails in the inbox, and if I comment out the getFrom statement and
add getContent code to the msg I got the content of the mail to e print
out. So the prolem is the getFrom.

Store store=null;
Folder folder=null;
try
{
// -- Get hold of the default session --
Properties props = System.getProperties();
Session session = Session.getInstance(props, null);

// -- Get hold of a POP3 message store, and connect to it --
store = session.getStore("pop3");
store.connect(popServer, popUser, popPassword);

// -- Try to get hold of the default folder --
// folder = store.getDefaultFolder();
// if (folder == null) throw new Exception("No default folder");

// -- ...and its INBOX --
folder = store.getFolder("INBOX");
if (folder == null) throw new Exception("No POP3 INBOX");

// -- Open the folder for read only --
folder.open(Folder.READ_ONLY);
Message[] msg = folder.getMessages
count = folder.getMessageCount();
for (int i = 0; i < count;i++)
{
System.out.println((msg.getFrom()).length);
printMessage(msgs);
}

}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
// -- Close down nicely --
try
{
if (folder!=null) folder.close(false);
if (store!=null) store.close();
}

catch (Exception ex2) {ex2.printStackTrace();}
}
GaryM said:
A NullPointerException always occured for the line
"System.out.println((msg.getFrom()).length);" since getFrom
return null. I don't know why. Is there othere way to get sender
address?


Looks OK except 2 things.

1. getFrom() can legitimately return a null or empty array depending
on the existence of the From attribute, or the attribute containing
email addresses respectively. The From attribute is OPTIONAL so you
should have some code to handle the possible null and empty
solutions.

2. The for-loop condition of getMessageCount(). This is an expensive
method to be calling for each iteration. Moreover it is potentially
dynamic (a message could arrive any time, changing the count and
putting it out of sync with the Message[]). Best to condition it on
the msg.length.

By the way, do you know what is null ? The getFrom(), or the msg?
I suspect it's the msg, as system.out.println would print the null
String. Are there messages in this mailbox and do these messages
definitely have From attributes?

This should be a simple problem, but I recognize it can be
infuriating to debug this. If you'd like to provide more info via
email feel free.

Gary
 
G

GaryM

Hi Gary,

Thank you very much for your helpful comments.

You did not say whether the message has a From line or not. I assume
it has. Can you post the headers to the message? Just munge the stuff
that you prefer not to be public or spam-harvested.

If you prefer not to, try the following 2 scenarios (I am writing it
from memory so fix syntax if necessary). Insert these in your message
loop in place of the code you have:

// Scenario 1: See if this finds the From line
String[] froms = msg.getHeader("From");
System.out.println("Number of From attrs in msg id-->" + msg
.getMessageID + " is " + froms.length);


// Scenario 2: List all headers
for (Enumeration e = msg.getAllHeaders(); e.hasMoreElements(); ) {
System.out.println(e.nextElement());
}


Did either register the existence of the From attribute?
 
N

news

Here is the most part of my code, I also attached the print out of the
program:

public static void receive(String popServer, String popUser, String
popPassword)
{

Store store=null;
Folder folder=null;

try
{
// -- Get hold of the default session --
Properties props = System.getProperties();
Session session = Session.getInstance(props, null);

// -- Get hold of a POP3 message store, and connect to it --
store = session.getStore("pop3");
store.connect(popServer, popUser, popPassword);

// -- ...and its INBOX --
folder = store.getFolder("INBOX");
if (folder == null) throw new Exception("No POP3 INBOX");

// -- Open the folder for read only --
folder.open(Folder.READ_ONLY);
Message[] msg = folder.getMessages();
int count = folder.getMessageCount();
for (int i = 0; i < count; i++)
{
String[] froms = msg.getHeader("From");
printMessage(msg);
}

}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
// -- Close down nicely --
try
{
if (folder!=null) folder.close(false);
if (store!=null) store.close();
}
catch (Exception ex2) {ex2.printStackTrace();}
}
}
/**
* "printMessage()" method to print a message.
*/
public static void printMessage(Message message)
{
try
{
for (Enumeration e = message.getAllHeaders();
e.hasMoreElements(); ){
System.out.println("Headers: "+ e.nextElement());}

if (message.getAllHeaders() != null)
System.out.println("Got headers for the received emails");
// -- Get the message part (i.e. the message itself) --
Part messagePart=message;
Object content=messagePart.getContent();

// -- or its first body part if it is a multipart message --
if (content instanceof Multipart)
{
messagePart=((Multipart)content).getBodyPart(0);
System.out.println("I got a Multipart Message!");
}

// -- Get the content type --
String contentType=messagePart.getContentType();

// -- If the content is plain text, we can print it --
System.out.println("The CONTENT type for the message:"+contentType);

if (contentType.startsWith("text/plain")
|| contentType.startsWith("text/html"))
{
InputStream is = messagePart.getInputStream();

BufferedReader reader
=new BufferedReader(new InputStreamReader(is));
String thisLine=reader.readLine();

while (thisLine!=null)
{
System.out.println(thisLine);
thisLine=reader.readLine();
}
}

System.out.println("-----------------------------");
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
The printout is as follows:

Got headers for the received emails
The CONTENT type for the message:text/plain
This is a multi-part message in MIME format.
------=_NextPart_000_002F_01C39A14.EDE61C50
Content-Type: multipart/alternative;
boundary="----=_NextPart_001_0030_01C39A14.EDE61C50"
------=_NextPart_001_0030_01C39A14.EDE61C50
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
This is my test email. I want to check if getFrom and multiPart work.
------=_NextPart_001_0030_01C39A14.EDE61C50
Content-Type: text/html;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META content=3D"text/html; charset=3Diso-8859-1" =
http-equiv=3DContent-Type>
<META content=3D"MSHTML 5.00.3502.5390" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV><FONT face=3DArial size=3D2>This is my test email. I want to check =
if getFrom=20
and multiPart work.</FONT></DIV></BODY></HTML>
------=_NextPart_001_0030_01C39A14.EDE61C50--
------=_NextPart_000_002F_01C39A14.EDE61C50
Content-Type: text/plain;
name="note.txt"
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment;
filename="note.txt"
Implementing a Queue
LinkedList queue = new LinkedList();

// Add to end of queue
queue.add(object);

// Get head of queue
Object o = queue.removeFirst();

// If the queue is to be used by multiple threads,
// the queue must be wrapped with code to synchronize the methods
queue = (LinkedList)Collections.synchronizedList(queue);
-------------------------------------------------------
------=_NextPart_000_002F_01C39A14.EDE61C50--
-----------------------------

You can see from here:

1. getAllHeaders didn't return null, but nothing was printed out when going
through the enumeration
2. no from lines in the message printed out
3. This message has an attachment so that it should be a multipart message.
But the program thought it is not.

I am not sure this is a javamail problem or email server problem. I am using
javamail1.3.1. Could you continue to help me to figure it out?
Thank you very much. I really appreciate your time and help.
 
G

GaryM

Zhao, I am interested in the section I pasted below. Leave the rest
for another time as there are issues with it not relevant to this
problem.

The code I copied below is not executing at all, meaning the message
attributes are not being retrieved when you ask for them with the
getAllHeaders() method.

The Message object gets data from the server as and when you ask for
it (not all of it at once). If the Enumeration is empty, something is
falling apart during the getAllHeaders() call.

Anyway, need to put Javamail in debug mode. To do this add the
property.

props.put("mail.debug","true");

Put this after your Property declaration.

When you run the code I suggest you restrict printMessage to what I
have copied below so you can easily see the debug messages. Likewise
remove this line from the Message loop.

String[] froms = msg.getHeader("From");

So you will only have:

* the connect
* the calling of getAllheaders()
* the closing of the connection

in your debug log.

Let me know what you see,

Gary




Here is the most part of my code, I also attached the print out of
the program:

/**
* "printMessage()" method to print a message.
*/
public static void printMessage(Message message)
{
try
{
for (Enumeration e = message.getAllHeaders();
e.hasMoreElements(); ){
System.out.println("Headers: "+ e.nextElement());}
 
N

news

Hi Gary,

I am really appreciate your kindness. Here are the output after the debug is
set on:

DEBUG: JavaMail version 1.3.1ea
DEBUG: java.io.FileNotFoundException:
C:\JBuilder9\jdk1.4\jre\lib\javamail.providers (The system cannot find the
file specified)
DEBUG: !anyLoaded
DEBUG: not loading resource: /META-INF/javamail.providers
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name:
{com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.
mail.smtp.SMTPTransport,Sun Microsystems, Inc],
com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap
..IMAPStore,Sun Microsystems, Inc],
com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3
..POP3Store,Sun Microsystems, Inc]}
DEBUG: Providers Listed By Protocol:
{imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun
Microsystems, Inc],
pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun
Microsystems, Inc],
smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun
Microsystems, Inc]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: !anyLoaded
DEBUG: not loading resource: /META-INF/javamail.address.map
DEBUG: java.io.FileNotFoundException:
C:\JBuilder9\jdk1.4\jre\lib\javamail.address.map (The system cannot find the
file specified)
DEBUG: getProvider() returning
javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems,
Inc]
DEBUG POP3: connecting to host "mailsrv11-pop3.siteserver.net", port 110
S: +OK POP3 server ready <12905920.1511460875@mailsrv11>
C: USER (e-mail address removed)
S: +OK Please send PASS
C: PASS ********
S: +OK User mailbox has 1 message (2170 octets)
C: STAT
S: +OK 1 2170
C: QUIT
S: +OK

GaryM said:
Zhao, I am interested in the section I pasted below. Leave the rest
for another time as there are issues with it not relevant to this
problem.

The code I copied below is not executing at all, meaning the message
attributes are not being retrieved when you ask for them with the
getAllHeaders() method.

The Message object gets data from the server as and when you ask for
it (not all of it at once). If the Enumeration is empty, something is
falling apart during the getAllHeaders() call.

Anyway, need to put Javamail in debug mode. To do this add the
property.

props.put("mail.debug","true");

Put this after your Property declaration.

When you run the code I suggest you restrict printMessage to what I
have copied below so you can easily see the debug messages. Likewise
remove this line from the Message loop.

String[] froms = msg.getHeader("From");

So you will only have:

* the connect
* the calling of getAllheaders()
* the closing of the connection

in your debug log.

Let me know what you see,

Gary




Here is the most part of my code, I also attached the print out of
the program:

/**
* "printMessage()" method to print a message.
*/
public static void printMessage(Message message)
{
try
{
for (Enumeration e = message.getAllHeaders();
e.hasMoreElements(); ){
System.out.println("Headers: "+ e.nextElement());}
 
N

news

Hi Gary,

If I use the following printMessage method:

public static void printMessage(Message message)
{
try
{
for (Enumeration e = message.getAllHeaders();
e.hasMoreElements(); ){
System.out.println("Headers: "+ e.nextElement());}

if (message.getAllHeaders() != null)
System.out.println("Got headers for the received emails"+
message.getHeader("Content-Type"));
// -- Get the message part (i.e. the message itself) --
Part messagePart=message;
Object content=messagePart.getContent();

// -- or its first body part if it is a multipart message --
if (content instanceof Multipart)
{
messagePart=((Multipart)content).getBodyPart(0);
System.out.println("I got a Multipart Message!");
}
}

With deug off, output is
Got headers for the received emails null
With debug on, the output is

DEBUG: JavaMail version 1.3.1ea
DEBUG: java.io.FileNotFoundException:
C:\JBuilder9\jdk1.4\jre\lib\javamail.providers (The system cannot find the
file specified)
DEBUG: !anyLoaded
DEBUG: not loading resource: /META-INF/javamail.providers
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name:
{com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.
mail.smtp.SMTPTransport,Sun Microsystems, Inc],
com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap
..IMAPStore,Sun Microsystems, Inc],
com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3
..POP3Store,Sun Microsystems, Inc]}
DEBUG: Providers Listed By Protocol:
{imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun
Microsystems, Inc],
pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun
Microsystems, Inc],
smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun
Microsystems, Inc]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: !anyLoaded
DEBUG: not loading resource: /META-INF/javamail.address.map
DEBUG: java.io.FileNotFoundException:
C:\JBuilder9\jdk1.4\jre\lib\javamail.address.map (The system cannot find the
file specified)
DEBUG: getProvider() returning
javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems,
Inc]
DEBUG POP3: connecting to host "mailsrv11-pop3.siteserver.net", port 110
S: +OK POP3 server ready <11186512.1514841515@mailsrv11>
C: USER (e-mail address removed)
S: +OK Please send PASS
C: PASS ***********
S: +OK User mailbox has 1 message (1361 octets)
C: STAT
S: +OK 1 1361
Got headers for the received emailsnull
C: RETR 1
S: +OK
Received: from [24.192.49.141] by mailsrv11.siteserver.net [63.203.180.102]
with SmartMax MailMax for (e-mail address removed); Fri, 24 Oct 2003
10:06:55 -0700
Return-Path: <[email protected]>
Message-ID: <009801c39a6b$27a419f0$cf00a8c0@wg014>
From: "Qiang Zhao" <[email protected]>
To: "Qiang Zhao" <[email protected]>
Subject: I am glad
Date: Fri, 24 Oct 2003 13:12:30 -0700
MIME-Version: 1.0
Content-Type: multipart/alternative;
boundary="----=_NextPart_000_0095_01C39A30.7A9727A0"
X-Priority: 3
X-MSMail-Priority: Normal
X-Mailer: Microsoft Outlook Express 5.50.4807.1700
X-MimeOLE: Produced By Microsoft MimeOLE V5.50.4910.0300
This is a multi-part message in MIME format.
------=_NextPart_000_0095_01C39A30.7A9727A0
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
------=_NextPart_000_0095_01C39A30.7A9727A0
Content-Type: text/html;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META content=3D"text/html; charset=3Diso-8859-1" =
http-equiv=3DContent-Type>
<META content=3D"MSHTML 5.00.3502.5390" name=3DGENERATOR>
<STYLE></STYLE>
</HEAD>
<BODY bgColor=3D#ffffff>
<DIV>&nbsp;</DIV></BODY></HTML>
------=_NextPart_000_0095_01C39A30.7A9727A0--
C: QUIT
S: +OK

It seems that from field appeared in the deug mode. How do you think?

Thank you very much, Gary.
 
G

GaryM

Hi Gary,

I am really appreciate your kindness. Here are the output after
the debug is set on:

Weird. I am not seeing a corresponding POP3 command for the
gettAllHeaders() method. The STAT corresponds to the getMessages()
(count and mailbox size). JavaMail would issued, for example, a "TOP
1 15" command after that.

I just checked the javamail source and all POP3 commands are sent to
the debug outstream BEFORE they are sent to the server. So obviously
something is happening before the command gets that far.

I am not sure where to go next though. Could there be character set
issues here?

Gary
 
G

GaryM

It seems that from field appeared in the deug mode. How do you think?

Thank you very much, Gary.

I just sent a reply to you before I saw this.

This confirms to me there is an issue specific to the retrieving of
headers. the POP3 Command "RETR 1" simply orders the server to retrieve
all of the message in response to the getContent() method. So the fact
that the headers are part of this is not surprising.

However, all commands related to the retrieving of headers are failing.
Do you have a non standard character set on your machine?
 
N

news

How to check if I have a non statndard character set in the machine? Sorry
to trouble you with so simple question. But I really don't know. Is that a
issue to the problem? Thanks.
 
G

GaryM

How to check if I have a non statndard character set in the
machine? Sorry to trouble you with so simple question. But I
really don't know. Is that a issue to the problem? Thanks.

You know I am just guessing and I don't want to waste your time. I
think it is best to write to someone on the Javamail team at this
point. I am fairly sure you are doing everything right. Try writing
to (e-mail address removed).

Check here for the protocol on how to submit bugs.

http://java.sun.com/products/javamail/NOTES.txt

I would definitely include the code and the debug output for the
version where you are doing the getAllHeaders(). This should make it
clear to the reader that Javamail is not working somewhere outside
your code.

I am very sorry I can't help you more with this. Please post back if
you find a solution.

Gary
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top