Example #1
0
        private void RecoverEnvelopeAttachments(IEnumerable <PECMailBox> boxes)
        {
            var boxName = string.Empty;

            try
            {
                foreach (var box in boxes)
                {
                    boxName = string.Format("{0} - {1}", box.Id, box.MailBoxName);

                    if (CancelRequest())
                    {
                        FileLogger.Info(Name, "Chiusura modulo invocata dall'utente.");
                        return;
                    }

                    FileLogger.Info(Name, "Recupero Envelope in corso...");
                    // Recupero l'elenco delle PEC da riprocessare
                    NHibernatePECMailFinder finder = new NHibernatePECMailFinder
                    {
                        Actives      = true,
                        MailDateFrom = !Parameters.RecoverEnvelopeAttachmentStartDate.Equals(default(DateTime)) ? (DateTime?)Parameters.RecoverEnvelopeAttachmentStartDate : null,
                        MailDateTo   = !Parameters.RecoverEnvelopeAttachmentEndDate.Equals(default(DateTime)) ? (DateTime?)Parameters.RecoverEnvelopeAttachmentEndDate : null,
                        MailboxIds   = new[] { box.Id },
                    };
                    List <PECMail> pecMails = finder.DoSearch().Where(pecMail =>
                                                                      pecMail.Direction != (short)DocSuiteWeb.Data.PECMailDirection.Outgoing &&
                                                                      pecMail.IDMailContent != Guid.Empty &&
                                                                      !pecMail.LogEntries.Any(pml => pml.Type.Eq(PECMailLogType.Reprocessed.ToString()))).
                                              Take(box.Configuration.MaxReadForSession).ToList();
                    FileLogger.Info(Name, string.Format("Trovate {0} pec da riprocessare", pecMails.Count));
                    foreach (PECMail pecMail in pecMails)
                    {
                        PECMail currentPecMail = pecMail;
                        // Recupero la PEC dal server di conservazione
                        BiblosDocumentInfo originalEml = FacadeFactory.Instance.PECMailFacade.GetPecMailContent(currentPecMail);
                        if (originalEml == null)
                        {
                            continue;
                        }
                        BiblosDocumentInfo originalEnvelope = new BiblosDocumentInfo(currentPecMail.Location.DocumentServer, currentPecMail.IDEnvelope);

                        FileLogger.Info(Name, string.Format("Estrazione eml originale GUID_Chain_EML {0} PEC [{1}] da riprocessare - EML name [{2}]", currentPecMail.IDMailContent, currentPecMail.Id, originalEml.Name));
                        try
                        {
                            Guid  originalEnvelopeId = currentPecMail.IDEnvelope;
                            IMail envelope           = new MailBuilder().CreateFromEml(originalEml.Stream);
                            FileLogger.Debug(Name, "Generata busta da EML");
                            envelope.RemoveAttachments();
                            FileLogger.Debug(Name, "Rimossi allegati con successo, archiviazione in corso...");
                            MailStoreFacade.Factory.PECMailFacade.ArchiveEnvelope(ref currentPecMail,
                                                                                  envelope.Render(), originalEnvelope.Name);
                            MailStoreFacade.Factory.PECMailFacade.UpdateNoLastChange(ref currentPecMail);
                            FileLogger.Info(Name,
                                            string.Format(
                                                "Aggiornamento Envelope avvenuto correttamente: nuovo GUID_Chain [{0}]",
                                                currentPecMail.IDEnvelope));
                            MailStoreFacade.Factory.PECMailLogFacade.InsertLog(ref currentPecMail, string.Format("Ricalcolata busta: guidPrecedente [{0}] -> guidRicalcolato [{1}]", originalEnvelopeId, currentPecMail.IDEnvelope), PECMailLogType.Reprocessed);
                        }
                        catch (Exception ex)
                        {
                            FileLogger.Error(Name, "Errore in fase di ricalcolo busta.", ex);
                            SendMessage(
                                string.Format("Errore in fase di ricalcolo busta per la PEC {1} - Guid: [{2}].{0}Stacktrace: {3}", Environment.NewLine, pecMail.Id, pecMail.IDEnvelope, FullStacktrace(ex)));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                FileLogger.Error(Name, string.Format("Errore in [RecoverEnvelopeAttachments] - Casella [{0}].", boxName), ex);
                SendMessage(string.Format("Errore in [RecoverEnvelopeAttachments] - Casella [{0}]. \nErrore: {1} \nStacktrace: {2}", boxName, ex.Message, FullStacktrace(ex)));
            }
            finally
            {
                // Libero le risorse
                NHibernateManager.NHibernateSessionManager.Instance.CloseTransactionAndSessions();
                GC.Collect(GC.MaxGeneration);
            }
        }
Example #2
0
        private string Execute(XElement root, string tempDir, string filename, ref int id, ref int idparent)
        {
            int    nextIdParent = -1;
            string nextFile     = String.Empty;

            IMail mail = new MailBuilder().CreateFromEmlFile(filename);

            // utilizzo NonVisuals per evitare di scaricare anche le immagini comprese nell'Html
            // cfr. http://www.limilabs.com/blog/download-email-attachments-net

            //TODO: BUGS mail.NonVisuals elimina anche il postacert eml
            //      e quindi la gestione dello sbusta del contenuto.
            foreach (MimeData mime in mail.Attachments)
            {
                if (mime.HasContentType &&
                    (mime.ContentType == Limilabs.Mail.Headers.ContentType.ImageBmp ||
                     mime.ContentType == Limilabs.Mail.Headers.ContentType.ImageGif ||
                     mime.ContentType == Limilabs.Mail.Headers.ContentType.ImageJpeg ||
                     mime.ContentType == Limilabs.Mail.Headers.ContentType.ImagePng ||
                     mime.ContentType == Limilabs.Mail.Headers.ContentType.ImageTiff))
                {
                    if (mail.Visuals != null && mail.Visuals.Any(mv => HashSHA512(mv.Data).Equals(HashSHA512(mime.Data))))
                    {
                        continue;
                    }
                }
                string   outpath = Utils.CreateTempName(tempDir, mime.SafeFileName, _biblosMaxLength).Trim();
                XElement child   = new XElement("file", outpath);

                //parent
                XAttribute childParent = new XAttribute("idParent", idparent.ToString(CultureInfo.InvariantCulture));
                child.Add(childParent);

                if (EmlExtensions.Contains(Path.GetExtension(outpath).ToLower()))
                {
                    nextFile     = outpath;
                    nextIdParent = id;
                }

                //id
                XAttribute childId = new XAttribute("id", id++.ToString(CultureInfo.InvariantCulture));
                child.Add(childId);

                //sourcename
                XAttribute childSource = new XAttribute("sourceName", Utils.SafeFileName(mime.SafeFileName, _biblosMaxLength));
                child.Add(childSource);

                //mimetype
                XAttribute childMime = new XAttribute("mimeType", mime.ContentType.MimeType.Name);
                child.Add(childMime);

                //mimetype
                XAttribute childSubMime = new XAttribute("mimeSubtype", mime.ContentType.MimeSubtype.Name);
                child.Add(childSubMime);

                root.Add(child);
                mime.Save(outpath);

                //gestione dello zip
                if (CompressExtensions.Contains(Path.GetExtension(outpath).ToLower()))
                {
                    try
                    {
                        ProcessCompressAttachment(root, tempDir, outpath, id - 1, ref id);
                    }
                    catch (Exception ex)
                    {
                        //gestione errore di file compresso che non riesce ad elaborare
                        //non lo elabora e prosegue
                        Console.WriteLine(ex.Message);
                    }
                }
            }

            //salva la mail escluso gli allegati (body)
            var bodyPath = Utils.CreateTempName(tempDir, "body.eml", _biblosMaxLength);

            mail.RemoveAttachments(new AttachmentRemoverConfiguration
            {
                RemoveAlternatives = false,
                RemoveVisuals      = false
            });

            File.WriteAllBytes(bodyPath, mail.Render());

            XElement body = new XElement("file", bodyPath);

            XAttribute bodyParent = new XAttribute("idParent", idparent.ToString(CultureInfo.InvariantCulture));

            body.Add(bodyParent);

            XAttribute bodyId = new XAttribute("id", id++.ToString(CultureInfo.InvariantCulture));

            body.Add(bodyId);

            XAttribute isBody = new XAttribute("isBody", true);

            body.Add(isBody);

            XAttribute bodyName = new XAttribute("sourceName", "busta.eml");

            body.Add(bodyName);

            root.Add(body);

            idparent = nextIdParent;
            return(nextFile);
        }