Solved

JavaMail : Transport.sendMessage() do not send mail to valid addresses

Posted on 2001-09-11
11
878 Views
Last Modified: 2013-11-24
JavaMail 1.2 Question

Transport.sendMessage(message, Addresses[]) should send the email messages to all the valid messages given in the array. On the other hand if Transport.send(message) is used then the message is sent only if all the email addresses are valid. Even if one email id is non valid the message is not delivered to the valid email ids. This is the case for send() method. However if sendMessage is used then, according to the documentation it should send the messages to the all valid email ids. But this is not happening for me. sendMessage and send methods are behaving the same way for me, that is, no mail is sent if single email id is invalid in the email ids given. However if all the email ids are OK then there is no problem. How to solve the sendMessage problem. Thanks!
0
Comment
Question by:javaq092999
  • 5
  • 3
  • 2
  • +1
11 Comments
 
LVL 7

Expert Comment

by:tomboshell
ID: 6474525
What about if you create a new method that checks the validity of the addresses before you send it?  You would have to program it yourself but it shouldn't be a problem.  
-send the array of addresses to the method
-loop through the entire array
-call the .toString() on each address to a temporary String
-evaluate the address (boolean pass true/false)
-if false mark that entry for deletion.
  in that method or a seperate method: use a ArrayList(or someother collection that you like) store each value individually into the collection that pass the test.  Call the .toArray() method.  (it returns an Object[]) then simply create a new Address[] sizing it to the length of the Object array.  Then loop through the Object array placing each value into the Addresss[] and finally return that array to your calling method.  
Then it would all depend how you check for valitiy.  I do know that it must be in the format: reciepient@host.extension.  like john@foo.com.  Since it is a string you check with the .indexOf("@"); method.  If it doesn't return a positive int then it is wrong.  Use the index to parse the string into substrings and check to see if each substring is alphanumeric or whatever.  

Tom
0
 

Author Comment

by:javaq092999
ID: 6475650
No Tom,

The problem occurs even when all the email formats are OK! No need for checking what you are saying. This is entirely related to valid emails (not well-formed emails). What I mean is that if you have two emails like me@abc.com and you@abc.com . In the email server only me@abc.com is registered. So when my JavaMail program sends a email to me@abc.com,you@abc.com then the whole emailing fails as you@abc.com is not there on the email server used (for abc.com)

--javaq
0
 
LVL 7

Expert Comment

by:tomboshell
ID: 6475968
Hmmm, not sure then.  I have just started playing around with the JavaMail.  But I wonder, if it sends back an error message and you catch it if you can re-send each e-mail individually.  Namely, it didn't go off in a mass email, so send each one off on its own.  It would involve more overhead. Too bad there is not a pre-verification.  

Been browsing the JavaDocs and looked at the TransportEvent.  It had some interestting methods (getInvalidAddresses(), getValidSentAddresses(), getValidUnsentAddresses())  That makes me wonder if adding a listener would help solve this problem.  

Anybody else have any ideas?
0
 

Author Comment

by:javaq092999
ID: 6475981
Nope again!

If Transport.sendMessage(Message, Address[]) fails it throws SendFailedException and this exception too have the methods like getInvalidAddresses(),
getValidSentAddresses(), getValidUnsentAddresses()). The point is that this exception SHOULD BE thrown once all the VALID emails are sent but this is not happening. All valid emails are not sent defying the documentation for this method in the JavaMail1.2 Documentation.

Anyone else?
0
 
LVL 10

Expert Comment

by:Nushi
ID: 6475994
you can use the function from a class i once placed here as answer.
you can use it free for you needs.

it get a String of the names with seperators and build Addresses from it:

http://www.experts-exchange.com/jsp/qShow.jsp?qid=20096487

/**
* This class serve as a util class for mail options
* Use this class to define mail properties.
*
* @see javax.mail.*;
* @see javax.mail.internet.*;
*
* @author Nushi
*/

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

public class NushiMail {
     
     //////////////////////////////////////
     //          MAIL SERVER     PROPERTIES          //
     //////////////////////////////////////
     
     //fields for message
     private Multipart          g_multiPart=new MimeMultipart();     //"Container" for diffrent message parts
     
     //fields for addresses
     private String g_host                    ="smtp.XXX.com";     //mail server
     private String g_message               =null;     //the body message
     private String g_subject               =null;     //the body message
     private InternetAddress[] g_from     =null;     //from adress
     private InternetAddress[] g_to          =null;     //array for To adresses
     private InternetAddress[] g_cc         =null;     //array for CC adresses
     private InternetAddress[] g_bcc          =null;     //array for BCC adresses
     //delimeter between adresses
     private static String ADDRESS_DELIMETERS = " ,;";
     
     /** mail host server field identifier*/
     public static final int FIELD_HOST          =1000;
     /** from address field identifier */
     public static final int FIELD_FROM          =1001;
     /** TO address field identifier */
     public static final int FIELD_TO          =1002;
     /** CC address field identifier */
     public static final int FIELD_CC          =1003;
     /** BCC address field identifier */
     public static final int FIELD_BCC          =1004;
     /** MEssage field identifier */
     public static final int FIELD_MESSAGE     =1005;
     /** Subject field identifier */
     public static final int FIELD_SUBJECT     =1006;
     /** DELIMETER field identifier */
     public static final int FIELD_DELIMETER     =1007;

     
     //////////////////////////////////////////////////////////
     //                      ADDRESSES SECTION                         //
     //////////////////////////////////////////////////////////
     
     /**
      * Set field
     
      * @param p_fields          field in message
      * @param p_text          string which conatins values
      */
     public void setField(int p_fields , String p_text){
         
          try{
               switch(p_fields){
                   
                    case FIELD_HOST:
                         g_host = p_text;    
                         break;
                         
                    case FIELD_MESSAGE:
                         g_message = p_text;    
                         break;
                         
                    case FIELD_FROM:
                         g_from = convertToAddress(p_text);    
                         break;
                         
                    case FIELD_SUBJECT:
                         g_subject = p_text;
                         break;
                         
                    case FIELD_TO:
                         g_to = convertToAddress(p_text);
                         break;
                         
                    case FIELD_CC:
                         g_cc = convertToAddress(p_text);
                         break;
                         
                    case FIELD_BCC:
                         g_bcc = convertToAddress(p_text);
                         break;
                         
                    case FIELD_DELIMETER:
                         ADDRESS_DELIMETERS = p_text;
                         break;
                    }
               }catch(Exception e){
               System.out.println("Exception while trying to set field "+p_fields);
               }
          }
     
     /**
      * Get field by its identifier
      *
      * @param p_identifier      identifier of field which we need
      * @return                    field which we asked for
      */
     public InternetAddress[] getAddresses(int p_identifier){
         
          switch(p_identifier){
               
               case FIELD_TO:
                    return g_to;    
                   
               case FIELD_CC:
                    return g_cc;    
                   
               case FIELD_BCC:
                    return g_bcc;    
               }
          return null;
          }
     
     /**
      * Get field
      * @return          mail server host
      */
     public String getHost(){
          return g_host;    
          }
     
     /**
      * Get message
      * @return          the body message
      */
     public String getMessage(){
          return g_message;    
          }
     
     /**
      * Get Subject of message
      * @return          the body message
      */
     public String getSubject(){
          return g_subject;    
          }
     
     
     /**
      * Sets a new Delimeter between addresses
      * Default is ","
      *
      * @param p_del          new delimeter
      */
     public void setDelimeter(String p_del){
          ADDRESS_DELIMETERS = p_del;
          }
     
     /**
      * Convert string to InternetAddress[].
      * the function gets a string of addresses seperated by delimeter
      * and parse the addresses from it
      *
      * @param  p_string          string with new data
      * @return array
      */
     public InternetAddress[] convertToAddress(String p_string){
          StringTokenizer          l_strToken=null;
          InternetAddress[]     l_reply=null;
         
          l_strToken     =new StringTokenizer(p_string , ADDRESS_DELIMETERS , false);
          l_reply          =new InternetAddress[l_strToken.countTokens()];
         
          int ind=0;
          try{
               while(l_strToken.hasMoreElements())    
                    l_reply[ind++] = new InternetAddress(l_strToken.nextToken());
               
               return l_reply;
               }catch(Exception e){
               System.out.println("Exception while trying to generate adresses "+e);
               }
          return null;
          }
     
     
     //////////////////////////////////////////////////////////
     //                      ATTACHMENTS SECTION                         //
     //////////////////////////////////////////////////////////
     
     /**
      * add file attachment to the message
      *
      * @param p_fileName     file name to attach to message
      */
     public void addAttachment(String p_fileName){
         
          //create attachment
          MimeBodyPart     l_newPart=new MimeBodyPart();
          DataSource          l_source =new FileDataSource(p_fileName);
         
          try{
               l_newPart.setDataHandler(new DataHandler(l_source));
               l_newPart.setFileName(p_fileName);
               g_multiPart.addBodyPart(l_newPart);
               
               }catch(Exception e){
               System.out.println("Exception in: addAttachment");
               }
          }
     
     
     //////////////////////////////////////////////////////////
     /**
      * This function will send an e-mail message
      */
     public void sendMessage(){
          //do some check before mailing:
          if (g_host == null){
               System.out.println("Please set a mail server first");
               return;
               }
         
          if (g_to == null){
               System.out.println("Field 'TO' was not filled");
               return;
               }
         
          Properties     l_props = System.getProperties();
          Session          l_session;
          Message          l_message;
         
          try{
               //set Session & msg
               l_props.put("mail.smtp.host" , getHost() );
               l_session=Session.getDefaultInstance( l_props , null);              
               l_message = new MimeMessage(l_session);

               g_from=convertToAddress(FROM_FIELD);
               //add addresses fields to the message
               if (g_from != null)
                    l_message.addFrom(g_from);          
               
               if (g_to != null)
                    l_message.addRecipients(Message.RecipientType.TO  , g_to);
               
               if (g_cc != null)
                    l_message.addRecipients(Message.RecipientType.CC  , g_cc);

               if (g_bcc != null)
                    l_message.addRecipients(Message.RecipientType.BCC , g_bcc);
               
               if (g_message != null)
                    l_message.setText(g_message);
               
               if (g_subject != null)
                    l_message.setSubject(g_subject);
               
               //l_message.setContent( g_multiPart);
               l_message.setContent(g_message , "text/plain");
               Transport.send(l_message);
               
               }catch(Exception e){
               System.out.println("Exception in: sendMessage "+e);
               }
          }
     }

Nushi.
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:javaq092999
ID: 6476037
Ouch! Nushi! Do you think this program will work if the list of, say, TO addresses contains some email address that is not recognised by your email server. NO IT WONT! (It may work if you set your server such that all unknown email ids for that server goes to, say, root@server.com). See, if even a single email id fails the send() method do not send any emails (though we expect that at least the other valid addresses the email is sent). sendMessage do that as per documentation but not doing that for me and my requirement is just that.
0
 
LVL 1

Accepted Solution

by:
Moondancer earned 0 total points
ID: 6877701
ADMINISTRATION WILL BE CONTACTING YOU SHORTLY.  Moderators Computer101 or Netminder will return to finalize these if still open in seven days.  Please post closing recommendations before that time.

Question(s) below appears to have been abandoned. Your options are:
 
1. Accept a Comment As Answer (use the button next to the Expert's name).
2. Close the question if the information was not useful to you. You must tell the participants why you wish to do this, and allow for Expert response.
3. Ask Community Support to help split points between participating experts, or just comment here with details and we'll respond with the process.
4. Delete the question. Again, please comment to advise the other participants why you wish to do this.

For special handling needs, please post a zero point question in the link below and include the question QID/link(s) that it regards.
http://www.experts-exchange.com/jsp/qList.jsp?ta=commspt
 
Please click the Help Desk link on the left for Member Guidelines, Member Agreement and the Question/Answer process.  http://www.experts-exchange.com/jsp/cmtyHelpDesk.jsp

Please click you Member Profile to view your question history and keep them all current with updates as the collaboration effort continues, to track all your open and locked questions at this site.  If you are an EE Pro user, use the Power Search option to find them.  Anytime you have questions which are LOCKED with a Proposed Answer but does not serve your needs, please reject it and add comments as to why.  In addition, when you do grade the question, if the grade is less than an A, please add a comment as to why.  This helps all involved, as well as future persons who may access this item in the future to seek help.

To view your open questions, please click the following link(s) and keep them all current with updates.
http://www.experts-exchange.com/questions/Q.20023290.html
http://www.experts-exchange.com/questions/Q.20121869.html
http://www.experts-exchange.com/questions/Q.20126064.html
http://www.experts-exchange.com/questions/Q.20139990.html
http://www.experts-exchange.com/questions/Q.20143257.html
http://www.experts-exchange.com/questions/Q.20148988.html
http://www.experts-exchange.com/questions/Q.20150711.html
http://www.experts-exchange.com/questions/Q.20158263.html
http://www.experts-exchange.com/questions/Q.20163902.html
http://www.experts-exchange.com/questions/Q.20163903.html
http://www.experts-exchange.com/questions/Q.20181528.html
http://www.experts-exchange.com/questions/Q.20245208.html
http://www.experts-exchange.com/questions/Q.20245590.html
http://www.experts-exchange.com/questions/Q.20251382.html
http://www.experts-exchange.com/questions/Q.20253111.html


To view your locked questions, please click the following link(s) and evaluate the proposed answer.
http://www.experts-exchange.com/questions/Q.20143170.html
http://www.experts-exchange.com/questions/Q.20143993.html

PLEASE DO NOT AWARD THE POINTS TO ME.  
 
------------>  EXPERTS:  Please leave any comments regarding your closing recommendations if this item remains inactive another seven (7) days.  Also, if you are interested in the cleanup effort, please click this link http://www.experts-exchange.com/jsp/qManageQuestion.jsp?ta=commspt&qid=20274643

Moderators will finalize this question if still open in 7 days, by either moving this to the PAQ (Previously Asked Questions) at zero points, deleting it or awarding expert(s) when recommendations are made, or an independent determination can be made.  Expert input is always appreciated to determine the fair outcome.
 
Thank you everyone.
 
Moondancer
Moderator @ Experts Exchange

P.S.  For any year 2000 questions, special attention is needed to ensure the first correct response is awarded, since they are not in the comment date order, but rather in Member ID order.
0
 

Author Comment

by:javaq092999
ID: 6881881
Didn't find any suitable answer. Accepting moderator comment to close.
0
 
LVL 1

Expert Comment

by:Moondancer
ID: 6882872
I have refunded our 50 points to you for this question.  You may now wish to post a new question to draw current attention, if this need still exists.  This is a very high volumes topic area, and questions this old are rarely visited by experts, so a possible win/win scenario by reposting new.

Good luck,

Moondancer - EE Moderator
0
 
LVL 1

Expert Comment

by:Moondancer
ID: 6889875
Just so you are advised, javaq, many experts look at grading history before deciding if they'll step in to help.  You have many "C" grades in yours, and few of our experts (if any) are likely to want these either.
Moondancer - EE Moderator
0
 

Author Comment

by:javaq092999
ID: 6890570
Moondancer - EE Moderator

I will take care next time onwards. However as there was no suitable answer to my question and as I was supposed to close the question I accepted your comment as closing instrument. Selecting any of the comment as answer could have given even more confusing state to the other users. Anyway I understand your point and will take care of that.

I have a issue/suggestion! Few times I could know the answer to my question based on study etc. There should be some way so that the SUBMITTER of the question SHOULD be allowed to answer the question him/her-self.

Regards
javaq
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now