Ejemplo n.º 1
0
            /// <summary>
            /// Función genérica de envío de correo electrónico devuelve el error producido ostring.empty si todo ok
            /// </summary>
            /// <param name="eMail">Mail del destinatario. Se admiten varias direccion separadas por ; La ultima tiene que tener ; para saber que esta formateado</param>
            /// <param name="Asunto">Asunto del envio del correo</param>
            /// <param name="cuerpoTexto">Texto que aparecera en el mensaje. Se admite HTML</param>
            /// <param name="empresaRemitente">Nombre de la empresa o persona que envia el mail</param>
            /// <param name="mailRemitente">Mail del remitente (opcional)</param>
            /// <param name="hostSMTP">Servidor de envio</param>
            /// <param name="userName">Nombre de usuario</param>
            /// <param name="userPass">Password de la cuenta</param>
            /// <param name="enableSsl">Habilitar la seguridad del servidor</param>
            /// <returns>
            /// String empty if it's success. If not return the error message
            /// </returns>
            public string EnviarMail(string eMail, string Asunto, string cuerpoTexto,
                                     string empresaRemitente, string mailRemitente, string hostSMTP, string userName,
                                     string userPass, bool IsBodyHtml, bool enableSsl = false)
            {
                string err = string.Empty;

                // preparar el correo en fotmato HTML
                if (eMail != "")
                {
                    // ENVÍO DEL FORMULARIO DE CONTACTO
                    // variables para la gestión del correo
                    MailMessage correo = new MailMessage();
                    SmtpClient  smtp   = new SmtpClient(hostSMTP);
                    // identificación de usuario
                    if (enableSsl)
                    {
                        smtp.Port = 587;
                    }
                    smtp.EnableSsl = enableSsl;
                    //smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                    //smtp.UseDefaultCredentials = false;
                    NetworkCredential userCredentials = new NetworkCredential(userName, userPass);
                    smtp.Credentials = userCredentials;
                    // agregar remitente
                    MailAddress emailRemitente;
                    try
                    {
                        emailRemitente = new MailAddress(mailRemitente, empresaRemitente);
                    }
                    catch
                    {
                        emailRemitente = new MailAddress("*****@*****.**", "DrUalcman API");
                    }
                    correo.From = emailRemitente;
                    correo.ReplyToList.Add(emailRemitente);
                    // agregar el asunto
                    correo.Subject = Asunto;
                    // propiedades del mail
                    correo.Priority   = MailPriority.Normal;
                    correo.IsBodyHtml = IsBodyHtml;

                    ficheros f = new ficheros();
                    string   fileHTML;
                    //guardar una copia del correo para poner un enlace a la copia HTML del mismo
                    try
                    {
                        fileHTML = f.guardaDato("mail.html", cuerpoTexto, "mails", true);
                    }
                    catch
                    {
                        fileHTML = string.Empty;
                    }

                    cuerpoTexto += Environment.NewLine;

                    if (!string.IsNullOrEmpty(fileHTML))
                    {
                        if (IsBodyHtml == true)
                        {
                            //insert link
                            cuerpoTexto += basicHTML.a(knowServerURL() + "/mails/" + fileHTML, "If you cannot read the message well click here to read it online", "_blank");
                        }
                        else
                        {
                            //inser texto where is it the file
                            cuerpoTexto += " If you cannot read the message well click here " + knowServerURL() + "/mails/" + fileHTML + " to read it online (copy the link in your Internet browser)";
                        }
                    }

                    // cuerpo del mail
                    correo.Body = cuerpoTexto;

                    //hacer el envio a todas las direcciones encontradas
                    if (eMail.IndexOf(";") > 0)
                    {
                        // extraer las direcciones
                        string[] Direcciones = eMail.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                        bool seguimiento;
                        if (eMail.IndexOf("invite.trustpilot.com") < 0)
                        {
                            seguimiento = false;
                        }
                        else
                        {
                            seguimiento = true;
                        }

                        byte s                = 1;
                        bool enviado          = false;
                        int  numDestinatarios = 50;
                        // recorrer las direcciones para realizar el envio
                        foreach (string item in Direcciones)
                        {
                            if (item != "")
                            {
                                //comprobar que tiene @
                                if (item.IndexOf("@") > 0)
                                {
                                    MailAddress nuevoCorreo = new MailAddress(item);
                                    if (seguimiento)
                                    {
                                        if (s < 2)
                                        {
                                            correo.To.Add(nuevoCorreo);
                                        }
                                        else
                                        {
                                            correo.Bcc.Add(nuevoCorreo);
                                        }
                                    }
                                    else
                                    {
                                        correo.Bcc.Add(nuevoCorreo);
                                    }
                                }

                                if (s >= numDestinatarios)
                                {
                                    try
                                    {
                                        smtp.Send(correo);
                                        enviado = true;
                                    }
                                    catch (Exception ex)
                                    {
                                        err    += "1: " + ex.ToString();
                                        enviado = false;
                                    }
                                    finally
                                    {
                                        correo.To.Clear();
                                        correo.Bcc.Clear();
                                    }
                                    s = 0;          // reseteamos para volver a enviar a otro grupo de correos
                                }
                                else
                                {
                                    enviado = false;
                                }
                            }
                            s++;
                        }
                        // enviar al resto de destinatarios
                        if (enviado == false)
                        {
                            try
                            {
                                smtp.Send(correo);
                            }
                            catch (Exception ex)
                            {
                                err += "2: " + ex.ToString();
                            }
                        }
                    }
                    else
                    {
                        // solo hay un destinatario
                        try
                        {
                            //MailAddress nuevoCorreo = new MailAddress(eMail);
                            //correo.To.Add(nuevoCorreo);
                            correo.To.Add(eMail);
                            smtp.Send(correo);
                        }
                        catch (Exception ex)
                        {
                            err = "3: " + ex.ToString();
                        }
                    }

                    correo.Dispose();
                    smtp.Dispose();
                }

                return(err);
            }
Ejemplo n.º 2
0
            /// <summary>
            /// Recoge un archivo css y lo devuelve sin lineas en blanco
            /// </summary>
            /// <param name="fileName">Nombre del archivo</param>
            /// <param name="folder">Carpeta contenedora en el servidor desde la raiz</param>
            /// <param name="min">Nombre del archivo a minificar sin extension</param>
            /// <returns></returns>
            public static string InlineFile(FileTipe tipo, string fileName, string folder, string min)
            {
                string retorno = string.Empty;

                switch (tipo)
                {
                case FileTipe.css:
                    retorno = "<style type=\"text/css\">";
                    break;

                case FileTipe.javascript:
                    retorno = "<script type=\"text/javascript\">";
                    break;
                }

                try
                {
                    ficheros f    = new ficheros();
                    string   file = f.RutaCompleta(folder) + fileName;
                    if (f.existeFichero(fileName, folder) == true)
                    {
                        StreamReader read    = new StreamReader(file);
                        string       content = read.ReadToEnd();
                        if (tipo == FileTipe.css)
                        {
                            content = content.Replace(Environment.NewLine, " ");
                            content = content.Replace((char)10, ' ');
                            content = content.Replace((char)11, ' ');
                            content = content.Replace((char)12, ' ');
                            content = content.Replace((char)13, ' ');
                            content = content.Replace("\t", "");
                            content = content.Replace("  ", "");
                            content = content.Replace("; ", ";");
                            content = content.Replace(": ", ":");
                            content = content.Replace(" {", "{");
                            content = content.Replace("{ ", "{");
                            content = content.Replace(" }", "}");
                            content = content.Replace("} ", "}");
                        }
                        retorno += content;

                        read.Close();
                    }
                    f = null;
                }
                catch
                {
                    retorno += "";
                }

                switch (tipo)
                {
                case FileTipe.css:
                    retorno += "</style>";
                    break;

                case FileTipe.javascript:
                    retorno += "</script>";
                    break;
                }

                return(retorno);
            }
Ejemplo n.º 3
0
            /// <summary>
            /// Función genérica de envío de correo electrónico
            /// </summary>
            /// <param name="eMail">Mail del destinatario. Se admiten varias direccion separadas por ; La ultima tiene que tener ; para saber que esta formateado</param>
            /// <param name="Asunto">Asunto del envio del correo</param>
            /// <param name="cuerpoTexto">Texto que aparecera en el mensaje. Se admite HTML</param>
            /// <param name="empresaRemitente">Nombre de la empresa o persona que envia el mail</param>
            /// <param name="mailRemitente">Mail del remitente (opcional)</param>
            /// <param name="hostSMTP">Servidor de envio</param>
            /// <param name="userName">Nombre de usuario</param>
            /// <param name="userPass">Password de la cuenta</param>
            /// <param name="numDestinatarios">Numero de destinatarios en cada envio. Defecto 50</param>
            /// <param name="IsBodyHtml">Indica si el texto tiene formato HTML</param>
            /// <param name="filename">Nombre del archivo a enviar</param>
            /// <param name="folder">Carpeta para almacenar el archivo. Adminte ; para separar nombres de archivo</param>
            /// <param name="temp">Indicar si el archiv es temporal o debe ser borrado</param>
            /// <param name="enableSsl">Habilitar la seguridad del servidor</param>
            /// <param name="urlFiles">URI que antecede a la carpeta folder para descargar el link del archivo adjunto</param>
            /// <returns>
            /// Devuelve true si el envío ha sido satisfactorio
            /// </returns>
            public bool EnviarMail(string eMail, string Asunto, string cuerpoTexto,
                                   string empresaRemitente, string mailRemitente, string hostSMTP, string userName,
                                   string userPass, string urlFiles, int numDestinatarios = 10, bool IsBodyHtml = false,
                                   string filename = "", string folder = "mails", bool temp = false, bool enableSsl = false)
            {
                bool bResutado = true;

                // preparar el correo en fotmato HTML
                if (eMail != "")
                {
                    // ENVÍO DEL FORMULARIO DE CONTACTO
                    // variables para la gestión del correo
                    MailMessage correo = new MailMessage();
                    SmtpClient  smtp   = new SmtpClient(hostSMTP);
                    // identificación de usuario
                    NetworkCredential userCredentials = new NetworkCredential(userName, userPass);
                    smtp.EnableSsl   = enableSsl;
                    smtp.Credentials = userCredentials;
                    // agregar remitente
                    MailAddress emailRemitente;
                    try
                    {
                        emailRemitente = new MailAddress(mailRemitente, empresaRemitente);
                    }
                    catch
                    {
                        emailRemitente = new MailAddress("*****@*****.**", "DrUalcman API");
                    }
                    correo.From = emailRemitente;
                    correo.ReplyToList.Add(emailRemitente);
                    // agregar el asunto
                    correo.Subject = Asunto;
                    // propiedades del mail
                    correo.Priority   = MailPriority.Normal;
                    correo.IsBodyHtml = IsBodyHtml;

                    ficheros f        = new ficheros();
                    string   fileHTML = string.Empty;
                    //guardar una copia del correo para poner un enlace a la copia HTML del mismo
                    try
                    {
                        fileHTML = f.guardaDato("mail.html", cuerpoTexto, folder, true);
                    }
                    catch
                    {
                        fileHTML = string.Empty;
                    }

                    cuerpoTexto += Environment.NewLine;

                    //comprobar que no tiene un fichero adjunto
                    if (filename != "")
                    {
                        //adjuntar el archivo fisicamente
                        archivos a = new archivos();
                        folder = a.checkCarpeta(folder);

                        //comprobar que no es una lista de archivo
                        string fichero = string.Empty;
                        string folder2 = "~/" + folder;
                        if (filename.IndexOf(";") > 0)
                        {
                            //es una lista de archivos
                            string[] files = filename.Split(';');
                            foreach (string file in files)
                            {
                                if (f.existeFichero(file.Trim(), folder))
                                {
                                    // solo es un archivo
                                    fichero = folder2 + file.Trim();
                                    correo.Attachments.Add(new Attachment(a.GetStreamFile(fichero), System.IO.Path.GetFileName(fichero)));
                                    //
                                    // se elimina el archivo porque no estara bloqueado y era un archivo temporal
                                    //
                                    if (temp == true)
                                    {
                                        f.borrarArchivo(file.Trim(), folder);
                                    }
                                }
                                else
                                {
                                    cuerpoTexto += basicHTML.a(urlFiles + folder.Replace("~", ""), file.Trim()) + Environment.NewLine;
                                }
                            }
                        }
                        else
                        {
                            if (f.existeFichero(filename.Trim(), folder))
                            {
                                // solo es un archivo
                                fichero = folder2 + filename.Trim();
                                correo.Attachments.Add(new Attachment(a.GetStreamFile(fichero), System.IO.Path.GetFileName(fichero)));
                                //
                                // se elimina el archivo porque no estara bloqueado y era un archivo temporal
                                //
                                if (temp == true)
                                {
                                    f.borrarArchivo(filename.Trim(), folder);
                                }
                            }
                            else
                            {
                                cuerpoTexto += basicHTML.a(urlFiles + folder.Replace("~", ""), filename.Trim());
                            }
                        }
                        a = null;
                    }


                    cuerpoTexto += Environment.NewLine;

                    if (!string.IsNullOrEmpty(fileHTML))
                    {
                        if (IsBodyHtml == true)
                        {
                            //insert link
                            cuerpoTexto += basicHTML.a(knowServerURL() + "/mails/" + fileHTML, "If you cannot read the message well click here to read it online", "_blank");
                        }
                        else
                        {
                            //inser texto where is it the file
                            cuerpoTexto += " If you cannot read the message well click here " + knowServerURL() + "/mails/" + fileHTML + " to read it online (copy the link in your Internet browser)";
                        }
                    }

                    // cuerpo del mail
                    correo.Body = cuerpoTexto;

                    //hacer el envio a todas las direcciones encontradas
                    if (eMail.IndexOf(";") > 0)
                    {
                        // extraer las direcciones
                        string[] Direcciones = eMail.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                        bool seguimiento;
                        if (eMail.IndexOf("invite.trustpilot.com") < 0)
                        {
                            seguimiento = false;
                        }
                        else
                        {
                            seguimiento = true;
                        }

                        byte s       = 1;
                        bool enviado = false;

                        // recorrer las direcciones para realizar el envio
                        foreach (string item in Direcciones)
                        {
                            if (item != "")
                            {
                                //comprobar que tiene @
                                if (item.IndexOf("@") > 0)
                                {
                                    MailAddress nuevoCorreo = new MailAddress(item);
                                    if (seguimiento)
                                    {
                                        if (s < 2)
                                        {
                                            correo.To.Add(nuevoCorreo);
                                        }
                                        else
                                        {
                                            correo.Bcc.Add(nuevoCorreo);
                                        }
                                    }
                                    else
                                    {
                                        correo.Bcc.Add(nuevoCorreo);
                                    }
                                }

                                if (s >= numDestinatarios)
                                {
                                    try
                                    {
                                        smtp.Send(correo);
                                        enviado = true;
                                    }
                                    catch (Exception ex)
                                    {
                                        string err = ex.ToString();
                                        enviado   = false;
                                        bResutado = false;
                                    }
                                    finally
                                    {
                                        correo.To.Clear();
                                        correo.Bcc.Clear();
                                    }
                                    s = 0;          // reseteamos para volver a enviar a otro grupo de correos
                                }
                                else
                                {
                                    enviado = false;
                                }
                            }
                            s++;
                        }
                        // enviar al resto de destinatarios
                        if (enviado == false)
                        {
                            try
                            {
                                smtp.Send(correo);
                            }
                            catch (Exception ex)
                            {
                                string err = ex.ToString();
                                //string datos = hostSMTP + ";" + userName + ";" + userPass + enableSsl.ToString();
                                //DrSeguridad.reportError(ex,err,datos);

                                bResutado = false;
                            }
                        }
                    }
                    else
                    {
                        // solo hay un destinatario
                        try
                        {
                            //MailAddress nuevoCorreo = new MailAddress(eMail);
                            //correo.To.Add(nuevoCorreo);
                            correo.To.Add(eMail);
                            smtp.Send(correo);
                        }
                        catch (Exception ex)
                        {
                            string err = ex.ToString();
                            //string datos = hostSMTP + ";" + userName + ";" + userPass + enableSsl.ToString();
                            //DrSeguridad.reportError(ex, err, datos);

                            bResutado = false;
                        }
                    }
                    //string datos1 = hostSMTP + ";" + userName + ";" + userPass + enableSsl.ToString();
                    //DrSeguridad.reportError(new Exception("nada"), "error mio",datos1);

                    correo.Dispose();
                    smtp.Dispose();
                }

                return(bResutado);
            }
Ejemplo n.º 4
0
            /// <summary>
            /// Recoge un archivo css y lo devuelve sin lineas en blanco
            /// </summary>
            /// <param name="fileName">Nombres de los archivos</param>
            /// <param name="folder">Carpetas contenedoras en el servidor desde la raiz en el mismo orden que los archivos</param>
            /// <param name="min">Nombre del archivo a minificar sin extension</param>
            /// <returns></returns>
            public static string InlineFile(FileTipe tipo, string[] fileName, string[] folder, string min, bool inline = false)
            {
                string retorno = string.Empty;

                string fichero = min;

                ficheros f = new ficheros();

                switch (tipo)
                {
                case FileTipe.css:
                    fichero += ".css";
                    retorno  = "<style>";
                    break;

                case FileTipe.javascript:
                    fichero += ".js";
                    retorno  = "<script>";
                    break;
                }

                string ok = string.Empty;

                try
                {
                    for (int i = 0; i < fileName.Length; i++)
                    {
                        ok += "/* " + folder[i] + "/" + fileName[i];
                        if (string.IsNullOrEmpty(folder[i]))
                        {
                            ok += " (fichero remoto) */";
                            System.Net.WebClient wc = new System.Net.WebClient();
                            string content          = wc.DownloadString(fileName[i]);
                            wc.Dispose();
                            wc = null;
                            if (tipo == FileTipe.css)
                            {
                                content = content.Replace(Environment.NewLine, " ");
                                content = content.Replace((char)10, ' ');
                                content = content.Replace((char)11, ' ');
                                content = content.Replace((char)12, ' ');
                                content = content.Replace((char)13, ' ');
                                content = content.Replace("\t", "");
                                content = content.Replace("  ", " ");
                                content = content.Replace("; ", ";");
                                content = content.Replace(": ", ":");
                                content = content.Replace(" {", "{");
                                content = content.Replace("{ ", "{");
                                content = content.Replace(" }", "}");
                                content = content.Replace("} ", "}");
                            }
                            ok += content;
                        }
                        else
                        {
                            if (f.existeFichero(fileName[i], folder[i]))
                            {
                                ok += " exist */";
                                string       file    = f.RutaCompleta(folder[i]) + fileName[i];
                                StreamReader read    = new StreamReader(file);
                                string       content = read.ReadToEnd();
                                System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex(@"(?=\/\*)(.*)(\*\/)");
                                content = rgx.Replace(content, "");
                                if (tipo == FileTipe.css)
                                {
                                    content = content.Replace(Environment.NewLine, " ");
                                    content = content.Replace((char)10, ' ');
                                    content = content.Replace((char)11, ' ');
                                    content = content.Replace((char)12, ' ');
                                    content = content.Replace((char)13, ' ');
                                    content = content.Replace("\t", "");
                                    content = content.Replace("  ", "");
                                    content = content.Replace("; ", ";");
                                    content = content.Replace(": ", ":");
                                    content = content.Replace(" {", "{");
                                    content = content.Replace("{ ", "{");
                                    content = content.Replace(" }", "}");
                                    content = content.Replace("} ", "}");
                                }
                                ok += content;

                                //retorno += content;
                                read.Close();
                            }
                            else
                            {
                                ok += " not exist */";
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    retorno = "/* exception " + ex.ToString() + "*/";
                }

                if (inline == true)
                {
                    switch (tipo)
                    {
                    case FileTipe.css:
                        retorno += ok + "</style>";
                        break;

                    case FileTipe.javascript:
                        retorno += ok + "</script>";
                        break;
                    }
                }
                else
                {
                    f.guardaDato(fichero, ok, "dat");
                    switch (tipo)
                    {
                    case FileTipe.css:
                        retorno = "<link rel=\"stylesheet\" href=\"" + string.Format("/dat/" + fichero + "?v={0}", CacheExpire(0)) + "\" type=\"text/css\" />";
                        break;

                    case FileTipe.javascript:
                        retorno = "<script src=\"" + string.Format("/dat/" + fichero + "?v={0}", CacheExpire(0)) + "\"></script>";
                        break;
                    }
                }

                f = null;

                return(retorno);
            }