Esempio n. 1
0
        private static void UpdateFlusso(SendMail.Model.ComunicazioniMapping.Comunicazioni c)
        {
            ComunicazioniService s = new ComunicazioniService();

            try
            {
                s.UpdateFlussoComunicazione(CANALE_INVIO, c);
            }
            catch (Exception ex)
            {
                if (!ex.GetType().Equals(typeof(ManagedException)))
                {
                    ManagedException mEx = new ManagedException("Errore nell'aggiornamento della mail",
                                                                "SEN_001",
                                                                string.Empty,
                                                                string.Empty,
                                                                ex.InnerException);
                    mEx.addEnanchedInfosTag("REQUEST",
                                            new XElement("Mail", new XAttribute("IdMail", c.MailComunicazione.IdMail),
                                                         new XElement("Status", c.ComFlussi[CANALE_INVIO].Last().StatoComunicazioneNew.ToString())).ToString());
                    ErrorLogInfo err = new ErrorLogInfo(mEx);
                    err.objectID = (c.UniqueId != null) ? c.UniqueId : c.IdComunicazione.ToString();
                    _log.Error(err);
                }
            }
        }
Esempio n. 2
0
        public HttpResponseMessage Comunicazione(FormDataCollection formsValues)
        {
            string      regexMail = RegexUtils.EMAIL_REGEX.ToString();
            TitoliModel model     = new TitoliModel();

            try
            {
                List <ComAllegato> allegati = new List <ComAllegato>();
                SendMail.Model.ComunicazioniMapping.Comunicazioni comun = new SendMail.Model.ComunicazioniMapping.Comunicazioni();
                string destinatario = formsValues["Destinatario"];
                string conoscenza   = formsValues["Conoscenza"];
                string bcc          = formsValues["BCC"];
                string oggetto      = formsValues["Oggetto"];
                string testoMail    = formsValues["TestoMail"];
                string titolo       = formsValues["Titolo"];
                string sottotitolo  = formsValues["SottoTitolo"];
                string userid       = formsValues["SenderMail"];
                if (SessionManager <Dictionary <string, DTOFileUploadResult> > .exist(SessionKeys.DTO_FILE))
                {
                    Dictionary <string, DTOFileUploadResult> dictDto = SessionManager <Dictionary <string, DTOFileUploadResult> > .get(SessionKeys.DTO_FILE);

                    List <DTOFileUploadResult> dto = (List <DTOFileUploadResult>)dictDto.Values.ToList();
                    foreach (DTOFileUploadResult d in dto)
                    {
                        SendMail.Model.ComunicazioniMapping.ComAllegato allegato = new SendMail.Model.ComunicazioniMapping.ComAllegato();
                        allegato.AllegatoExt  = d.Extension;
                        allegato.AllegatoFile = d.CustomData;
                        allegato.AllegatoName = d.FileName;
                        allegato.AllegatoTpu  = "";
                        allegato.FlgInsProt   = AllegatoProtocolloStatus.FALSE;
                        allegato.FlgProtToUpl = AllegatoProtocolloStatus.FALSE;
                        allegati.Add(allegato);
                    }
                }
                comun.ComAllegati = allegati;
                string[] destinatari = destinatario.Split(';');
                for (int i = 0; i < destinatari.Length; i++)
                {
                    var match = Regex.Match(destinatari[i], regexMail, RegexOptions.IgnoreCase);
                    if (!match.Success)
                    {
                        model.success = "false";
                        model.message = "Attenzione mail destinatario non valida";
                        return(this.Request.CreateResponse <TitoliModel>(HttpStatusCode.OK, model));
                    }
                }
                // gestione destinatari
                ContactsApplicationMapping c = new ContactsApplicationMapping
                {
                    Mail          = destinatario,
                    IdSottotitolo = long.Parse(sottotitolo),
                    IdTitolo      = long.Parse(titolo)
                };
                Collection <ContactsApplicationMapping> en = new Collection <ContactsApplicationMapping>();
                en.Add(c);
                if (conoscenza != string.Empty)
                {
                    string[] conoscenze = conoscenza.Split(';');
                    for (int i = 0; i < conoscenze.Length; i++)
                    {
                        var match = Regex.Match(conoscenze[i], regexMail, RegexOptions.IgnoreCase);
                        if (!match.Success)
                        {
                            model.success = "false";
                            model.message = "Attenzione mail conoscenza non valida";
                            return(this.Request.CreateResponse <TitoliModel>(HttpStatusCode.OK, model));
                        }
                    }
                    ContactsApplicationMapping c1 = new ContactsApplicationMapping
                    {
                        Mail          = conoscenza,
                        IdSottotitolo = long.Parse(sottotitolo),
                        IdTitolo      = long.Parse(titolo)
                    };
                    Collection <ContactsApplicationMapping> en1 = new Collection <ContactsApplicationMapping>();
                    en1.Add(c1);
                    comun.SetMailDestinatari(en1, AddresseeType.CC);
                }
                if (bcc != string.Empty)
                {
                    string[] bccs = bcc.Split(';');
                    for (int i = 0; i < bcc.Length; i++)
                    {
                        var match = Regex.Match(bccs[i], regexMail, RegexOptions.IgnoreCase);
                        if (!match.Success)
                        {
                            model.success = "false";
                            model.message = "Attenzione mail destinatario nascosto non valido";
                            return(this.Request.CreateResponse <TitoliModel>(HttpStatusCode.OK, model));
                        }
                    }

                    ContactsApplicationMapping c2 = new ContactsApplicationMapping
                    {
                        Mail          = bcc,
                        IdSottotitolo = long.Parse(sottotitolo),
                        IdTitolo      = long.Parse(titolo)
                    };
                    Collection <ContactsApplicationMapping> en2 = new Collection <ContactsApplicationMapping>();
                    en2.Add(c2);
                    comun.SetMailDestinatari(en2, AddresseeType.CCN);
                }
                comun.SetMailDestinatari(en, AddresseeType.TO);
                // gestione body email
                MailContent content = new MailContent();
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                string html = testoMail;
                HtmlAgilityPack.HtmlNode body = null;
                if (string.IsNullOrEmpty(html) == false)
                {
                    doc.LoadHtml(html);
                    doc.OptionAutoCloseOnEnd = true;
                    doc.OptionFixNestedTags  = true;
                    body = doc.DocumentNode.Descendants()
                           .Where(n => n.Name.Equals("body", StringComparison.InvariantCultureIgnoreCase))
                           .FirstOrDefault();
                }
                var ele = new HtmlAgilityPack.HtmlNode(HtmlAgilityPack.HtmlNodeType.Element, doc, 0);
                ele.Name            = "div";
                ele.InnerHtml       = testoMail;
                content.MailSubject = oggetto;
                content.MailText    = ele.OuterHtml;
                // gestione sender
                MailServerConfigFacade mailSCF = MailServerConfigFacade.GetInstance();
                MailUser mailuser = mailSCF.GetUserByUserId(decimal.Parse(userid));
                content.MailSender      = mailuser.EmailAddress;
                c.IdTitolo              = long.Parse(titolo);
                c.IdSottotitolo         = long.Parse(sottotitolo);
                comun.UtenteInserimento = MySecurityProvider.CurrentPrincipal.MyIdentity.UserName;
                comun.MailComunicazione = content;
                // da scommentare
                comun.FolderTipo = "O";
                comun.FolderId   = 2;
                ComunicazioniService com = new ComunicazioniService();
                com.InsertComunicazione(comun);
                model.success = "true";
                SessionManager <Dictionary <string, DTOFileUploadResult> > .del(SessionKeys.DTO_FILE);
            }
            catch (Exception ex)
            {
                if (ex.GetType() != typeof(ManagedException))
                {
                    ManagedException mEx = new ManagedException("Errore invio nuova mail. Dettaglio: " + ex.Message +
                                                                "StackTrace: " + ((ex.StackTrace != null) ? ex.StackTrace.ToString() : " vuoto "),
                                                                "ERR317",
                                                                string.Empty,
                                                                string.Empty,
                                                                ex.InnerException);
                    ErrorLogInfo err = new ErrorLogInfo(mEx);
                    log.Error(err);
                    model.success = "false";
                    model.message = ex.Message;
                    return(this.Request.CreateResponse <TitoliModel>(HttpStatusCode.OK, model));
                }
            }
            return(this.Request.CreateResponse <TitoliModel>(HttpStatusCode.OK, model));
        }
Esempio n. 3
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                Message msg;
                ComunicazioniService comunicazioniService = new ComunicazioniService();
                if (MailMessageComposer.CurrentSendMailExist())
                {
                    msg = MailMessageComposer.CurrentSendMailGet();
                }
                else
                {
                    msg = new Message();
                }

                msg.Subject = SubjectTextBox.Text;
                if (String.IsNullOrEmpty(ToTextBox.Text.Trim()) &&
                    String.IsNullOrEmpty(CCTextBox.Text.Trim()) &&
                    String.IsNullOrEmpty(BCCTextBox.Text.Trim()))
                {
                    ErrorLabel.Text    = "Inserire almeno un destinatario";
                    ErrorLabel.Visible = true;
                    return;
                }
                msg.To.Clear();
                msg.Cc.Clear();
                msg.Bcc.Clear();
                this.addEmailsTo(ToTextBox.Text, msg);
                this.addEmailsCc(CCTextBox.Text, msg);
                this.addEmailCcn(BCCTextBox.Text, msg);
                msg.Date = System.DateTime.Now;
                //mantengo il vecchio testo perché in caso di ErrorEventArgs lo devo ripristinare
                bodyBag = msg.BodyHtml.Text;
                SendMail.Model.BodyChunk bb = new SendMail.Model.BodyChunk();
                string   txt = BodyTextBox.Text;
                string[] lst = txt.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                foreach (string l in lst)
                {
                    bb.Line.Add(l);
                }
                //inserisco il testo libero in testa a quello preformattato
                HtmlNode newNode = null;
                if (bb.Line.Count != 0)
                {
                    newNode = HtmlNode.CreateNode(bb.getAsHtml());
                }
                HtmlDocument d = new HtmlDocument();
                if (!String.IsNullOrEmpty(PreformattedBody.Text))
                {
                    d.LoadHtml(PreformattedBody.Text);
                }
                if (newNode != null)
                {
                    if (d.DocumentNode.Descendants().Count() != 0)
                    {
                        HtmlNode root = d.DocumentNode.Descendants().SingleOrDefault(x => x.Name.Equals("body", StringComparison.InvariantCultureIgnoreCase));
                        if (root == null)
                        {
                            root = d.DocumentNode.Descendants().FirstOrDefault(x => x.NodeType == HtmlNodeType.Element);
                        }
                        if (root != null)
                        {
                            root.PrependChild(newNode);
                        }
                        else
                        {
                            d.DocumentNode.PrependChild(newNode);
                        }
                    }
                    else
                    {
                        d.DocumentNode.PrependChild(newNode);
                    }
                }
                msg.BodyHtml.Text = d.DocumentNode.InnerHtml;
                //se non sono inclusi gli allegati originali
                if (MailEditabile == true && cbIncludiAllegati.Checked == false)
                {
                    for (int i = 0; i < msg.Attachments.Count; i++)
                    {
                        //rimuovo gli allegati originali
                        if (msg.Attachments[i].ParentMessage != null)
                        {
                            msg.Attachments.RemoveAt(i);
                        }
                    }
                }
                foreach (MimePart mm in msg.Attachments)
                {
                    if (mm.BinaryContent == null || mm.BinaryContent.Length < 10)
                    {
                        if (!String.IsNullOrEmpty(mm.ContentId))
                        {
                            string idAttach = mm.ContentId.Trim(new char[] { '<', '>' });
                            long   idAtt    = -1;
                            if (long.TryParse(idAttach, out idAtt))
                            {
                                ComAllegato all = comunicazioniService
                                                  .LoadAllegatoComunicazioneById(long.Parse(idAttach));
                                mm.BinaryContent = all.AllegatoFile;
                            }
                        }
                    }
                }
                switch (CurrentAction)
                {
                case MailActions.REPLY_TO:
                case MailActions.REPLY_ALL:
                case MailActions.RE_SEND:
                case MailActions.FORWARD:
                    msg.InReplyTo = msg.Id.ToString();
                    break;
                }

                ActiveUp.Net.Mail.DeltaExt.MailUser mailUser = null;
                if (WebMailClientManager.AccountExist())
                {
                    mailUser = WebMailClientManager.getAccount();
                }

                if (mailUser != null)
                {
                    MailServerFacade f = MailServerFacade.GetInstance(mailUser);

                    if (mailUser.IsManaged)
                    {
                        try
                        {
                            SendMail.Model.ComunicazioniMapping.Comunicazioni c =
                                new SendMail.Model.ComunicazioniMapping.Comunicazioni(
                                    SendMail.Model.TipoCanale.MAIL,
                                    this.SottoTitolo,
                                    msg,
                                    MySecurityProvider.CurrentPrincipal.MyIdentity.UserName, 2, "O");
                            if (c.MailComunicazione.MailRefs != null && c.MailComunicazione.MailRefs.Count != 0)
                            {
                                c.RubricaEntitaUsed = (from cont in c.MailComunicazione.MailRefs
                                                       select new SendMail.Model.ComunicazioniMapping.RubrEntitaUsed
                                {
                                    Mail = cont.MailDestinatario,
                                    TipoContatto = cont.TipoRef
                                }).ToList();
                            }

                            comunicazioniService.InsertComunicazione(c);
                        }
                        catch (Exception ex)
                        {
                            ManagedException mex = new ManagedException("Errore nel salvataggio della mail",
                                                                        "MAIL_CMP_002", "", ex.StackTrace, ex);
                            ErrorLog err = new ErrorLog(mex);
                            _log.Error(err);
                            ErrorLabel.Text    = "Errore nell'invio del messaggio";
                            ErrorLabel.Visible = true;
                            return;
                        }
                    }
                    else
                    {
                        f.sendMail(msg);
                    }

                    (this.Page as BasePage).info.AddInfo("Il messaggio e' stato spedito correttamente");
                    MailMessageComposer.CurrentSendMailClear();
                    onMailSent();
                }
                else
                {
                    ((BasePage)this.Page).info.AddInfo("Account inesistente.");
                }
            }
            catch (Exception ex)
            {
                if (ex.GetType() != typeof(ManagedException))
                {
                    _log.Error(new Com.Delta.Logging.Errors.ErrorLog(new ManagedException(ex.Message, "FAC_007", string.Empty, string.Empty, ex)));
                }
                //_log.Error(new Com.Delta.Logging.Errors.ErrorLog("FAC_007", ex, string.Empty, string.Empty, string.Empty));

                MailMessageComposer.CurrentSendMailGet().BodyHtml.Text = bodyBag;
                ErrorLabel.Visible = true;
                ErrorLabel.Text    = ex.Message;
                return;
            }
            Label5.Visible = true;
        }
Esempio n. 4
0
        public HttpResponseMessage SendMailExt(FormDataCollection collection)
        {
            MailModel model = new MailModel();
            string    bodyBag;

            try
            {
                Message msg;
                ComunicazioniService comunicazioniService = new ComunicazioniService();
                if (MailMessageComposer.CurrentSendMailExist())
                {
                    msg = MailMessageComposer.CurrentSendMailGet();
                }
                else
                {
                    msg = new Message();
                }

                msg.Subject = collection["Oggetto"];
                if (String.IsNullOrEmpty(collection["DestinatarioA"]) &&
                    String.IsNullOrEmpty(collection["DestinatarioCC"]) &&
                    String.IsNullOrEmpty(collection["DestinatarioBCC"]))
                {
                    model.message = "Inserire almeno un destinatario";
                    model.success = "false";
                    return(this.Request.CreateResponse <MailModel>(HttpStatusCode.OK, model));
                }
                msg.To.Clear();
                msg.Cc.Clear();
                msg.Bcc.Clear();
                this.addEmailsTo(collection["DestinatarioA"].Trim(), msg);
                if (!(string.IsNullOrEmpty(collection["DestinatarioCC"])))
                {
                    this.addEmailsCc(collection["DestinatarioCC"], msg);
                }
                if (!(string.IsNullOrEmpty(collection["DestinatarioBCC"])))
                {
                    this.addEmailCcn(collection["DestinatarioBCC"], msg);
                }
                msg.Date = System.DateTime.Now;
                //mantengo il vecchio testo perché in caso di ErrorEventArgs lo devo ripristinare
                bodyBag = msg.BodyHtml.Text;
                SendMail.Model.BodyChunk bb = new SendMail.Model.BodyChunk();
                string   txt = collection["TestoMail"];
                string[] lst = txt.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                foreach (string l in lst)
                {
                    bb.Line.Add(l);
                }
                //inserisco il testo libero in testa a quello preformattato
                HtmlNode newNode = null;
                if (bb.Line.Count != 0)
                {
                    newNode = HtmlNode.CreateNode(bb.getAsHtml());
                }
                HtmlDocument d = new HtmlDocument();
                if (newNode != null)
                {
                    if (d.DocumentNode.Descendants().Count() != 0)
                    {
                        HtmlNode root = d.DocumentNode.Descendants().SingleOrDefault(x => x.Name.Equals("body", StringComparison.InvariantCultureIgnoreCase));
                        if (root == null)
                        {
                            root = d.DocumentNode.Descendants().FirstOrDefault(x => x.NodeType == HtmlNodeType.Element);
                        }
                        if (root != null)
                        {
                            root.PrependChild(newNode);
                        }
                        else
                        {
                            d.DocumentNode.PrependChild(newNode);
                        }
                    }
                    else
                    {
                        d.DocumentNode.PrependChild(newNode);
                    }
                }
                msg.BodyHtml.Text = d.DocumentNode.InnerHtml;
                //se non sono inclusi gli allegati originali
                if (!(string.IsNullOrEmpty(collection["IncludiAllegati"])) && collection["IncludiAllegati"].ToUpper() == "FALSE")
                {
                    for (int i = 0; i < msg.Attachments.Count; i++)
                    {
                        //rimuovo gli allegati originali
                        if (msg.Attachments[i].ParentMessage != null)
                        {
                            msg.Attachments.RemoveAt(i);
                        }
                    }
                }
                msg.InReplyTo = msg.Id.ToString();
                ActiveUp.Net.Mail.DeltaExt.MailUser mailUser = null;
                if (WebMailClientManager.AccountExist())
                {
                    mailUser = WebMailClientManager.getAccount();
                }

                if (mailUser != null)
                {
                    MailServerFacade f = MailServerFacade.GetInstance(mailUser);
                    msg.From = new Address(mailUser.Casella);
                    if (mailUser.IsManaged)
                    {
                        try
                        {
                            SendMail.Model.ComunicazioniMapping.Comunicazioni c =
                                new SendMail.Model.ComunicazioniMapping.Comunicazioni(
                                    SendMail.Model.TipoCanale.MAIL,
                                    "0",
                                    msg,
                                    MySecurityProvider.CurrentPrincipal.MyIdentity.UserName, 2, "O");
                            if (c.MailComunicazione.MailRefs != null && c.MailComunicazione.MailRefs.Count != 0)
                            {
                                c.RubricaEntitaUsed = (from cont in c.MailComunicazione.MailRefs
                                                       select new SendMail.Model.ComunicazioniMapping.RubrEntitaUsed
                                {
                                    Mail = cont.MailDestinatario,
                                    TipoContatto = cont.TipoRef
                                }).ToList();
                            }
                            if (SessionManager <Dictionary <string, DTOFileUploadResult> > .exist(SessionKeys.DTO_FILE))
                            {
                                Dictionary <string, DTOFileUploadResult> dictDto = SessionManager <Dictionary <string, DTOFileUploadResult> > .get(SessionKeys.DTO_FILE);

                                List <DTOFileUploadResult> dto = (List <DTOFileUploadResult>)dictDto.Values.ToList();
                                c.ComAllegati = new List <ComAllegato>();
                                foreach (DTOFileUploadResult dd in dto)
                                {
                                    ComAllegato allegato = new SendMail.Model.ComunicazioniMapping.ComAllegato();
                                    allegato.AllegatoExt  = dd.Extension;
                                    allegato.AllegatoFile = dd.CustomData;
                                    allegato.AllegatoName = dd.FileName;
                                    allegato.AllegatoTpu  = "";
                                    allegato.FlgInsProt   = AllegatoProtocolloStatus.FALSE;
                                    allegato.FlgProtToUpl = AllegatoProtocolloStatus.FALSE;
                                    c.ComAllegati.Add(allegato);
                                }
                            }
                            foreach (MimePart mm in msg.Attachments)
                            {
                                if (mm.BinaryContent != null || mm.BinaryContent.Length > 10)
                                {
                                    if (c.ComAllegati == null)
                                    {
                                        c.ComAllegati = new List <ComAllegato>();
                                    }

                                    ComAllegato allegato = new SendMail.Model.ComunicazioniMapping.ComAllegato();
                                    FileInfo    info     = new FileInfo(mm.Filename);
                                    allegato.AllegatoExt  = info.Extension;
                                    allegato.AllegatoFile = mm.BinaryContent;
                                    allegato.AllegatoName = mm.Filename;
                                    allegato.AllegatoTpu  = "";
                                    allegato.FlgInsProt   = AllegatoProtocolloStatus.FALSE;
                                    allegato.FlgProtToUpl = AllegatoProtocolloStatus.FALSE;
                                    c.ComAllegati.Add(allegato);
                                }
                            }
                            comunicazioniService.InsertComunicazione(c);
                        }
                        catch (Exception ex)
                        {
                            ManagedException mex = new ManagedException("Errore nel salvataggio della mail",
                                                                        "MAIL_CMP_002", "", ex.StackTrace, ex);
                            ErrorLog err = new ErrorLog(mex);
                            log.Error(err);
                            model.message = "Errore nell'invio del messaggio";
                            model.success = "false";
                            return(this.Request.CreateResponse <MailModel>(HttpStatusCode.OK, model));
                        }
                    }
                    else
                    {
                        f.sendMail(msg);
                    }

                    model.message = "Email memorizzata correttamente";
                    model.success = "true";
                    return(this.Request.CreateResponse <MailModel>(HttpStatusCode.OK, model));
                }
                else
                {
                    model.message = "Account inesistente";
                    model.success = "false";
                    return(this.Request.CreateResponse <MailModel>(HttpStatusCode.OK, model));
                }
            }
            catch (Exception ex)
            {
                if (ex.GetType() != typeof(ManagedException))
                {
                    log.Error(new Com.Delta.Logging.Errors.ErrorLog(new ManagedException(ex.Message, "FAC_007", string.Empty, string.Empty, ex)));
                }

                model.message = ex.Message;
                model.success = "false";
                return(this.Request.CreateResponse <MailModel>(HttpStatusCode.OK, model));
            }
            model.message = "Email memorizzata correttamente";
            model.success = "true";
            return(this.Request.CreateResponse <MailModel>(HttpStatusCode.OK, model));
        }
Esempio n. 5
0
        protected void btnSend_OnClick(object sender, EventArgs e)
        {
            if (HeaderNew.DestinatarioSelected != null && HeaderNew.DestinatarioSelected.Length > 0)
            {
                if (HeaderNew.SottoTitoloSelected != string.Empty && HeaderNew.TitoloSelected != "-- Selezionare un titolo --" && HeaderNew.SottoTitoloSelected.Length > 0)
                {
                    try
                    {
                        SendMail.Model.ComunicazioniMapping.Comunicazioni comun = new SendMail.Model.ComunicazioniMapping.Comunicazioni();
                        // gestione allegati
                        List <ComAllegato> allegati = new List <ComAllegato>();
                        if (SessionManager <Dictionary <string, DTOFileUploadResult> > .exist(SessionKeys.DTO_FILE))
                        {
                            Dictionary <string, DTOFileUploadResult> dictDto = SessionManager <Dictionary <string, DTOFileUploadResult> > .get(SessionKeys.DTO_FILE);

                            List <DTOFileUploadResult> dto = (List <DTOFileUploadResult>)dictDto.Values.ToList();
                            foreach (DTOFileUploadResult d in dto)
                            {
                                SendMail.Model.ComunicazioniMapping.ComAllegato allegato = new SendMail.Model.ComunicazioniMapping.ComAllegato();
                                allegato.AllegatoExt  = d.Extension;
                                allegato.AllegatoFile = d.CustomData;
                                allegato.AllegatoName = d.FileName;
                                allegato.AllegatoTpu  = "";
                                allegato.FlgInsProt   = AllegatoProtocolloStatus.FALSE;
                                allegato.FlgProtToUpl = AllegatoProtocolloStatus.FALSE;
                                allegati.Add(allegato);
                            }
                        }

                        comun.ComAllegati = allegati;
                        string[] destinatari = HeaderNew.DestinatarioSelected.Split(';');
                        for (int i = 0; i < destinatari.Length; i++)
                        {
                            var match = Regex.Match(destinatari[i], regexMail, RegexOptions.IgnoreCase);
                            if (!match.Success)
                            {
                                ((BasePage)this.Page).info.AddMessage("Attenzione mail destinatario non valida ", LivelloMessaggio.ERROR);
                                return;
                            }
                        }
                        // gestione destinatari
                        ContactsApplicationMapping c = new ContactsApplicationMapping
                        {
                            Mail          = HeaderNew.DestinatarioSelected,
                            IdSottotitolo = long.Parse(HeaderNew.SottoTitoloSelected),
                            IdTitolo      = long.Parse(HeaderNew.TitoloSelected)
                        };
                        Collection <ContactsApplicationMapping> en = new Collection <ContactsApplicationMapping>();
                        en.Add(c);
                        if (HeaderNew.ConoscenzaSelected != string.Empty)
                        {
                            string[] conoscenze = HeaderNew.ConoscenzaSelected.Split(';');
                            for (int i = 0; i < conoscenze.Length; i++)
                            {
                                var match = Regex.Match(conoscenze[i], regexMail, RegexOptions.IgnoreCase);
                                if (!match.Success)
                                {
                                    ((BasePage)this.Page).info.AddMessage("Attenzione mail conoscenza non valida ", LivelloMessaggio.ERROR);
                                    return;
                                }
                            }
                            ContactsApplicationMapping c1 = new ContactsApplicationMapping
                            {
                                Mail          = HeaderNew.ConoscenzaSelected,
                                IdSottotitolo = long.Parse(HeaderNew.SottoTitoloSelected),
                                IdTitolo      = long.Parse(HeaderNew.TitoloSelected)
                            };
                            Collection <ContactsApplicationMapping> en1 = new Collection <ContactsApplicationMapping>();
                            en1.Add(c1);
                            comun.SetMailDestinatari(en1, AddresseeType.CC);
                        }
                        if (HeaderNew.BCCSelected != string.Empty)
                        {
                            string[] bcc = HeaderNew.BCCSelected.Split(';');
                            for (int i = 0; i < bcc.Length; i++)
                            {
                                var match = Regex.Match(bcc[i], regexMail, RegexOptions.IgnoreCase);
                                if (!match.Success)
                                {
                                    ((BasePage)this.Page).info.AddMessage("Attenzione mail BCC non valida ", LivelloMessaggio.ERROR);
                                    return;
                                }
                            }

                            ContactsApplicationMapping c2 = new ContactsApplicationMapping
                            {
                                Mail          = HeaderNew.BCCSelected,
                                IdSottotitolo = long.Parse(HeaderNew.SottoTitoloSelected),
                                IdTitolo      = long.Parse(HeaderNew.TitoloSelected)
                            };
                            Collection <ContactsApplicationMapping> en2 = new Collection <ContactsApplicationMapping>();
                            en2.Add(c2);
                            comun.SetMailDestinatari(en2, AddresseeType.CCN);
                        }
                        comun.SetMailDestinatari(en, AddresseeType.TO);
                        // gestione body email
                        MailContent content = new MailContent();
                        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                        string html = CacheManager <XmlDocument> .EmptyHtml;
                        HtmlAgilityPack.HtmlNode body = null;
                        if (string.IsNullOrEmpty(html) == false)
                        {
                            doc.LoadHtml(html);
                            doc.OptionAutoCloseOnEnd = true;
                            doc.OptionFixNestedTags  = true;
                            body = doc.DocumentNode.Descendants()
                                   .Where(n => n.Name.Equals("body", StringComparison.InvariantCultureIgnoreCase))
                                   .FirstOrDefault();
                        }
                        var ele = new HtmlAgilityPack.HtmlNode(HtmlAgilityPack.HtmlNodeType.Element, doc, 0);
                        ele.Name            = "div";
                        ele.InnerHtml       = HidHtml.Value;
                        content.MailSubject = HeaderNew.ObjectSelected;
                        content.MailText    = ele.OuterHtml;
                        // gestione sender
                        MailUser mailuser = WebMailClientManager.getAccount();
                        content.MailSender      = mailuser.EmailAddress;
                        c.IdTitolo              = long.Parse(HeaderNew.TitoloSelected);
                        c.IdSottotitolo         = long.Parse(HeaderNew.SottoTitoloSelected);
                        comun.UtenteInserimento = MySecurityProvider.CurrentPrincipal.MyIdentity.UserName;
                        comun.MailComunicazione = content;
                        // da scommentare
                        comun.FolderTipo = "O";
                        comun.FolderId   = 2;
                        ComunicazioniService com = new ComunicazioniService();
                        com.InsertComunicazione(comun);
                        // ((baseLayoutDelta.BasePage)this.Page).info.ClearMessage();
                        ((BasePage)this.Page).info.AddMessage("Email correttamente inviata", LivelloMessaggio.INFO);
                        btnSend.Visible = false;
                        SessionManager <Dictionary <string, DTOFileUploadResult> > .del(SessionKeys.DTO_FILE);
                    }
                    catch (Exception ex)
                    {
                        if (ex.GetType() != typeof(ManagedException))
                        {
                            ManagedException mEx = new ManagedException("Errore invio nuova mail. Dettaglio: " + ex.Message +
                                                                        "StackTrace: " + ((ex.StackTrace != null) ? ex.StackTrace.ToString() : " vuoto "),
                                                                        "ERR317",
                                                                        string.Empty,
                                                                        string.Empty,
                                                                        ex.InnerException);
                            ErrorLogInfo err = new ErrorLogInfo(mEx);
                            log.Error(err);
                        }
                        btnSend.Enabled = true;
                        ((BasePage)this.Page).info.AddMessage(/*error.logCode + */ " - Errore durante l'inserimento della mail:" + ex.Message, LivelloMessaggio.ERROR);
                    }
                    return;
                }
                ((BasePage)this.Page).info.AddMessage("Attenzione sottotitolo non selezionato ", LivelloMessaggio.ERROR);
                return;
            }
            else
            {
                ((BasePage)this.Page).info.AddMessage("Attenzione email destinatario non corretta ", LivelloMessaggio.ERROR);
                return;
            }
        }
Esempio n. 6
0
        public static void Receive(string mail)
        {
            ApplicationCodeConfigSection configSection =
                (ApplicationCodeConfigSection)ConfigurationManager.GetSection("ApplicationCode");

            if (configSection != null)
            {
                APP_CODE = configSection.AppCode;
            }

            IList <ActiveUp.Net.Mail.DeltaExt.MailUser> listUsers = null;

            try
            {
                //listUsers = ServiceLocator.GetServiceFactory().MailAccountService.GetAllManaged();
                List <string> mails = new List <string>();
                mails.Add(mail);
                MailAccountService mailaccountservice = new MailAccountService();
                listUsers = mailaccountservice.GetUsersByMails(mails);
                listUsers = listUsers.Where(x => x.FlgManaged != 0).ToList();
            }
            catch (Exception ex)
            {
                if (ex.GetType() != typeof(ManagedException))
                {
                    ManagedException mEx = new ManagedException("Errore nel caricamento degli utenti di posta dettagli: " + ex.Message,
                                                                "RMA_001",
                                                                string.Empty,
                                                                string.Empty,
                                                                ex.InnerException);
                    ErrorLogInfo err = new ErrorLogInfo(mEx);
                    _log.Error(err);
                }
            }

            // IMailServerService mailService = null
            MailServerService mailService        = new MailServerService();
            MailLocalService  mailMessageService = null;

            foreach (ActiveUp.Net.Mail.DeltaExt.MailUser user in listUsers)
            {
                _log.Info(new MailLogInfo(APP_CODE, "", user.DisplayName,
                                          user.EmailAddress, (string)null));
                try
                {
                    mailService        = MailServerService.Instance.GetInstance(user);
                    mailMessageService = MailLocalService.Instance;
                }
                catch (Exception e)
                {
                    //TASK: Allineamento log - Ciro
                    if (e.GetType() != typeof(ManagedException))
                    {
                        ManagedException mEx = new ManagedException("Errore nel caricamento degli utenti di posta dettagli: " + e.Message,
                                                                    "RMA_002",
                                                                    string.Empty,
                                                                    string.Empty,
                                                                    e.InnerException);
                        ErrorLogInfo err = new ErrorLogInfo(mEx);
                        _log.Error(err);
                    }
                    //ManagedException mEx = new ManagedException(String.Format("Account {0} non valido", user.EmailAddress), "RMA_002", "", "", e);
                    //ErrorLog err = new ErrorLog(APP_CODE, mEx);
                    //_log.Error(err);
                    continue;
                }
                user.Validated = true;

                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("Account: " + user.EmailAddress);
                Console.ResetColor();
                int retries = 0;
                do
                {
                    mailService.IncomingConnect();
                    if (mailService.IsIncomingConnected())
                    {
                        break;
                    }
                    ++retries;
                }while (retries <= 5);

                if (!mailService.IsIncomingConnected())
                {
                    //TASK: Allineamento log - Ciro
                    ManagedException mEx = new ManagedException("Impossibile connettersi al server remoto",
                                                                "RMA_022",
                                                                string.Empty,
                                                                string.Empty,
                                                                null);
                    ErrorLogInfo err = new ErrorLogInfo(mEx);
                    err.loggingAppCode = string.Empty;
                    err.objectID       = mail.ToString() + " - " + System.DateTime.Now.Date + "_" + System.DateTime.Now.Ticks;
                    err.userID         = user.UserId.ToString();
                    _log.Error(err);
                    //_log.Error(new ErrorLogInfo(APP_CODE, "RMA_002", "Impossibile connettersi al server remoto.",
                    //    user.EmailAddress, null, null, null, null, null, null,
                    //    null, null, null));
                    continue;
                }
                ///pensiamo a qualcosa di più decente che così non si può vedere
                System.Threading.Thread.Sleep(500);
                List <MessageUniqueId> listUIds = mailService.RetrieveUIds();
                if (listUIds == null || listUIds.Count == 0)
                {
                    if (mailService.IsIncomingConnected())
                    {
                        Disconnect(mailService);
                    }
                    _log.Info(new MailLogInfo(APP_CODE, "", user.DisplayName,
                                              user.EmailAddress, "Nessun messaggio da scaricare"));
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Non vi sono messaggi da scaricare");
                    Console.ResetColor();
                    continue;
                }

                listUIds = listUIds.OrderBy(x => x.Ordinal).ToList();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(String.Format("Vi sono {0} messaggi da scaricare", listUIds.Count()));
                Console.ResetColor();
                List <ActiveUp.Net.Common.DeltaExt.MailStatusServer> stSer = new List <ActiveUp.Net.Common.DeltaExt.MailStatusServer>();
                stSer.Add(ActiveUp.Net.Common.DeltaExt.MailStatusServer.PRESENTE);
                stSer.Add(ActiveUp.Net.Common.DeltaExt.MailStatusServer.DA_NON_CANCELLARE);
                Dictionary <ActiveUp.Net.Common.DeltaExt.MailStatusServer, List <string> > savedUidsAll = (Dictionary <ActiveUp.Net.Common.DeltaExt.MailStatusServer, List <string> >)mailMessageService.GetAllUIDsByAccount(user.EmailAddress, stSer);
                List <string> savedUids = null;
                if (savedUidsAll != null && savedUidsAll.Count > 0)
                {
                    savedUids = savedUidsAll.SelectMany(x => x.Value).ToList();
                }
                else
                {
                    savedUids = new List <string>();
                }
                //cancello dal server
                bool   toCancel  = false;
                string cancelKey = System.Configuration.ConfigurationManager.AppSettings.Get("DeleteFromServer");
                bool.TryParse(cancelKey, out toCancel);
                int idx = 0;
                //se abilitato alla cancellazione
                if (user.FlgManaged == 2 && toCancel)
                {
                    //se ci sono email da cencellare
                    if (savedUidsAll != null && savedUidsAll.ContainsKey(ActiveUp.Net.Common.DeltaExt.MailStatusServer.PRESENTE) && savedUidsAll[ActiveUp.Net.Common.DeltaExt.MailStatusServer.PRESENTE].Count != 0)
                    {
                        try
                        {
                            //seleziona gli uid da cancellare
                            var mailToCancel = listUIds.Where(x =>
                                                              savedUidsAll[ActiveUp.Net.Common.DeltaExt.MailStatusServer.PRESENTE].Contains(x.UId.Replace(',', '§')));
                            foreach (var uid in mailToCancel)
                            {
                                //cancella dal server
                                mailService.DeleteMessageFromServer(uid.UId);
                                Disconnect(mailService);
                                Connect(mailService);
                                mailMessageService.UpdateMessageServerStatus(user.EmailAddress, uid.UId, ActiveUp.Net.Common.DeltaExt.MailStatusServer.CANCELLATA);
                                idx = mailToCancel.IndexOf(uid) + 1;
                                //disconnect ogni 10 mail per committare sul server
                                if ((idx % 10) == 0)
                                {
                                    Console.ForegroundColor = ConsoleColor.Red;
                                    Console.WriteLine("Cancellati " + idx + " messaggi");
                                    Console.ResetColor();
                                    if (Disconnect(mailService))
                                    {
                                        if (!Connect(mailService))
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                            _log.Info(new MailLogInfo(APP_CODE, "", user.DisplayName,
                                                      user.EmailAddress, "Cancellati " + idx + " messaggi"));
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("Cancellati " + idx + " messaggi");
                            Console.ResetColor();
                            if (Disconnect(mailService))
                            {
                                if (!Connect(mailService))
                                {
                                    continue;
                                }
                            }
                            //aggiorna gli uid dal server di posta
                            listUIds = mailService.RetrieveUIds();
                            if (listUIds == null || listUIds.Count == 0)
                            {
                                if (mailService.IsIncomingConnected())
                                {
                                    Disconnect(mailService);
                                }
                                _log.Info(new MailLogInfo(APP_CODE, "", user.DisplayName,
                                                          user.EmailAddress, "Nessun messaggio da scaricare"));
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("Non vi sono messaggi da scaricare");
                                Console.ResetColor();
                                continue;
                            }
                            //esclude quelli da già in banca dati, se vi sono
                            var lUids = listUIds.Where(x => !savedUidsAll[ActiveUp.Net.Common.DeltaExt.MailStatusServer.PRESENTE].Contains(x.UId));
                            if (lUids.Count() == 0)
                            {
                                continue;
                            }
                            listUIds = lUids.OrderBy(x => x.Ordinal).ToList();
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine(String.Format("Vi sono {0} messaggi da scaricare", listUIds.Count()));
                            Console.ResetColor();
                            _log.Info(new MailLogInfo(APP_CODE, "", user.DisplayName,
                                                      user.EmailAddress, "Vi sono " + listUIds.Count + " messaggi da scaricare"));
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }
                idx = 0;
                foreach (MessageUniqueId uId in listUIds)
                {
                    if (!savedUids.Contains(uId.UId.Replace(',', '§')))
                    {
                        _log.Debug("WORKING UID:" + uId.UId);
                        _log.Debug("WORKING ORDINAL:" + uId.Ordinal);
                        List <ActiveUp.Net.Mail.DeltaExt.MailHeader> ml = ((MailServerService)mailService).Pop3.RetrieveHeaders(uId.Ordinal, 1);
                        if (ml == null || ml.Count == 0)
                        {
                            ml = new List <ActiveUp.Net.Mail.DeltaExt.MailHeader>();
                            ml.Add(new ActiveUp.Net.Mail.DeltaExt.MailHeader {
                                UniqueId = uId.UId
                            });
                        }
                        _log.Debug(string.Format("WORKING HEADER: FROM - {0} ; SUBJECT - {1} ; UID - {2}", ml[0].From, ml[0].Subject, ml[0].UniqueId));
                        //maxSize da configurazione
                        int    maxSize         = 0;
                        string confMaxMailSize = ConfigurationManager.AppSettings.Get("MaxMailSizeInMB");
                        if (!String.IsNullOrEmpty(confMaxMailSize))
                        {
                            int.TryParse(confMaxMailSize, out maxSize);
                            // limite alzato a 8 mega
                            //     maxSize *= (int)Math.Pow(1024, 2);
                            maxSize *= (int)Math.Pow(1024, 8);
                        }
                        if (maxSize > 0)//se è definito un maxSize positivo
                        {
                            //dimensione del messaggio in byte
                            int size = mailService.GetMessageSize(uId.UId);
                            if (size > maxSize) // 4MB
                            {
                                //TASK: Allineamento log - Ciro
                                ManagedException mEx = new ManagedException(string.Format("Messaggio: {0} - Mail superiore a {1}MB! Controllare sul server", uId.UId, ConfigurationManager.AppSettings.Get("MaxMailSizeInMB")),
                                                                            "RMA_031",
                                                                            string.Empty,
                                                                            string.Empty,
                                                                            null);
                                ErrorLogInfo err = new ErrorLogInfo(mEx);
                                _log.Error(err);
                                //_log.Error(new ErrorLogInfo(APP_CODE, "RMA_003",
                                //    string.Format("Messaggio: {0} - Mail superiore a {1}MB! Controllare sul server",
                                //    uId.UId,
                                //    ConfigurationManager.AppSettings.Get("MaxMailSizeInMB")),
                                //    user.EmailAddress, null, null, null, null,
                                //    null, null, null, null, null));
                                Console.ForegroundColor = ConsoleColor.Cyan;
                                Console.WriteLine("WORKING HEADER: FROM - {0} ; SUBJECT - {1} ; UID - {2} ; SIZE - {3} ", ml[0].From, ml[0].Subject, ml[0].UniqueId, size);
                                Console.ResetColor();
                                continue;
                            }
                        }

                        ActiveUp.Net.Mail.Message m = mailService.getMessage(uId.UId, false);

                        if (m == null) //messaggio non trovato dall'UID!!!!
                        {
                            byte[] msx;
                            try
                            {
                                //provo a prendere il messaggio per progressivo
                                if (!mailService.IsIncomingConnected())
                                {
                                    Connect(mailService);
                                }
                                msx = ((MailServerService)mailService).Pop3.Pop3Client.RetrieveMessage(uId.Ordinal);
                                if (mailService.IsIncomingConnected())
                                {
                                    mailService.IncomingDisconnect();
                                }
                            }
                            catch (Exception ex)
                            {
                                _log.Info(new MailLogInfo(APP_CODE, "", user.DisplayName, user.EmailAddress,
                                                          "Messaggio " + uId.UId + " non trovato"));
                                msx = null;
                            }
                            if (msx == null || msx.Length == 0)
                            {
                                continue;
                            }
                            ActiveUp.Net.Mail.Message msg = new Message();
                            try
                            {
                                //provo il parser dal binary content
                                //Parser.BodyParsed += new Parser.OnBodyParsedEvent(Parser_BodyParsed);
                                //Parser.ErrorParsing += new Parser.OnErrorParsingEvent(Parser_ErrorParsing);
                                msg     = Parser.ParseMessage(msx);
                                msg.Uid = uId.UId;
                            }
                            catch (Exception ex)
                            {
                                //costruisco il messaggio a mano
                                msg.OriginalData = msx;
                                msg.Uid          = uId.UId;
                                msg.From         = new Address();
                                msg.From.Email   = ml[0].From ?? "UNDEFINED";
                                if (!String.IsNullOrEmpty(ml[0].To))
                                {
                                    msg.To = new AddressCollection();
                                    string[] to_emails = ml[0].To.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                    msg.To.AddRange(to_emails.Select(to => new Address(to.Trim())));
                                }
                                msg.Subject = ml[0].Subject;
                                msg.Date    = ml[0].Date;

                                if (ex.GetType() != typeof(ManagedException))
                                {
                                    ManagedException mEx = new ManagedException("Messaggio costruito a mano: " + ex.Message,
                                                                                "ERR_H100",
                                                                                string.Empty,
                                                                                string.Empty,
                                                                                ex);
                                    ErrorLogInfo er = new ErrorLogInfo(mEx);
                                    _log.Error(er);
                                }
                            }
                            //assegno il messaggio al messaggio in lavorazione
                            m = msg;
                        }

                        try
                        {
                            if (savedUidsAll != null && savedUidsAll.ContainsKey(ActiveUp.Net.Common.DeltaExt.MailStatusServer.DA_NON_CANCELLARE) && savedUidsAll[ActiveUp.Net.Common.DeltaExt.MailStatusServer.DA_NON_CANCELLARE].Contains(m.Uid))
                            {
                                mailMessageService.Update(user, m);
                            }
                            else
                            {
                                mailMessageService.Insert(user, m);
                            }

                            if (!String.IsNullOrEmpty(m.HeaderFields["X-Ricevuta"]))
                            {
                                string ric = m.HeaderFields["X-Ricevuta"].ToLower();
                                ActiveUp.Net.Common.DeltaExt.MailStatus newSt = ActiveUp.Net.Common.DeltaExt.MailStatus.UNKNOWN;

                                switch (ric)
                                {
                                case "accettazione":
                                    newSt = ActiveUp.Net.Common.DeltaExt.MailStatus.ACCETTAZIONE;
                                    break;

                                case "non-accettazione":
                                    newSt = ActiveUp.Net.Common.DeltaExt.MailStatus.NON_ACCETTAZIONE;
                                    break;

                                case "presa-in-carico":
                                    break;

                                case "avvenuta-consegna":
                                    newSt = ActiveUp.Net.Common.DeltaExt.MailStatus.AVVENUTA_CONSEGNA;
                                    break;

                                case "posta-certificata":
                                    break;

                                case "errore-consegna":
                                    newSt = ActiveUp.Net.Common.DeltaExt.MailStatus.ERRORE_CONSEGNA;
                                    break;

                                case "preavviso-errore-consegna":
                                    newSt = ActiveUp.Net.Common.DeltaExt.MailStatus.ERRORE_CONSEGNA;
                                    break;

                                case "rilevazione-virus":
                                    newSt = ActiveUp.Net.Common.DeltaExt.MailStatus.ERROR;
                                    break;
                                }

                                if (newSt != ActiveUp.Net.Common.DeltaExt.MailStatus.UNKNOWN)
                                {
                                    string idOldString = m.HeaderFields["X-Riferimento-Message-ID"];
                                    if (idOldString.StartsWith("<"))
                                    {
                                        idOldString = idOldString.Substring(1);
                                    }
                                    if (idOldString.EndsWith(">"))
                                    {
                                        idOldString = idOldString.Substring(0, idOldString.Length - 1);
                                    }
                                    string[] idOldStr = idOldString.Split('.');
                                    Int64    idOld    = -1;
                                    if (idOldStr.Length > 0 && Int64.TryParse(idOldStr[0], out idOld))
                                    {
                                        //IComunicazioniService comS = ServiceLocator.GetServiceFactory().ComunicazioniService;
                                        ComunicazioniService comS = new ComunicazioniService();
                                        SendMail.Model.ComunicazioniMapping.Comunicazioni com = comS.LoadComunicazioneByIdMail(idOld);
                                        if (com != null)
                                        {
                                            SendMail.Model.ComunicazioniMapping.ComFlusso flusso = com.ComFlussi[SendMail.Model.TipoCanale.MAIL].Last();

                                            //se si trova in stato di errore non aggiorno
                                            if (flusso.StatoComunicazioneNew == ActiveUp.Net.Common.DeltaExt.MailStatus.ERROR ||
                                                flusso.StatoComunicazioneNew == ActiveUp.Net.Common.DeltaExt.MailStatus.CANCELLED ||
                                                flusso.StatoComunicazioneNew == ActiveUp.Net.Common.DeltaExt.MailStatus.NON_ACCETTAZIONE ||
                                                flusso.StatoComunicazioneNew == ActiveUp.Net.Common.DeltaExt.MailStatus.ERRORE_CONSEGNA)
                                            {
                                                idx = listUIds.ToList().IndexOf(uId);
                                                if ((idx != 0) && ((idx % 50) == 0))
                                                {
                                                    Console.ForegroundColor = ConsoleColor.Red;
                                                    Console.WriteLine("Inseriti " + idx + " messaggi");
                                                    Console.ResetColor();
                                                    _log.Info(new MailLogInfo(APP_CODE,
                                                                              "", user.DisplayName, user.EmailAddress,
                                                                              "Inseriti " + idx + " messaggi"));
                                                }
                                                continue;
                                            }

                                            SendMail.Model.ComunicazioniMapping.ComFlusso newFl = new SendMail.Model.ComunicazioniMapping.ComFlusso();
                                            newFl.Canale                = SendMail.Model.TipoCanale.MAIL;
                                            newFl.DataOperazione        = m.Date;
                                            newFl.RefIdComunicazione    = flusso.RefIdComunicazione;
                                            newFl.StatoComunicazioneNew = newSt;
                                            newFl.StatoComunicazioneOld = flusso.StatoComunicazioneNew;
                                            newFl.UtenteOperazione      = "SYSTEM";
                                            com.ComFlussi[SendMail.Model.TipoCanale.MAIL].Add(newFl);
                                            comS.UpdateFlussoComunicazione(SendMail.Model.TipoCanale.MAIL, com);
                                        }
                                        else
                                        {
                                            try
                                            {
                                                Message msg = mailMessageService.GetById(idOld);
                                                if (msg != null)
                                                {
                                                    List <string> uidMails = new List <string>();
                                                    uidMails.Add(msg.Uid);
                                                    mailMessageService.UpdateMailStatus(user.EmailAddress, uidMails, newSt, null, null, "I");
                                                }
                                            }
                                            catch
                                            {
                                                continue;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch (ManagedException mEx)
                        {
                            if (mEx.CodiceEccezione.Equals("WRN_INS_ML_001"))
                            {
                                mailService.DeleteMessageFromServer(uId.UId);
                            }
                        }
                        catch (Exception ex)
                        {
                            //TASK: Allineamento log - Ciro
                            if (ex.GetType() != typeof(ManagedException))
                            {
                                ManagedException mEx = new ManagedException(String.Format("Errore nel salvataggio della mail uid: {0} from: {1} subject:{2} dell'account {3}", m.Uid, m.From.Email, m.Subject, user.EmailAddress),
                                                                            "RMA_003",
                                                                            string.Empty,
                                                                            string.Empty,
                                                                            ex.InnerException);
                                ErrorLogInfo err = new ErrorLogInfo(mEx);
                                _log.Error(err);
                            }
                            //ManagedException mEx = new ManagedException(
                            //    String.Format("Errore nel salvataggio della mail uid: {0} from: {1} subject:{2} dell'account {3}", m.Uid, m.From.Email, m.Subject, user.EmailAddress),
                            //    "RCV_MAIL_003", "", "", ex);
                            //ErrorLog err = new ErrorLog(APP_CODE, mEx);
                            //_log.Error(err);
                        }

                        idx = listUIds.IndexOf(uId) + 1;
                        if ((idx % 50) == 0)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("Inseriti " + idx + " messaggi");
                            Console.ResetColor();
                            _log.Info(new MailLogInfo(APP_CODE, "", user.DisplayName,
                                                      user.EmailAddress, "Inseriti " + idx + " messaggi"));
                        }
                    }
                }
                if (mailService.IsIncomingConnected())
                {
                    Disconnect(mailService);
                }
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Inseriti " + listUIds.Count + " messaggi");
                Console.ResetColor();
                _log.Info(new MailLogInfo(APP_CODE, "", user.DisplayName,
                                          user.EmailAddress, "Inseriti " + listUIds.Count + " messaggi"));
            }
        }
Esempio n. 7
0
        public static void Send(string mail, int maxNrMail)
        {
            Console.WriteLine("Invio mail");
            MailMessage email = new MailMessage();
            List <SendMail.Model.ComunicazioniMapping.Comunicazioni> listComunicazioni = null;
            ComunicazioniService service = new ComunicazioniService();

            listComunicazioni = (List <SendMail.Model.ComunicazioniMapping.Comunicazioni>)service.LoadComunicazioniDaInviare(CANALE_INVIO, 0, maxNrMail, mail);
            if (listComunicazioni == null || listComunicazioni.Count == 0)
            {
                _log.Info(new MailLogInfo(APP_CODE, "", "BATCH", mail,
                                          "Nessuna comunicazione da inviare"));
                return;
            }
#if TEST
            // listComunicazioni = listComunicazioni.Where(c => c.IdComunicazione == 54373).ToList();
#endif
            Console.WriteLine("Trovate {0} comunicazioni", listComunicazioni.Count);
            _log.Info(new MailLogInfo(APP_CODE, "", "BACTH", mail,
                                      string.Format("Trovate {0} comunicazioni", listComunicazioni.Count)));
            List <String> mails = null;
            var           accs  = from c in listComunicazioni
                                  where c.MailComunicazione != null
                                  let mc = c.MailComunicazione
                                           where !String.IsNullOrEmpty(mc.MailSender)
                                           select mc.MailSender;

            if (accs != null && accs.Count() != 0)
            {
                mails = accs.Distinct().ToList();
            }
            IList <MailUser> mUs = null;
            if (mails != null)
            {
                MailAccountService accS = new MailAccountService();
                mUs = accS.GetUsersByMails(mails);
            }
            if (mUs == null)
            {
                ManagedException mEx = new ManagedException("Nessun account mappato per invio mail",
                                                            "SND_ERR_011",
                                                            string.Empty,
                                                            string.Empty,
                                                            null);
                ErrorLogInfo err = new ErrorLogInfo(mEx);
                _log.Error(err);
                return;
            }

            foreach (SendMail.Model.ComunicazioniMapping.Comunicazioni comun in listComunicazioni)
            {
                Console.WriteLine("Id comunicazione: {0}", comun.IdComunicazione);
                SendMail.Model.ComunicazioniMapping.ComFlusso nuovoFlusso = null;
                IOrderedEnumerable <SendMail.Model.ComunicazioniMapping.ComFlusso> flusso = comun.ComFlussi[CANALE_INVIO].OrderBy(f => !f.DataOperazione.HasValue).ThenBy(f => f.DataOperazione);
                if (flusso.Last().StatoComunicazioneOld == MailStatus.SEND_AGAIN)
                {
                    nuovoFlusso = flusso.Last();
                }
                else
                {
                    nuovoFlusso =
                        new SendMail.Model.ComunicazioniMapping.ComFlusso()
                    {
                        Canale                = CANALE_INVIO,
                        RefIdComunicazione    = comun.IdComunicazione,
                        StatoComunicazioneOld = flusso.Last().StatoComunicazioneNew,
                        StatoComunicazioneNew = MailStatus.UNKNOWN,
                        UtenteOperazione      = flusso.Last().UtenteOperazione
                    };
                    comun.ComFlussi[CANALE_INVIO].Add(nuovoFlusso);
                }

                if (!comun.IsValid)
                {
                    nuovoFlusso.StatoComunicazioneNew = MailStatus.ERROR;
                    UpdateFlusso(comun);
                    continue;
                }

                MailUser us = mUs.SingleOrDefault(x => x.EmailAddress == comun.MailComunicazione.MailSender);
                if (us == null)
                {
                    nuovoFlusso.StatoComunicazioneNew = MailStatus.CANCELLED;
                    UpdateFlusso(comun);
                    continue;
                }

                List <SendMail.Model.ComunicazioniMapping.ComAllegato> allegatiList =
                    (List <SendMail.Model.ComunicazioniMapping.ComAllegato>)comun.ComAllegati;
                try
                {
                    foreach (SendMail.Model.ComunicazioniMapping.ComAllegato allegato in allegatiList)
                    {
                        try
                        {
                            switch (allegato.AllegatoExt)
                            {
                            case "XSL":
                            case "xsl":
                                System.IO.MemoryStream sXML = new System.IO.MemoryStream(allegato.AllegatoFile);
                                XmlDocument            xml  = new XmlDocument();
                                xml.Load(sXML);
                                string   xslUri    = System.IO.Path.Combine(ConfigurationManager.AppSettings.Get("pathFolderTpu"), allegato.AllegatoTpu);
                                string[] separator = new string[1] {
                                    ".tpu"
                                };
                                string[]    appo = xslUri.Split(separator, StringSplitOptions.RemoveEmptyEntries);
                                XmlDocument xsl  = new XmlDocument();
                                xsl.Load(appo[0].Trim());
                                // modificato per usare itextsharp
                                PdfFormatterITEXT      fo   = FormatterProvider.formatDocumentitext("PDF");
                                System.IO.MemoryStream mPdf = fo.formatData(xml, xsl);
                                // fine modifica
                                IDictionary <string, string> d = new Dictionary <string, string>();
                                d.Add("subject", "VERIFICA ABITAZIONE");
                                d.Add("author", "ROMA CAPITALE");
                                d.Add("creator", "Certificati Online");
                                byte[] bdoc = fo.SetMetadati(mPdf, d);
                                allegato.AllegatoFile = bdoc;
                                allegato.AllegatoExt  = "PDF";
                                break;

                            default:
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            if (!ex.GetType().Equals(typeof(ManagedException)))
                            {
                                ManagedException mEx = new ManagedException("Errore nella generazione del pdf",
                                                                            "SEN_012",
                                                                            string.Empty,
                                                                            string.Empty,
                                                                            ex.InnerException);
                                mEx.addEnanchedInfosTag("REQUEST", new XElement("Mail",
                                                                                new XAttribute("IdComunicazione", comun.IdComunicazione),
                                                                                new XElement("Status", nuovoFlusso.StatoComunicazioneNew.ToString()),
                                                                                new XElement("IdMail",
                                                                                             (comun.MailComunicazione.IdMail != null) ? comun.MailComunicazione.IdMail.ToString():" vuoto ")).ToString());
                                ErrorLogInfo err = new ErrorLogInfo(mEx);
                                err.objectID = (comun.UniqueId != null) ? comun.UniqueId : comun.IdComunicazione.ToString();
                                _log.Error(err);
                                throw mEx;
                            }
                            else
                            {
                                throw;
                            }
                        }
                    }
                }
                catch
                {
                    nuovoFlusso.StatoComunicazioneNew = MailStatus.ERROR;
                    UpdateFlusso(comun);
                    continue;
                }

                try
                {
                    service.UpdateAllegati(CANALE_INVIO, comun);
                }
                catch (Exception ex)
                {
                    if (!ex.GetType().Equals(typeof(ManagedException)))
                    {
                        ManagedException mEx = new ManagedException("Errore aggiornamento della mail",
                                                                    "SEN_002",
                                                                    string.Empty,
                                                                    string.Empty,
                                                                    ex.InnerException);
                        mEx.addEnanchedInfosTag("REQUEST", new XElement("Mail",
                                                                        new XAttribute("IdMail", comun.IdComunicazione),
                                                                        new XElement("Status", nuovoFlusso.StatoComunicazioneNew.ToString())).ToString());
                        ErrorLogInfo err = new ErrorLogInfo(mEx);
                        err.objectID = (comun.UniqueId != null) ? comun.UniqueId : comun.IdComunicazione.ToString();
                        _log.Error(err);
                    }
                }
                try
                {
                    email = ComunicazioniExtensionMethods.ConvertToEmail(comun);
                    if (null == email)
                    {
                        throw new ArgumentNullException("email non creata");
                    }
                    //carica le immagini
                    HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
                    htmlDoc.LoadHtml(email.Body);
                    var imgs = from img in htmlDoc.DocumentNode.Descendants("img")
                               where img.Attributes["src"].Value.StartsWith("file:///")
                               select img;
                    if (imgs.Count() > 0)
                    {
                        foreach (var img in imgs)
                        {
                            string rootPath = ConfigurationManager.AppSettings.Get("pathFolderTpu");
                            string pathImg  = Path.Combine(rootPath, img.Attributes["src"].Value.Substring(8));
                            string ext      = Path.GetExtension(pathImg).Substring(1);
                            byte[] imgBytes = File.ReadAllBytes(pathImg);
                            img.Attributes["src"].Value = "data:image/" + ext + ";base64,"
                                                          + Convert.ToBase64String(imgBytes);
                        }

                        using (Stream ms = new MemoryStream())
                        {
                            htmlDoc.Save(ms, new UTF8Encoding(false));
                            ms.Position = 0;
                            byte[] buffer = new byte[ms.Length];
                            ms.Read(buffer, 0, (int)ms.Length);
                            email.Body = new UTF8Encoding(false).GetString(buffer);
                            service.UpdateMailBody(comun.MailComunicazione.IdMail.Value, email.Body);
                        }
                    }
                    foreach (ComAllegato t in comun.ComAllegati)
                    {
                        email.Attachments.Add(ComunicazioniExtensionMethods.ConvertToAttachment(t));
                    }
                }
                catch (Exception ex)
                {
                    if (!ex.GetType().Equals(typeof(ManagedException)))
                    {
                        ManagedException mEx = new ManagedException("Errore nella creazione della mail per il metabus",
                                                                    "SEN_003",
                                                                    string.Empty,
                                                                    string.Empty,
                                                                    ex.InnerException);
                        mEx.addEnanchedInfosTag("REQUEST", new XElement("Mail",
                                                                        new XAttribute("IdMail", comun.MailComunicazione.IdMail)).ToString());
                        ErrorLogInfo err = new ErrorLogInfo(mEx);
                        err.objectID = (comun.UniqueId != null) ? comun.UniqueId : comun.IdComunicazione.ToString();
                        _log.Error(err);
                    }

                    nuovoFlusso.StatoComunicazioneNew = MailStatus.ERROR;
                    UpdateFlusso(comun);
                    continue;
                }
                try
                {
                    MailUser user = MailServerConfigFacade.GetInstance().GetManagedUserByAccount(email.From.Address);
                    System.Net.Mail.SmtpClient smtpMail = new System.Net.Mail.SmtpClient();
                    smtpMail                       = new System.Net.Mail.SmtpClient(user.OutgoingServer, user.PortOutgoingServer);
                    smtpMail.EnableSsl             = user.IsOutgoingSecureConnection;
                    smtpMail.DeliveryMethod        = SmtpDeliveryMethod.Network;
                    smtpMail.UseDefaultCredentials = false;
                    if (user.LoginId != null && user.Password != null && user.LoginId.Length > 0)
                    {
                        smtpMail.Credentials = new NetworkCredential(user.LoginId, user.Password);
                    }
                    smtpMail.Send(email);
                    nuovoFlusso.StatoComunicazioneNew = MailStatus.SENT;
                    UpdateFlusso(comun);
                }
                catch (Exception ex)
                {
                    XElement details = new XElement("comunicazione",
                                                    new XAttribute("uniqueId", comun.UniqueId));
                    if (ex != null)
                    {
                        System.Xml.Serialization.XmlSerializer ser =
                            new System.Xml.Serialization.XmlSerializer(typeof(Exception));
                        MemoryStream ms = new MemoryStream();
                        ser.Serialize(ms, ex);
                        ms.Seek(0, SeekOrigin.Begin);
                        details.Add(XElement.Load(XmlReader.Create(ms)));
                    }

                    if (!ex.GetType().Equals(typeof(ManagedException)))
                    {
                        //TASK: Allineamento log - Ciro
                        ManagedException mEx = new ManagedException(String.Format("Errore: {0}", ex.Message),
                                                                    "SND_ERR_107",
                                                                    string.Empty,
                                                                    string.Empty,
                                                                    ex.InnerException);
                        mEx.addEnanchedInfosTag("REQUEST", new XElement("Mail",
                                                                        new XAttribute("IdMail", comun.IdComunicazione)).ToString());
                        ErrorLogInfo err = new ErrorLogInfo(mEx);
                        err.objectID = (comun.UniqueId != null) ? comun.UniqueId : comun.IdComunicazione.ToString();
                        _log.Error(err);
                    }
                    nuovoFlusso.StatoComunicazioneNew = MailStatus.SEND_AGAIN;
                    UpdateFlusso(comun);
                }
            }
        }