Smart questions
Smart answers
Smart people
Join Tek-Tips Forums
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Member Login




Remember Me
Forgot Password?
Join Us!

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips now!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

Join Tek-Tips
*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.
Jobs from Indeed

Link To This Forum!

Partner Button
Add Stickiness To Your Site By Linking To This Professionally Managed Technical Forum.
Just copy and paste the
code below into your site.

crguy (Programmer) (OP)
25 Sep 03 18:56
Hi,

I have a Java class SendMail.java (code below).
I have a jsp page that send the required parameters to the Java class. (code below). Everything works as it should except when I try to send it to multiple people in the TO field. Can anybody direct me on how to fix this problem?

Thanks
crguy

=============================================
SendMail.jsp
=============================================
<%@ page contentType="text/html;charset=WINDOWS-1252"%>

<HTML>
  <HEAD>

  <TITLE>OC4J JSP Sample - Send Email</TITLE>
  </HEAD>
  <BODY background="../../images/Background.gif">
  <CENTER>
  <BR>
  <%--
    Prepare the inputs and call the bean method to send the
    mail using the API

  --%>
  <jsp:useBean id="sendMail" class="mypackage4.SendMail" scope="page" />
  <%
    String Sender    = request.getParameter("p_from");
    String Recipient      = request.getParameter("p_to");
    String cc      = request.getParameter("p_cc");
    String bcc     = request.getParameter("p_bcc");
    String subject = request.getParameter("p_subject");
    String Body = request.getParameter("p_message");
    String ErrorMessage = request.getParameter("p_ErrorMessage");
    String Attachments = request.getParameter("p_filename");
   
    sendMail.Send(Sender, Recipient, subject, Body, Attachments, ErrorMessage);
 
  %>
  
  <FONT SIZE=3 COLOR="blue">
  <A HREF="InputsForm.jsp">Compose Mail</A>
  </CENTER>
  </BODY>
</HTML>



=============================================
SendMail.java
=============================================
package mypackage4;

  import java.util.*;
  import java.io.*;
  import javax.mail.*;
  import javax.mail.internet.*;
  import javax.activation.*;
  
  public class SendMail {
     // Sender, Recipient, CCRecipient, and BccRecipient are comma-
     // separated lists of addresses;
     // Body can span multiple CR/LF-separated lines;
     // Attachments is a ///-separated list of file names;
     public static int Send(String Sender,
                            String Recipient,
                            String Subject,
                            String Body,
                            String Attachments,
                            String ErrorMessage) {

        // Error status;
        int ErrorStatus = 0;
        
        //Strings
        String SMTPServer = "host";
        
        

        // create some properties and get the default Session;
        Properties props = System.getProperties();
        props.put("mail.smtp.host", SMTPServer);
         Session session = Session.getDefaultInstance(props, null);

         try {
            // create a message;
            MimeMessage msg = new MimeMessage(session);

            // extracts the senders and adds them to the message;
            // Sender is a comma-separated list of e-mail addresses as
            // per RFC822;
            {
               InternetAddress[] TheAddresses =
                                        InternetAddress.parse(Sender);
               msg.addFrom(TheAddresses);
            }

          // extract the recipients and assign them to the message;
            // Recipient is a comma-separated list of e-mail addresses
            // as per RFC822;
            {
               InternetAddress[] TheAddresses =
                                     InternetAddress.parse(Recipient);
               msg.addRecipients(Message.RecipientType.TO,
                                 TheAddresses);
            }

           // subject field;
            msg.setSubject(Subject);

            // create the Multipart to be added the parts to;
            Multipart mp = new MimeMultipart();

            // create and fill the first message part;
            {
               MimeBodyPart mbp = new MimeBodyPart();
               mbp.setText(Body);

               // attach the part to the multipart;
               mp.addBodyPart(mbp);
            }

            // attach the files to the message;
            if (null != Attachments) {
               int StartIndex = 0, PosIndex = 0;
               while (-1 != (PosIndex = Attachments.indexOf("///",
                                                      StartIndex))) {
                  // create and fill other message parts;
                  MimeBodyPart mbp = new MimeBodyPart();
                  FileDataSource fds =
                  new FileDataSource(Attachments.substring(StartIndex,
                                                           PosIndex));
                  mbp.setDataHandler(new DataHandler(fds));
                  mbp.setFileName(fds.getName());
                  mp.addBodyPart(mbp);
                  PosIndex += 3;
                  StartIndex = PosIndex;
               }
               // last, or only, attachment file;
               if (StartIndex < Attachments.length()) {
                  MimeBodyPart mbp = new MimeBodyPart();
                  FileDataSource fds =
                new FileDataSource(Attachments.substring(StartIndex));
                  mbp.setDataHandler(new DataHandler(fds));
                  mbp.setFileName(fds.getName());
                  mp.addBodyPart(mbp);
               }
            }

            // add the Multipart to the message;
            msg.setContent(mp);

            // set the Date: header;
            msg.setSentDate(new Date());

            // send the message;
            Transport.send(msg);
         } catch (MessagingException MsgException) {
              ErrorMessage = MsgException.toString();
              Exception TheException = null;
              if ((TheException = MsgException.getNextException()) !=
                                                                 null)
                 ErrorMessage = ErrorMessage + "\n" +
                                   TheException.toString();
             ErrorStatus = 1;
         }
         return ErrorStatus;
     }
  }
hologram (Programmer)
26 Sep 03 2:03
Maybe you can do something with the following code snippets. If not I shall post the complete code.

...
private Vector to = null;
private Vector cc = null;
private Vector bcc = null;
...
  mimeMessage.addRecipients(Message.RecipientType.TO, this.getTo());
  mimeMessage.addRecipients(Message.RecipientType.CC, this.getCc());
  mimeMessage.addRecipients(Message.RecipientType.BCC, this.getBcc());
...

public MailAddress[] getTo() {
  return toMailAddress(this.to);
}
public MailAddress[] getCc() {
  return toMailAddress(this.cc);
}
public MailAddress[] getBcc() {
  return toMailAddress(this.bcc);
}

private MailAddress[] toMailAddress(Vector vector) {
  return (MailAddress[]) vector.toArray(new MailAddress[vector.size()]);
}
crguy (Programmer) (OP)
26 Sep 03 9:14
Hi hologram,

If I use Vectors, what do I put in my SendMail.jsp page?
I am confused all how it all ties in together. Any detailed example would be greatful.

crguy
hologram (Programmer)
28 Sep 03 5:03
Forget about the Vector, it is being converted to an array in

private MailAddress[] toMailAddress(Vector vector) {
  return (MailAddress[]) vector.toArray(new MailAddress[vector.size()]);
}

In our application we parse an XML file for the To, Cc and Bcc, ... fields and add to these to the vector (it's easier then using an array)
====================
Your code seems to be OK, and if it works for 1 TO-address, the problem could be in your Recipient field.
Are you sure your Recipient field "is a comma-separated list of e-mail addresses" ? Can you print it before you parse it ? Can you print "TheAddresses" after the parsing ?
            
InternetAddress[] TheAddresses = InternetAddress.parse(Recipient);
         
crguy (Programmer) (OP)
28 Sep 03 17:47
Hi hologram,

I get this error when I try to execute it:
javax.mail.internet.AddressException: Illegal address in string ``john.smith@aol.com,john.smith@aol.com'

I will paste the revised code for SendMail.java any code examples would be great. Thanks in advance.
==========================================
package JavaBean;


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

 
public class SendMail {
    
  public static Session getSession()
  {
    Session session = null;
    
    // Name of the Host Machine
    String smtpServer = "mailhost.mcgill.ca";
    
    // Get system properties
    Properties props = System.getProperties();
 
    // Setup mail server
    props.put("mail.smtp.host", smtpServer);
 
    // Get session
    session = Session.getDefaultInstance(props, null);
    
    return session;
  }

  public static void send (String from, String[] to, String subject, String filename) throws MessagingException
  {
    Message message = new MimeMessage(getSession());
    
    message.setFrom(new InternetAddress(from));
    
    InternetAddress[] sendTo = new InternetAddress[to.length];
    for (int i = 0; i<to.length; i++)
    {
      sendTo = new InternetAddress(to);
    }
    
    message.setSubject(subject);
 
    // Create the multi-part
    Multipart multipart = new MimeMultipart();
 
    // Create part one
    BodyPart messageBodyPart = new MimeBodyPart();
 
    // Fill the message
    messageBodyPart.setText("Here is the file");
 
    // Add the first part
    multipart.addBodyPart(messageBodyPart);
 
    //Part two is attachment
    messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(filename);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
 
    // Add the second part
    multipart.addBodyPart(messageBodyPart);
 
    // Put parts in message
    message.setContent(multipart);
 
    // Send message
    Transport.send(message);    
  }

} //end of bean
 


crguy (Programmer) (OP)
28 Sep 03 18:15
Hi hologram,

I am sorry I posted the wrong code above.

package JavaBean;


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

   
  public class SendMail {
     // Sender, Recipient, CCRecipient, and BccRecipient are comma-
     // separated lists of addresses;
     // Body can span multiple CR/LF-separated lines;
     // Attachments is a ///-separated list of file names;
     public static int Send(String from,
                            String to,
                            String Subject,
                            String Body,
                            String Attachments,
                            String ErrorMessage) {

        // Error status;
        int ErrorStatus = 0;
        
        //Strings
        String SMTPServer = "myhost.com";
        
        

        // create some properties and get the default Session;
        Properties props = System.getProperties();
        props.put("mail.smtp.host", SMTPServer);
         Session session = Session.getDefaultInstance(props, null);

         try {
            // create a message;
            MimeMessage msg = new MimeMessage(session);

            // extracts the senders and adds them to the message;
            // Sender is a comma-separated list of e-mail addresses as
            // per RFC822;
            {
               InternetAddress[] TheAddresses =
                                        InternetAddress.parse(from);
               msg.addFrom(TheAddresses);
            }

          // extract the recipients and assign them to the message;
            // Recipient is a comma-separated list of e-mail addresses
            // as per RFC822;
            {
               InternetAddress[] TheAddresses =
                                     InternetAddress.parse(to);
                                     
              msg.addRecipients(Message.RecipientType.TO,
                                 TheAddresses);
            }

           // subject field;
            msg.setSubject(Subject);

            // create the Multipart to be added the parts to;
            Multipart mp = new MimeMultipart();

            // create and fill the first message part;
            {
               MimeBodyPart mbp = new MimeBodyPart();
               mbp.setText(Body);

               // attach the part to the multipart;
               mp.addBodyPart(mbp);
            }

            // attach the files to the message;
            if (null != Attachments) {
               int StartIndex = 0, PosIndex = 0;
               while (-1 != (PosIndex = Attachments.indexOf("///",
                                                      StartIndex))) {
                  // create and fill other message parts;
                  MimeBodyPart mbp = new MimeBodyPart();
                  FileDataSource fds =
                  new FileDataSource(Attachments.substring(StartIndex,
                                                           PosIndex));
                  mbp.setDataHandler(new DataHandler(fds));
                  mbp.setFileName(fds.getName());
                  mp.addBodyPart(mbp);
                  PosIndex += 3;
                  StartIndex = PosIndex;
               }
               // last, or only, attachment file;
               if (StartIndex < Attachments.length()) {
                  MimeBodyPart mbp = new MimeBodyPart();
                  FileDataSource fds =
                new FileDataSource(Attachments.substring(StartIndex));
                  mbp.setDataHandler(new DataHandler(fds));
                  mbp.setFileName(fds.getName());
                  mp.addBodyPart(mbp);
               }
            }

            // add the Multipart to the message;
            msg.setContent(mp);

            // set the Date: header;
            msg.setSentDate(new Date());

            // send the message;
            Transport.send(msg);
         } catch (MessagingException MsgException) {
              ErrorMessage = MsgException.toString();
              Exception TheException = null;
              if ((TheException = MsgException.getNextException()) !=
                                                                 null)
                 ErrorMessage = ErrorMessage + "\n" +
                                   TheException.toString();
             ErrorStatus = 1;
         }
         return ErrorStatus;
     }
  }

 



  

crguy (Programmer) (OP)
30 Sep 03 19:25
Figured it out using JDBC. Thanks

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Back To Forum

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close