?
Solved

Java Mail Attachment

Posted on 2006-05-08
9
Medium Priority
?
269 Views
Last Modified: 2013-11-24
hi experts,

I'v this code works fine now I need to modify this in order to make attachment file work:

ublic class JavaMail {          
      
      public String sendMail(java.lang.String  from, java.lang.String to)
                    throws IOException, ServletException, AddressException, SendFailedException, MessagingException, NamingException
                    {                
          try {
                String textmessage = "some msg....";
                        
                InitialContext  ctx = new InitialContext();
                   Session mailSession = (Session)  ctx.lookup("java:comp/env/mail/xz");
                  Message message = new MimeMessage(mailSession);
                  
                  //Set  the from address
                   InternetAddress[] fromAddress = InternetAddress.parse(from);
                   message.addFrom(fromAddress);

                //Set  the to address                   
                   InternetAddress[] toAddress = InternetAddress.parse(to);
                   message.setRecipients(Message.RecipientType.TO,toAddress);

                  //Set  the subject and text
                    message.setSubject(subject);
                    message.setText(textmessage);

                        //send mail
                     Transport.send(message);      
                }           
      
       catch(AddressException  e) {
             status = "Address Exception: "+e;
            System.out.println(status);
      } catch(SendFailedException  e) {
            status = "Send Failed Exception: "+e;
            System.out.println(status);
      } catch  (MessagingException e) {
            status = "MessagingException: "+e;
            System.out.println(status);
      } catch  (NamingException e) {
            status = "Naming Exception: "+e;
            System.out.println(status);
      } catch  (Exception e) {
            status = "General Exception: "+e;
            System.out.println(status);            
      }      
      return status;

                    } // END sendMail
}

and the way I'm calling above class in another class:
..
 JavaMail rm = new JavaMail();
 jm.sendMail(FromEmailAddress, ToEmailAddress);
..

Please let me what changes do I need to go for
thx,
PH
0
Comment
Question by:princehyderabad
  • 4
  • 4
9 Comments
 
LVL 13

Expert Comment

by:kawas
ID: 16636066
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class AttachExample {
  public static void main (String args[])
      throws Exception {
    String host = args[0];
    String from = args[1];
    String to = args[2];
    String fileAttachment = args[3];

    // Get system properties
    Properties props = System.getProperties();

    // Setup mail server
    props.put("mail.smtp.host", host);

    // Get session
    Session session =
      Session.getInstance(props, null);

    // Define message
    MimeMessage message =
      new MimeMessage(session);
    message.setFrom(
      new InternetAddress(from));
    message.addRecipient(
      Message.RecipientType.TO,
      new InternetAddress(to));
    message.setSubject(
      "Hello JavaMail Attachment");

    // create the message part
    MimeBodyPart messageBodyPart =
      new MimeBodyPart();

    //fill message
    messageBodyPart.setText("Hi");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    // Part two is attachment
    messageBodyPart = new MimeBodyPart();
    DataSource source =
      new FileDataSource(fileAttachment);
    messageBodyPart.setDataHandler(
      new DataHandler(source));
    messageBodyPart.setFileName(fileAttachment);
    multipart.addBodyPart(messageBodyPart);

    // Put parts in message
    message.setContent(multipart);

    // Send the message
    Transport.send( message );
  }
}
0
 

Author Comment

by:princehyderabad
ID: 16641160
hi kawas

You just copied from :http://www.jguru.com/faq/view.jsp?EID=30251
I already knew this.

What I'm looking is how to modify my existing code so that attachment code can be added. And how to make call to my JavaMail class when attachment code is ready. See my 2nd half question the way I'm calling my javamail class without attchment code. Same way I want to know how to make call to Javamail class when attachment code is updated.

THX,
PH
0
 
LVL 13

Expert Comment

by:kawas
ID: 16641195
public class JavaMail {          
     
     public String sendMail(java.lang.String  from, java.lang.String to)
                 throws IOException, ServletException, AddressException, SendFailedException, MessagingException, NamingException
                 {              
         try {
              String textmessage = "some msg....";
                     
              InitialContext  ctx = new InitialContext();
                Session mailSession = (Session)  ctx.lookup("java:comp/env/mail/xz");
               Message message = new MimeMessage(mailSession);
               
               //Set  the from address
                InternetAddress[] fromAddress = InternetAddress.parse(from);
                message.addFrom(fromAddress);

              //Set  the to address                
                InternetAddress[] toAddress = InternetAddress.parse(to);
                message.setRecipients(Message.RecipientType.TO,toAddress);

               //Set  the subject and text
                 message.setSubject(subject);
                 message.setText(textmessage);


    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    // attachment
    messageBodyPart = new MimeBodyPart();
    DataSource source =
      new FileDataSource(fileAttachment);
    messageBodyPart.setDataHandler(
      new DataHandler(source));
    messageBodyPart.setFileName(fileAttachment);
    multipart.addBodyPart(messageBodyPart);

    // Put parts in message
    message.setContent(multipart);

                   //send mail
                  Transport.send(message);    
              }          
     
      catch(AddressException  e) {
           status = "Address Exception: "+e;
          System.out.println(status);
     } catch(SendFailedException  e) {
          status = "Send Failed Exception: "+e;
          System.out.println(status);
     } catch  (MessagingException e) {
          status = "MessagingException: "+e;
          System.out.println(status);
     } catch  (NamingException e) {
          status = "Naming Exception: "+e;
          System.out.println(status);
     } catch  (Exception e) {
          status = "General Exception: "+e;
          System.out.println(status);          
     }    
     return status;

                 } // END sendMail
}

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!

 

Author Comment

by:princehyderabad
ID: 16641557
thanks kawas, I think I'm asking basci stuff.

By the way can U also tell me how to call this javamail. My previous code is called in this way:

JavaMail rm = new JavaMail();
 jm.sendMail(FromEmailAddress, ToEmailAddress);

Now that attachment is also need to pass here, how can i make work.
0
 

Author Comment

by:princehyderabad
ID: 16641569
Atleast for testing that code let me know how to attached file
0
 
LVL 13

Accepted Solution

by:
kawas earned 1000 total points
ID: 16641610
public class JavaMail {          
     
     public String sendMail(java.lang.String  from, java.lang.String to, java.io.File file)
                 throws IOException, ServletException, AddressException, SendFailedException, MessagingException, NamingException
                 {              
         try {
              String textmessage = "some msg....";
                     
              InitialContext  ctx = new InitialContext();
                Session mailSession = (Session)  ctx.lookup("java:comp/env/mail/xz");
               Message message = new MimeMessage(mailSession);
               
               //Set  the from address
                InternetAddress[] fromAddress = InternetAddress.parse(from);
                message.addFrom(fromAddress);

              //Set  the to address                
                InternetAddress[] toAddress = InternetAddress.parse(to);
                message.setRecipients(Message.RecipientType.TO,toAddress);

               //Set  the subject and text
                 message.setSubject(subject);
                 message.setText(textmessage);


    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    // attachment
    messageBodyPart = new MimeBodyPart();
    DataSource source =
      new FileDataSource(file);
    messageBodyPart.setDataHandler(
      new DataHandler(source));
    messageBodyPart.setFileName(file.getName());
    multipart.addBodyPart(messageBodyPart);

    // Put parts in message
    message.setContent(multipart);

                   //send mail
                  Transport.send(message);    
              }          
     
      catch(AddressException  e) {
           status = "Address Exception: "+e;
          System.out.println(status);
     } catch(SendFailedException  e) {
          status = "Send Failed Exception: "+e;
          System.out.println(status);
     } catch  (MessagingException e) {
          status = "MessagingException: "+e;
          System.out.println(status);
     } catch  (NamingException e) {
          status = "Naming Exception: "+e;
          System.out.println(status);
     } catch  (Exception e) {
          status = "General Exception: "+e;
          System.out.println(status);          
     }    
     return status;

                 } // END sendMail
}
0
 

Author Comment

by:princehyderabad
ID: 16642168
so bascially this is the way I should call my javamail class from other jsp or class as:

JavaMail rm = new JavaMail();
 jm.sendMail(FromEmailAddress, ToEmailAddress, fileAttachment);
0
 
LVL 13

Expert Comment

by:kawas
ID: 16642187
yep, i forgot to say that. sorry
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16645030
You can also make it a static method, like a utility:

public static void sendMail ( .... )
{
}

And call it using:

JavaMail.sendMail ( .... ) ;
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

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…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses
Course of the Month15 days, 11 hours left to enroll

850 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