Exemple #1
0
 public Model.ComunicazioniMapping.ComAllegato GetById(long id)
 {
     SendMail.Model.ComunicazioniMapping.ComAllegato alleg = null;
     using (FAXPECContext dbcontext = new FAXPECContext())
     {
         try
         {
             COMUNICAZIONI_ALLEGATI allegato = dbcontext.COMUNICAZIONI_ALLEGATI.Where(x => x.ID_ALLEGATO == id).FirstOrDefault();
             alleg = AutoMapperConfiguration.FromAllegatoToModel(allegato);
         }
         catch { }
     }
     return(alleg);
 }
Exemple #2
0
        public ComAllegato(ComAllegato c)
        {
            if (c == null)
            {
                return;
            }

            Type t = c.GetType();

            foreach (System.Reflection.PropertyInfo p in t.GetProperties())
            {
                if (p.CanWrite)
                {
                    p.SetValue(this, p.GetValue(c, null), null);
                }
            }
        }
Exemple #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));
        }
        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));
        }
Exemple #5
0
        public Comunicazioni(TipoCanale canaleType, String sottoTitolo, ActiveUp.Net.Mail.Message msg, String utente, int folderId, string folderTipo)
        {
            #region "sottotitolo"

            if (!String.IsNullOrEmpty(sottoTitolo))
            {
                this.RefIdSottotitolo = Convert.ToInt64(sottoTitolo);
            }

            #endregion

            #region "mail"

            MailContent mail = new MailContent();
            this.MailComunicazione = mail;

            #region "sender"

            mail.MailSender = msg.From.Email;

            #endregion

            #region "refs"
            mail.MailRefs = new List <MailRefs>();
            List <MailRefs> lR = new List <MailRefs>();
            var             to = from to0 in msg.To
                                 select new MailRefs
            {
                MailDestinatario = to0.Email,
                TipoRef          = AddresseeType.TO
            };
            if (to.Count() > 0)
            {
                lR.AddRange(to);
            }
            var cc = from cc0 in msg.Cc
                     select new MailRefs
            {
                MailDestinatario = cc0.Email,
                TipoRef          = AddresseeType.CC
            };
            if (cc.Count() > 0)
            {
                lR.AddRange(cc);
            }
            var ccn = from ccn0 in msg.Bcc
                      select new MailRefs
            {
                MailDestinatario = ccn0.Email,
                TipoRef          = AddresseeType.CCN
            };
            if (ccn.Count() > 0)
            {
                lR.AddRange(ccn);
            }
            if (lR.Count > 0)
            {
                mail.MailRefs = lR;
            }

            #endregion

            #region "subject"

            mail.MailSubject = msg.Subject;

            #endregion

            #region "body"

            mail.MailText = !String.IsNullOrEmpty(msg.BodyHtml.Text) ? msg.BodyHtml.Text : msg.BodyText.Text;

            #endregion

            #region "reply"
            if (!String.IsNullOrEmpty(msg.InReplyTo) && !String.IsNullOrEmpty(msg.InReplyTo.Trim()))
            {
                string follows = msg.InReplyTo.Trim();
                if (follows.StartsWith("<"))
                {
                    follows = follows.Substring(1);
                }
                if (follows.EndsWith(">"))
                {
                    follows = follows.Substring(0, follows.Length - 1);
                }
                long?flw    = null;
                long flwout = 0;
                if (long.TryParse(follows.Split('.')[0], out flwout))
                {
                    flw = flwout;
                }
                mail.Follows = flw;
            }
            #endregion
            #endregion

            #region "attachments"

            List <ComAllegato> all = null;
            if (msg.Attachments.Count > 0)
            {
                all = new List <ComAllegato>();

                for (int j = 0; j < msg.Attachments.Count; j++)
                {
                    ActiveUp.Net.Mail.MimePart mp = msg.Attachments[j];
                    ComAllegato a = new ComAllegato();
                    a.IdAllegato   = null;
                    a.AllegatoExt  = System.IO.Path.GetExtension(mp.Filename);
                    a.AllegatoExt  = a.AllegatoExt.Replace(".", string.Empty);
                    a.AllegatoFile = mp.BinaryContent;
                    a.AllegatoName = System.IO.Path.GetFileNameWithoutExtension(mp.Filename);
                    a.T_Progr      = j;
                    a.FlgInsProt   = AllegatoProtocolloStatus.UNKNOWN;
                    a.FlgProtToUpl = AllegatoProtocolloStatus.UNKNOWN;
                    a.RefIdCom     = null;

                    all.Add(a);
                }
            }
            this.ComAllegati = all;

            #endregion

            #region "notifica"

            this.MailNotifica = msg.ReplyTo.Email;

            #endregion

            #region "utente inserimento"

            this.UtenteInserimento = utente;

            #endregion

            #region "flusso comunicazione"

            this.SetStatoComunicazione(canaleType, MailStatus.INSERTED, utente);

            #endregion

            #region Folder
            this.FolderId   = folderId;
            this.FolderTipo = folderTipo;

            #endregion
        }
Exemple #6
0
        public Comunicazioni(TipoCanale canaleType, List <DataRow> _list)
        {
            this.ComFlussi = new Dictionary <TipoCanale, List <ComFlusso> >();
            this.ComFlussi.Add(canaleType, null);
            if (_list[0].Table.Columns.Contains("ANN_PRT"))
            {
                this.annPrt = _list[0].Field <string>("ANN_PRT");
                this.numPrt = _list[0].Field <string>("NUM_PRT");
            }
            if (_list[0].Table.Columns.Contains("COD_IND"))
            {
                this.CodiceIndividuale = _list[0].Field <string>("COD_IND");
            }
            this.ComCode         = _list[0].Field <String>("TIP_RIC");
            this.StringaID       = _list[0].Field <String>("STRINGA_ID");
            this.destinatariCode = _list[0].Field <String>("COD_DESTINATARIO").Split(';');
            string             oggetto = string.Empty;
            List <ComAllegato> lAll    = new List <ComAllegato>();
            StringBuilder      dati    = new StringBuilder();

            System.Collections.Generic.Dictionary <int, string> prus = new System.Collections.Generic.Dictionary <int, string>();
            System.Collections.Generic.Dictionary <int, string> tpus = new System.Collections.Generic.Dictionary <int, string>();

            if (_list == null && _list.Count == 0)
            {
                this.ComAllegati = null;
            }
            else
            {
                for (int i = 0; i < _list.Count; i++)
                {
                    if ((_list[i].Field <String>("NOME_TPU").ToUpper().Trim() == "TESTO_MAIL") || (_list[i].Field <String>("NOME_TPU").ToUpper().Trim() == "TESTO_MAIL_ELE"))
                    {
                        dati.Append(_list[i].Field <String>("DATI_PRU"));
                    }
                    if (_list[i].Field <string>("NOME_TPU").ToUpper().Trim() == "OGGETTO_MAIL_ELE")
                    {
                        oggetto += _list[i].Field <string>("DATI_PRU");
                        continue;
                    }

                    if (!(string.IsNullOrEmpty(_list[i].Field <String>("PROG_PRU")) || _list[i].Field <String>("NOME_TPU").ToLower().Equals("testo_mail") || _list[i].Field <String>("NOME_TPU").ToLower().Equals("testo_mail_ele")))
                    {
                        if (!prus.ContainsKey(int.Parse(_list[i].Field <String>("PROG_TPU").Trim())))
                        {
                            prus.Add(int.Parse(_list[i].Field <String>("PROG_TPU").Trim()), string.Empty);
                            tpus.Add(int.Parse(_list[i].Field <String>("PROG_TPU").Trim()), _list[i].Field <String>("NOME_TPU"));
                        }
                        prus[int.Parse(_list[i].Field <String>("PROG_TPU").Trim())] = prus[int.Parse(_list[i].Field <String>("PROG_TPU").Trim())] + _list[i].Field <String>("DATI_PRU");
                    }
                }

                for (int j = 0; j < tpus.Count; j++)
                {
                    ComAllegato a = new ComAllegato();
                    a.IdAllegato   = null;
                    a.RefIdCom     = null;
                    a.AllegatoTpu  = tpus[j + 1];
                    a.T_Progr      = j;
                    a.AllegatoExt  = "PRU";
                    a.AllegatoFile = Encoding.GetEncoding("ISO-8859-1").GetBytes(prus[j + 1]);
                    a.AllegatoFile = new UTF8Encoding(false).GetBytes(prus[j + 1]);
                    string[] cmp = tpus[j + 1].Split('.');
                    a.AllegatoName = String.Format("{0}_{1}", String.Join(".", cmp, 0, cmp.Length - 1), (j + 1).ToString("D3"));
                    lAll.Add(a);
                }
                this.ComAllegati = lAll;
            }

            switch (canaleType)
            {
            case TipoCanale.MAIL:
                this.MailComunicazione               = new MailContent();
                this.MailComunicazione.MailSender    = _list[0].Field <String>("EMAIL");
                this.MailComunicazione.MailText      = dati.ToString();
                this.MailComunicazione.HasCustomRefs = false;
                if (!string.IsNullOrEmpty(oggetto))
                {
                    this.MailComunicazione.MailSubject = oggetto.Trim();
                }
                break;

            default:
                break;
            }
        }
Exemple #7
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;
            }
        }