[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

java mail to cc someone

Posted on 2006-04-18
11
Medium Priority
?
237 Views
Last Modified: 2013-11-24
Hi Experts,
I am using the following code to successfully send mail to one person but I want to be able to send to a few different people and also to CC someone.
What modifications do i need to make?

Regards,
Raftor.

**********************************************************************

package classfiles;

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


public class Mail
{
      String from = "";
      String to = "";
      String subject = "";
      String body = "";

        public Mail( String to, String from, String subject, String body)
        {

            this.to = to;
            this.from = from;
            this.subject = subject;
            this.body = body;
      }

        public void sendMail()
        {
            boolean successful = false;
            try
            {

                  Properties props = System.getProperties();
                  props.put("mail.smtp.host", "irmail2.gtk.gtech.com");
                  Session session = Session.getDefaultInstance(props, null);
                  MimeMessage message = new MimeMessage(session);
                  message.setFrom(new InternetAddress(from));
                  message.addRecipient(Message.RecipientType.TO,
                  new InternetAddress(to));
                  message.setSubject(subject);
                  message.setContent(body, "text/html");
                  Transport.send(message);
                  successful = true;
            }
            catch(Exception e)
            {
                   System.out.println("Mail " +e.toString());
                   successful = false;
            }

        }

      public String getServerName()
      {
       try
       {
              return InetAddress.getLocalHost().getHostAddress();
       }
        catch (Exception e) {return "unknown";}
    }

}
0
Comment
Question by:Raftor
  • 5
  • 3
9 Comments
 
LVL 30

Accepted Solution

by:
Mayank S earned 100 total points
ID: 16478748
>> message.addRecipient(Message.RecipientType.TO,
               new InternetAddress(to));

Add this after it:

message.addRecipient ( Message.RecipientType.CC, new InternetAddress ( cc ) ) ;

>> public Mail( String to, String from, String subject, String body)

Make that public Mail ( String to, String cc, String from, String subject, String body )

so that you pass a CC address to it.

0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16478771
>> I want to be able to send to a few different people

You might be better off by sending an array of TO and CC in that case, like:

public Mail ( String[] to, String[] cc, String from, String subject, String body )

Make your data-members:

>> String to = "";

as:

String[] to ;
String[] cc ;

Loop through the array while adding to-address:

for ( int i = 0 ; i < to.length ; i ++ )
  message.addRecipient ( Message.RecipientType.TO, new InternetAddress ( to[i] ) ) ;

Same way, do it for CC....
0
 
LVL 23

Assisted Solution

by:rama_krishna580
rama_krishna580 earned 100 total points
ID: 16479384
Hi,

   public boolean sendMail( Vector addressTo, String addressFrom, String msgSub,

                             String msgBody, String ehData )

    {

        if ( debug )

        {

            String logStr = "\n addressTo is " + addressTo ;

            logStr += "\n addressFrom is " + addressFrom;

            logStr += "\n ShallSend is " + shallSend;

            logStr += "\n debug is " + debug;

            log.debug( logStr );

            //return true;

        }

        if ( !shallSend )

        {

            log.debug(

                    "Mailer called. ShallSend value is false. Not sending email...." );

            return false;

        }

        if ( host == null )

        {

            log.debug( "Host is null.." );

            return false;

        }

        // create some properties and get the default Session

        Properties props = new Properties();

        props.put( "mail.smtp.host", host );

        Session session = Session.getDefaultInstance( props, null );

        session.setDebug( debug );

        try

        {

            // create a message

            String unixHostName = System.getProperty( "hostname" );
            String serverName = System.getProperty( "serverName" );

            if( msgBody != null && msgBody.trim().length() > 0 )

            {

                if( serverName != null && serverName.trim().length() > 0 )
                    msgBody = "ServerName : " + serverName + "\n\n" + msgBody;

                if( unixHostName != null && unixHostName.trim().length() > 0 )
                    msgBody = "  HostName : " + unixHostName + "\n\n" + msgBody;

            }

            else

            {

                msgBody = "";

                if( serverName != null && serverName.trim().length() > 0 )
                    msgBody = "ServerName : " + serverName + "\n\n" + msgBody;
               
                if( unixHostName != null && unixHostName.trim().length() > 0 )
                    msgBody = "  HostName : " + unixHostName + "\n\n" + msgBody;

            }

            MimeMessage msg = new MimeMessage( session );
            msg.setFrom( new InternetAddress( addressFrom ) );

            InternetAddress[] address = new InternetAddress[addressTo.size()];
            for ( int i = 0; i < addressTo.size(); i++ )
            {
                address[i] = new InternetAddress( ( String ) addressTo.elementAt( i ) );
            }

            msg.setRecipients( Message.RecipientType.TO, address );
            msg.setSubject( msgSub );
            msg.setSentDate( new Date() );

            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText( msgBody, "us-ascii" );

            // create the Multipart and its parts to it
            Multipart mp = new MimeMultipart();
            mp.addBodyPart( mbp1 );

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

            // send the message
            Transport.send( msg );
        }
        catch ( MessagingException mex )
        {
            log.debug( "Send mail failed ..." );

            mex.printStackTrace();

            Exception ex = null;

            if ( ( ex = mex.getNextException() ) != null )

            {

                ex.printStackTrace();

            }

            return false;

        }

        catch ( Throwable t )

        {

            log.debug( "Send mail failed ..." + t.toString() );

            return false;

        }

        return true;

    }


R.K
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 30

Expert Comment

by:Mayank S
ID: 16484513
Actually a Vector should not be used until synchronization is required. Prefer ArrayList or simply an array.
0
 

Author Comment

by:Raftor
ID: 16508052
I have hard coded my 'to' string to be something like this: person1@mail.com, person2@mail.com, person3@mail.com and it just does not send the mail. I have also tried this format :person1@mail.com;person2@mail.com;person3@mail.com and it does not send the mail.

This is similar to what mayankeagle is saying in your first comment is it not.
What am i doing wrong?
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16508275
No, you need to make it an array like I have shown, or a collection.
0
 

Author Comment

by:Raftor
ID: 16509543
ok, ill give that a go and ill get back to you...
0
 

Author Comment

by:Raftor
ID: 16515637
mayankeagle  in your second example will that look to the user like i sent him a mail and i cc'd it to a few others? that is what i want.

Regards,
Raftor.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16515830
Yes.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses
Course of the Month20 days, 1 hour left to enroll

872 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