INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • 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!

*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

Jobs from Indeed

Sending Email to multiple TO

Sending Email to multiple TO

(OP)
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;
     }
  }

RE: Sending Email to multiple TO

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()]);
}

RE: Sending Email to multiple TO

(OP)
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

RE: Sending Email to multiple TO

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);
         

RE: Sending Email to multiple TO

(OP)
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
 


RE: Sending Email to multiple TO

(OP)
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;
     }
  }

 



  

RE: Sending Email to multiple TO

(OP)
Figured it out using JDBC. Thanks

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

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!

Resources

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