Results 1 to 3 of 3
  1. #1
    Basit56 is offline Member
    Join Date
    Aug 2009
    Posts
    48
    Rep Power
    0

    Question How i connect my java code to linux sendmail server

    Hi,
    Hope you all will be fine. I wrote a java code that connect to gmail using POP3s and read emails. Now i want that i use this code for linux sendmail server means whenever linux sendmail server which is on IP xxx.x.xxx.xxx encounter an email it runs my java code.Currently i have tested on windows. But now i will put this code on linux and then run it to achieve what i am telling to you(actually using local host try to connect to sendmail server) . Now i am using this code for connection to gmail on windows on netbeans.

    Java Code:
     public void connectEmailClient() {
    
            //Create empty properties
            Properties props = new Properties();
             //props.put("mail.smtp.port", port);
    
            //Get Session
            Session session = Session.getDefaultInstance(props, null);
    
            try{
                //Get the store
                Store store = session.getStore("pop3s");
                System.out.println("Trying to connect host");
    
                store.connect(getHost(), getUsername(), getPassword());
                System.out.println("Connection Successful");
    
                //Get Folder
                Folder folder = store.getFolder("Inbox");
    
                folder.open(Folder.READ_WRITE);
    
                 //Get directory
                Message[] message = folder.getMessages();
    ................................
    Actually here i connect to a particular account. Host is pop.gmail.com and user is of gmail account holder.
    But what i want that is, whenever sendmail receive any email its run my code. for this i think i have to do two things.

    1.Tell linux sendmail(email server) that whenever you encounter an email run this code.
    (I know this part is not belongs to this forum but if some one knows that how can i do it then please let me know.)

    2. When sendmail run my code then where i made connection to gmail i suppose it to change to connect to sendmail. so how can i modify my code to achieve this means instead of make connection to gmail i make connection with linux sendmail.

    Thank you.
    Last edited by Basit56; 01-13-2010 at 12:10 PM.

  2. #2
    nyk976 is offline Member
    Join Date
    Jan 2010
    Posts
    5
    Rep Power
    0

    Default

    hey buddy can u help me to do the same in windows i.e. connect to gmail then check inbox get the text body of email and to run my code on my windows machine...

  3. #3
    Basit56 is offline Member
    Join Date
    Aug 2009
    Posts
    48
    Rep Power
    0

    Default

    Hi :),
    Sure why not.Here is the code, it's also contains comments, so it will easy for you to understand the code. More if you do a little Google you can find a lot of examples regarding what you want :). I have checked this code on netbeans but you have to include mail.jar in netbeans library.

    This my first attempt to do the things:). Simply make a main file and instantiate the Retreive attachment with the arguments.

    Java Code:
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Date;
    import java.util.Properties;
    import javax.mail.*;
    import javax.mail.internet.InternetAddress;
    
    public class RetreiveAttachment {
    
        private String host;
        private String username;
        private String password;
        private String mailFrom;
        private String mailTo;
        private Date sentDate;
    
        public RetreiveAttachment(String host, String username, String password){
            this.host = host;
            this.username = username;
            this.password = password;
            System.out.println("In RetAttach");
        }
    
        public void setSentDate(Date sentdate){
            this.sentDate = sentdate;
        }
    
        public void setMailFrom(String mailfrom){
            this.mailFrom = mailfrom;
    
        }
    
        public void setMailTo(String mailto){
            this.mailTo = mailto;
        }
    
        public String getHost(){
            return host;
        }
    
        public String getUsername(){
            return username;
        }
    
        public String getPassword(){
            return password;
        }
    
        public String getMailFrom(){
            return mailFrom;
        }
    
        public String getMailTo(){
            return mailTo;
        }
    
        public Date getSentDate(){
            return sentDate;
        }
    
        public void connectEmailClient() {
    
            //String host = "pop.gmail.com";
            //String username = "basit.mahmood56@gmail.com";
            //String password = "";
            //String port = "465";
    
            //Scanner scanner = new Scanner(System.in);
    
            //Create empty properties
            Properties props = new Properties();
             //props.put("mail.smtp.port", port);
    
            //Get Session
            Session session = Session.getDefaultInstance(props, null);
    
            try{
                //Get the store
                Store store = session.getStore("pop3s");
                System.out.println("Trying to connect host");
    
                store.connect(getHost(), getUsername(), getPassword());
                System.out.println("Connection Successful");
    
                //Get Folder
                Folder folder = store.getFolder("Inbox");
    
                folder.open(Folder.READ_ONLY);
    
                 //Get directory
                Message[] message = folder.getMessages();
    
               
                for(int i=0, n=message.length; i<n; i++){
                    setMailFrom(InternetAddress.toString(message[i].getFrom()));
                    setMailTo(InternetAddress.toString(message[i].getRecipients(Message.RecipientType.TO)));
                    setSentDate(message[i].getSentDate());
    
                    System.out.println("From: " + getMailFrom());
                    System.out.println("To: " + getMailTo());
                    System.out.println("SendDate: " + getSentDate());
                    // System.out.println("Hi i am here");
                    //System.out.println("Do you want to read message? [YES to read/QUIT" +
                            //" to end]");
                    //String line = scanner.next();
                   // if("YES".equalsIgnoreCase(line)){
                          // System.out.println(i + ": " + message[i].getFrom()[0] + "\t" +
                                   //message[i].getSubject() + "\t" +
                                 // message[i].getRecipients(Message.RecipientType.TO)[0] +
                                    //"getAllrecipent method start" + message[i].getAllRecipients()[0]);
    
                       /**
                        * Forwarding messages is a little more involved. There is no single
                        * method to call and you build up the message to forward by
                        * working with the parts that make up a message.
                        * A mail message can be made up of multiple parts. Each part is
                        * a BodyPart, or more specifically, a MimeBodyPart when working
                        * with MIME messages. The different body parts get combined
                        * into a container called Multipart or, again, more specifically
                        * a MimeMultipart. To forward a message, you create one part for
                        * the text of your message and a second part with the message
                        * to forward, and combine the two into a multipart. Then you
                        * add the multipart to a properly addressed message and send it.
                        * That's essentially it. To copy the content from one message to
                        * another, just copy over its DataHandler, a class from the
                        * JavaBeans Activation Framework.
                        *
                        * // Create the message to forward
                          Message forward = new MimeMessage(session);
    
                            // Fill in header
                            forward.setSubject("Fwd: " + message.getSubject());
                            forward.setFrom(new InternetAddress(from));
                            forward.addRecipient(Message.RecipientType.TO,
                            new InternetAddress(to));
    
                            // Create your new message part
                            BodyPart messageBodyPart = new MimeBodyPart();
                            messageBodyPart.setText("Here you go with the original +
                                message:\n\n");
    
                            // Create a multi-part to combine the parts
                            Multipart multipart = new MimeMultipart();
                            multipart.addBodyPart(messageBodyPart);
    
                            // Create and fill part for the forwarded content
                            messageBodyPart = new MimeBodyPart();
                            messageBodyPart.setDataHandler(message.getDataHandler());
    
                            // Add part to multi part
                            multipart.addBodyPart(messageBodyPart);
    
                            // Associate multi-part with message
                            forward.setContent(multipart);
    
                            // Send message
                            Transport.send(forward);
    
                        *
                        *
                        * Working with Attachments:
                        * Attachments are resources associated with a mail message, 
                        * usually kept outside of the message like a text file,
                        * spreadsheet, or image. As with common mail programs like
                        * Eudora and pine, you can attach resources to your mail message
                        * with the JavaMail API and get those attachments when you
                        * receive the message
                        *
                        * Sending Attachments:
                        * Sending attachments is quite like forwarding messages. You
                        * build up the parts to make the complete message. After the
                        * first part, your message text, you add other parts where the
                        * DataHandler for each is your attachment, instead of the shared
                        * handler in the case of a forwarded message. If you are reading
                        * the attachment from a file, your attachment data source is a
                        * FileataSource.
                        *  Reading from a URL, it is a URLDataSource. Once you have your
                        * DataSource, just pass it on to the DataHandler constructor,
                        * before finally attaching it to the BodyPart with setDataHandler()
                        *  Assuming you want to retain the original filename for the
                        * attachment, the last thing to do is to set the filename
                        * associated with the attachment with the setFileName() method
                        * of BodyPart.
                        *
                        *  // Define message
                             Message 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
                             BodyPart messageBodyPart = new MimeBodyPart();
    
                             // Fill the message
                             messageBodyPart.setText("Pardon Ideas");
    
                             Multipart multipart = new MimeMultipart();
                             multipart.addBodyPart(messageBodyPart);
    
                             // Part two is attachment
                             messageBodyPart = new MimeBodyPart();
                             DataSource source = new FileDataSource(filename);
                             messageBodyPart.setDataHandler(new DataHandler(source));
                             messageBodyPart.setFileName(filename);
                             multipart.addBodyPart(messageBodyPart);
    
                             // Put parts in message
                             message.setContent(multipart);
    
                             // Send the message
                             Transport.send(message);
                        *
                        *
                        * Getting Attachments:
                        * Getting attachments out of your messages is a little more 
                        * involved then sending them, as MIME has no simple notion of
                        * attachments. The content of your message is a Multipart object
                        * when it has attachments. You then need to process each
                        * Part, to get the main content and the attachment(s). Parts
                        * marked with a disposition of Part.ATTACHMENT from
                        * part.getDisposition() are clearly  attachments. However,
                        * attachments can also come across with no disposition
                        * (and a non-text MIME type) or a disposition of Part.INLINE.
                        * When the disposition is either Part.ATTACHMENT or Part.INLINE,
                        * you can save * off the content for that message part. Just get
                        * the original filename with getFileName() and the input stream
                        * with getInputStream().
                        */
    
                           Object content = message[i].getContent();
                           if(content instanceof Multipart){
                              handleMultipart((Multipart)content);
                           }else{
                              handlePart(message[i]);
                           }
                    //}else if("QUIT".equalsIgnoreCase(line)){
                       // break;
                   //}
                    folder.close(false);
                    store.close();
                 }
            }catch(Exception e){
                e.printStackTrace();
            }
    
        } //Main
    
        public static void handleMultipart(Multipart multipart)throws MessagingException, IOException{
            for(int i=0, n=multipart.getCount(); i<n; i++){
                handlePart(multipart.getBodyPart(i));
            }
        }
    
        public static void handlePart(Part part)throws MessagingException, IOException{
            String disposition = part.getDisposition();
            String contentType = part.getContentType();
    
            if(disposition == null){
                System.out.println("Null: " + contentType);
                if((contentType.length() >= 10) && (contentType.toLowerCase().substring(0, 10).equals("text/plain"))){
                    part.writeTo(System.out);
                }else{
                    System.out.println("OtherBody: " + contentType);
                    part.writeTo(System.out);
                }
            } else if(disposition.equalsIgnoreCase(Part.ATTACHMENT)){
                System.out.println("Attachment in the mail is: " + part.getFileName() +
                        ": " + contentType );
                saveFile(part.getFileName(), part.getInputStream());
            } else if(disposition.equalsIgnoreCase(Part.INLINE)){
                System.out.println("Inline: " + part.getFileName() + " : " + contentType);
                //saveFile(part.getFileName(), part.getInputStream());
            } else{
                System.out.println("Other: " + disposition);
            }
        }
    
        public static void saveFile(String fileName, InputStream input)throws IOException{
           // if(fileName != null){
               // System.out.println("filename is: " + fileName);
                
                //File dir = new File("C://Temp");
                //fileName = File.createTempFile("msg0000", ".wav", dir).getName();
                //System.out.println("Created temporary file with name: " + fileName );
    
    
                //Define path for the file
                //String fileNamePath = "C://" + fileName;
                //String fileNamePath =  fileName;
                //System.out.println("Created temporary file with name: " + fileNamePath );
                
    
                //Create new file
                File file = new File("C://Temp/msg0000.wav");
    
                //for(int i=0; file.exists(); i++){
                    //file = new File(fileNamePath );
               //}
    
                FileOutputStream fos =  new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                //Copy the contents of the attachment to the newly created file
                BufferedInputStream bis = new BufferedInputStream(input);
    
                int aByte;
                while((aByte = bis.read()) != -1){
                    bos.write(aByte);
                }
    
                bos.flush();
                bos.close();
                bis.close();
            }
        }
    Hope this will help you.
    Cheers:)

Similar Threads

  1. Archiving File on Shared Folder in Linux using java code
    By ajmerasunny in forum Advanced Java
    Replies: 1
    Last Post: 10-30-2009, 07:15 AM
  2. Replies: 2
    Last Post: 04-06-2009, 05:52 PM
  3. Replies: 0
    Last Post: 08-25-2008, 02:13 PM
  4. connect to web server from mobile using java app.
    By jankrishnan in forum Advanced Java
    Replies: 1
    Last Post: 07-15-2008, 04:12 PM
  5. linux command to start a java web server
    By lazarus in forum JavaServer Faces (JSF)
    Replies: 0
    Last Post: 06-24-2008, 03:30 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •