Пример #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);
                }
            }
        }
Пример #2
0
        public Comunicazioni(Comunicazioni c)
        {
            if (c == null)
            {
                return;
            }

            Type t = this.GetType();

            foreach (System.Reflection.PropertyInfo p in t.GetProperties())
            {
                if (p.CanWrite && p.CanRead)
                {
                    try
                    {
                        p.SetValue(this, p.GetValue(c, null), null);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
        }
Пример #3
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));
        }
Пример #4
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;
        }
Пример #5
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));
        }
Пример #6
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;
            }
        }