Guest User

Untitled

a guest
Mar 14th, 2018
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 12.28 KB | None | 0 0
  1. /**
  2.   * Copyright (c) 2008 Steven M. Cherry
  3.   * All rights reserved.
  4.   */
  5. package utils.scheduled;
  6.  
  7. import java.io.BufferedOutputStream;
  8. import java.io.File;
  9. import java.io.FileOutputStream;
  10. import java.io.InputStream;
  11. import java.sql.Timestamp;
  12. import java.util.Properties;
  13. import java.util.Vector;
  14.  
  15. import javax.mail.Address;
  16. import javax.mail.Flags;
  17. import javax.mail.Folder;
  18. import javax.mail.Message;
  19. import javax.mail.Multipart;
  20. import javax.mail.Part;
  21. import javax.mail.Session;
  22. import javax.mail.Store;
  23. import javax.mail.internet.MimeBodyPart;
  24.  
  25. import glob.ActionLogicImplementation;
  26. import glob.IOConn;
  27. import glob.log.Log;
  28. import logic.utils.sql.Settings;
  29. import logic.utils.sqldo.EMail;
  30. import logic.utils.sqldo.EMailAttach;
  31.  
  32. /**
  33.   * This will connect to our incoming e-mail server and download any e-mails
  34.   * that are found on the server.  The e-mails will be stored for further processing
  35.   * in our internal database.  Attachments will be written out to separate files
  36.   * and then referred to by the database entries.  This is intended to be  run by
  37.   * the scheduler every minute or so.
  38.   *
  39.   * @author Steven M. Cherry
  40.   */
  41. public class DownloadEMail implements ActionLogicImplementation {
  42.  
  43.     protected String receiving_host;
  44.     protected String receiving_user;
  45.     protected String receiving_pass;
  46.     protected String receiving_protocol;
  47.     protected boolean receiving_secure;
  48.     protected String receiving_attachments;
  49.  
  50.     /** This will run our logic */
  51.     public void ExecuteRequest(IOConn ioc) throws Exception {
  52.         Log.Trace("Enter");
  53.  
  54.         Log.Debug("Executing DownloadEMail");
  55.         ioc.initializeResponseDocument("DownloadEMail");
  56.  
  57.         // pick up our configuration from the server:
  58.         receiving_host = Settings.getValue(ioc, "server.email.receiving.host");
  59.         receiving_user = Settings.getValue(ioc, "server.email.receiving.username");
  60.         receiving_pass = Settings.getValue(ioc, "server.email.receiving.password");
  61.         receiving_protocol = Settings.getValue(ioc, "server.email.receiving.protocol");
  62.         String tmp_secure = Settings.getValue(ioc, "server.email.receiving.secure");
  63.         receiving_attachments = Settings.getValue(ioc, "server.email.receiving.attachments");
  64.  
  65.         // sanity check on the parameters:
  66.         if(receiving_host == null || receiving_host.length() == 0){
  67.                 ioc.SendReturn();
  68.                 ioc.Close();
  69.                 Log.Trace("Exit");
  70.                 return; // no host defined.
  71.         }
  72.         if(receiving_user == null || receiving_user.length() == 0){
  73.                 ioc.SendReturn();
  74.                 ioc.Close();
  75.                 Log.Trace("Exit");
  76.                 return; // no user defined.
  77.         }
  78.         if(receiving_pass == null || receiving_pass.length() == 0){
  79.                 ioc.SendReturn();
  80.                 ioc.Close();
  81.                 Log.Trace("Exit");
  82.                 return; // no pass defined.
  83.         }
  84.         if(receiving_protocol == null || receiving_protocol.length() == 0){
  85.                 Log.Debug("EMail receiving protocol not defined, defaulting to POP");
  86.                 receiving_protocol = "POP";
  87.         }
  88.         if(tmp_secure == null ||
  89.                 tmp_secure.length() == 0 ||
  90.                 tmp_secure.compareToIgnoreCase("false") == 0 ||
  91.                 tmp_secure.compareToIgnoreCase("no") == 0
  92.         ){
  93.                 receiving_secure = false;
  94.         } else {
  95.                 receiving_secure = true;
  96.         }
  97.         if(receiving_attachments == null || receiving_attachments.length() == 0){
  98.                 Log.Debug("EMail receiving attachments not defined, defaulting to ./email/attachments/");
  99.                 receiving_attachments = "./email/attachments/";
  100.         }
  101.  
  102.         // now do the real work.
  103.         doEMailDownload(ioc);
  104.  
  105.         ioc.SendReturn();
  106.         ioc.Close();
  107.         Log.Trace("Exit");
  108.     }
  109.  
  110.     protected void doEMailDownload(IOConn ioc) throws Exception {
  111.         // Create empty properties
  112.         Properties props = new Properties();
  113.         // Get the session
  114.         Session session = Session.getInstance(props, null);
  115.  
  116.         // Get the store
  117.         Store store = session.getStore(receiving_protocol);
  118.         store.connect(receiving_host, receiving_user, receiving_pass);
  119.  
  120.         // Get folder
  121.         Folder folder = store.getFolder("INBOX");
  122.         folder.open(Folder.READ_WRITE);
  123.  
  124.         try {
  125.  
  126.                 // Get directory listing
  127.                 Message messages[] = folder.getMessages();
  128.  
  129.                 for (int i=0; i < messages.length; i++) {
  130.                         // get the details of the message:
  131.                         EMail email = new EMail();
  132.                         email.fromaddr = messages[i].getFrom()[0].toString();
  133.                         Address[] to = messages[i].getRecipients(Message.RecipientType.TO);
  134.                         email.toaddr = "";
  135.                         for(int j = 0; j < to.length; j++){
  136.                                 email.toaddr += to[j].toString() + "; ";
  137.                         }
  138.                         Address[] cc;
  139.                         try {
  140.                                 cc = messages[i].getRecipients(Message.RecipientType.CC);
  141.                         } catch (Exception e){
  142.                                 Log.Warn("Exception retrieving CC addrs: %s", e.getLocalizedMessage());
  143.                                 cc = null;
  144.                         }
  145.                         email.cc = "";
  146.                         if(cc != null){
  147.                                 for(int j = 0; j < cc.length; j++){
  148.                                         email.cc += cc[j].toString() + "; ";
  149.                                 }
  150.                         }
  151.                         email.subject = messages[i].getSubject();
  152.                         if(messages[i].getReceivedDate() != null){
  153.                                 email.received_when = new Timestamp(messages[i].getReceivedDate().getTime());
  154.                         } else {
  155.                                 email.received_when = new Timestamp( (new java.util.Date()).getTime());
  156.                         }
  157.  
  158.  
  159.                         email.body = "";
  160.                         Vector<EMailAttach> vema = new Vector<EMailAttach>();
  161.                         Object content = messages[i].getContent();
  162.                         if(content instanceof java.lang.String){
  163.                                 email.body = (String)content;
  164.                         } else if(content instanceof Multipart){
  165.                                 Multipart mp = (Multipart)content;
  166.  
  167.                                 for (int j=0; j < mp.getCount(); j++) {
  168.                                         Part part = mp.getBodyPart(j);
  169.  
  170.                                         String disposition = part.getDisposition();
  171.  
  172.                                         if (disposition == null) {
  173.                                                 // Check if plain
  174.                                                 MimeBodyPart mbp = (MimeBodyPart)part;
  175.                                                 if (mbp.isMimeType("text/plain")) {
  176.                                                         Log.Debug("Mime type is plain");
  177.                                                         email.body += (String)mbp.getContent();
  178.                                                 } else {
  179.                                                         Log.Debug("Mime type is not plain");
  180.                                                         // Special non-attachment cases here of
  181.                                                         // image/gif, text/html, ...
  182.                                                         EMailAttach ema = new EMailAttach();
  183.                                                         ema.name = decodeName(part.getFileName());
  184.                                                         File savedir = new File(receiving_attachments);
  185.                                                         savedir.mkdirs();
  186.                                                         File savefile = File.createTempFile("emailattach", ".atch", savedir );
  187.                                                         ema.path = savefile.getAbsolutePath();
  188.                                                         ema.size = part.getSize();
  189.                                                         vema.add(ema);
  190.                                                         ema.size = saveFile(savefile, part);
  191.                                                 }
  192.                                         } else if ((disposition != null) &&
  193.                                                 (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE) )
  194.                                         ){
  195.                                                 // Check if plain
  196.                                                 MimeBodyPart mbp = (MimeBodyPart)part;
  197.                                                 if (mbp.isMimeType("text/plain")) {
  198.                                                         Log.Debug("Mime type is plain");
  199.                                                         email.body += (String)mbp.getContent();
  200.                                                 } else {
  201.                                                         Log.Debug("Save file (%s)", part.getFileName() );
  202.                                                         EMailAttach ema = new EMailAttach();
  203.                                                         ema.name = decodeName(part.getFileName());
  204.                                                         File savedir = new File(receiving_attachments);
  205.                                                         savedir.mkdirs();
  206.                                                         File savefile = File.createTempFile("emailattach", ".atch", savedir );
  207.                                                         ema.path = savefile.getAbsolutePath();
  208.                                                         ema.size = part.getSize();
  209.                                                         vema.add(ema);
  210.                                                         ema.size = saveFile( savefile, part);
  211.                                                 }
  212.                                         }
  213.                                 }
  214.                         }
  215.  
  216.                         // Insert everything into the database:
  217.                         logic.utils.sql.EMail.insertEMail(ioc, email);
  218.                         for(int j = 0; j < vema.size(); j++){
  219.                                 vema.get(j).emailid = email.id;
  220.                                 logic.utils.sql.EMail.insertEMailAttach(ioc, vema.get(j) );
  221.                         }
  222.  
  223.                         // commit this message and all of it's attachments
  224.                         ioc.getDBConnection().commit();
  225.  
  226.                         // Finally delete the message from the server.
  227.                         messages[i].setFlag(Flags.Flag.DELETED, true);
  228.                 }
  229.  
  230.                 // Close connection
  231.                 folder.close(true); // true tells the mail server to expunge deleted messages.
  232.                 store.close();
  233.         } catch (Exception e){
  234.                 folder.close(true); // true tells the mail server to expunge deleted messages.
  235.                 store.close();
  236.                 throw e;
  237.         }
  238.  
  239.     }
  240.  
  241.     protected int saveFile(File saveFile, Part part) throws Exception {
  242.  
  243.         BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(saveFile) );
  244.  
  245.         byte[] buff = new byte[2048];
  246.         InputStream is = part.getInputStream();
  247.         int ret = 0, count = 0;
  248.         while( (ret = is.read(buff)) > 0 ){
  249.                 bos.write(buff, 0, ret);
  250.                 count += ret;
  251.         }
  252.         bos.close();
  253.         is.close();
  254.         return count;
  255.     }
  256.  
  257.     protected String decodeName( String name ) throws Exception {
  258.         if(name == null || name.length() == 0){
  259.                 return "unknown";
  260.         }
  261.         String ret = java.net.URLDecoder.decode( name, "UTF-8" );
  262.  
  263.         // also check for a few other things in the string:
  264.         ret = ret.replaceAll("=\\?utf-8\\?q\\?", "");
  265.         ret = ret.replaceAll("\\?=", "");
  266.         ret = ret.replaceAll("=20", " ");
  267.  
  268.         return ret;
  269.     }
  270.  
  271. }
Add Comment
Please, Sign In to add comment