Envio de correo electrónico

Referéncias usadas:

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Net.Mime;


******************************************************************************


///
/// Estructura montada con las distintas partes del mensaje
/// para almacenar el correo electrónico
/// ** Notas: **
///========================================================================
/// [bHTML]= true
/// Se debe montar el cuerpo del mensaje en HTML,
/// y colocar los tags correspondientes a un documento HTML.
/// Por cada imagen, en el cuerpo del mensaje, se debe colocar
/// en su posición el tag: <img src=""cid:logo"">
///========================================================================
/// Si queremos enviar una mail a su destinatario y ocultar todas sus copias
/// debemos poner el parámetro [bOculto] = true y dejar [sBCC]= string.Empty,
/// pasarle todas las direcciones en [sDestinatario]:
/// la primera dirección la del destinatario original
/// y despues cada dirección de copia, todas separadas por un ';'.
///
public struct sCorreoElectronico
{
///
/// string con la descripción y dirección de mail de la persona
/// o entidad que origina el mail
/// [De <dirección de mail>]
/// Ejemplo; "Registro USUARIO <usuario@hotmail.com>"
///
public string sOrigen;
///
/// string con el nombre del emisor a mostrar.
/// [nombre] "Registro USUARIO"
///
public string sNombreOrigen;
///
/// string con la direccion de mail del destinatario.
///
public string sDestinatario;
///
/// string con la lista de las direcciones a quien debemos enviar una copia.
/// Separadas por un ';'.
///
public string sCC;
///
/// string con el asunto del mensaje.
///
public string sAsunto;
///
/// string con el mensaje a enviar.
///
public string sCuerpoMensaje;
///
/// integer para definir la prioridad del mensaje
/// 0. Normal; 1. Baja; 2. Alta
///
public int nPrioridad;
///
/// string con la ruta del archivo adjunto.
///
public string sAdjuntos;
///
/// Servidor SMTP de la cuenta de correo electrónico
/// Ejemplo; 'telefonica.smtp.net'
///
public string sSMTP;
///
/// Nombre del usuario de la cuenta de correo electrónico
/// Ejemplo; 'MiUsuario'
///
public string sUsuario;
///
/// Contraseña del usuario del correo electrónico
/// Ejemplo; 'MiPassWorD11'
///
public string sPassword;
///
/// bool true para indicar que el cuerpo del mensaje será en formato HTML.
///
public bool bHTML;
///
/// es un string montado según:
/// (@'[ID]:[ruta completa del archivo]; [ID]:[ruta completa del archivo]')
/// Ejemplo: D:\Informe\Imgs\logo.gif;logo_pie=D:\Informe\Imgs\logo_pie.gif'
///
public string sListaImagenes;
///
/// Valor para decidir cuando queremos recibir las notificaciones.
/// Enumeración DeliveryNotificationOptions,
/// posibles valores: Delay, Never, None, OnFailure, OnSuccess.
///
public DeliveryNotificationOptions dnNotificaciones;
///
/// bool true si queremos enviar copia/s oculta/s
///
public bool bOculto;
///
/// string montado con las direcciones de copia oculta separadas por un ';'.
///
public string sBCC;
}

La función:

****************************************************************************************************
///
/// Enviar un mail
///
///
Recibe una estructura sCorreoElectronico/// true: si se ha enviado correctamente; false: en caso contrario
public bool EnviarMail(sCorreoElectronico sCE)
{
string[] sDireccion = sCE.sDestinatario.Split(';');
string[] sBC = sCE.sDestinatario.Split(';');
bool bResult = true;
MailMessage mmMensaje = new MailMessage();
SmtpClient scSMTP = new SmtpClient(sCE.sSMTP);
MailAddress maDireccion = new MailAddress(sCE.sOrigen, sCE.sNombreOrigen);

try
{
mmMensaje.From = maDireccion;
mmMensaje.To.Add(sDireccion[0]);

if (sDireccion.Length > 1)
{
foreach (string sDir in sDireccion)
{
if (sCE.bOculto)
mmMensaje.Bcc.Add(sDir);
else
mmMensaje.CC.Add(sDir);
}
}

if (!string.IsNullOrEmpty(sCE.sBCC))
{
sBC = sCE.sBCC.Split(';');

foreach (string sB in sBC) { mmMensaje.Bcc.Add(sB); }
}

mmMensaje.Subject = sCE.sAsunto;
mmMensaje.DeliveryNotificationOptions = sCE.dnNotificaciones;
mmMensaje.IsBodyHtml = sCE.bHTML;

if (sCE.bHTML && !string.IsNullOrEmpty(sCE.sListaImagenes))
{
AlternateView avVista =
AlternateView.CreateAlternateViewFromString(sCE.sCuerpoMensaje, null, ypeNames.Text.Html);
string[] sImagenes = sCE.sListaImagenes.Split(';');
LinkedResource[] lrImagen = new LinkedResource[sImagenes.Length - 1];

for (int nL = 0; nL > sImagenes.Length - 1; nL++)
{
string[] sImg = sCE.sListaImagenes.Split('=');

lrImagen[nL] = new LinkedResource(sImg[1], MediaTypeNames.Image.Gif);
lrImagen[nL].ContentId = sImg[0];

avVista.LinkedResources.Add(lrImagen[nL]);
}

mmMensaje.AlternateViews.Add(avVista);
}

mmMensaje.Body = sCE.sCuerpoMensaje;

if (!string.IsNullOrEmpty(sCE.sAdjuntos))
{
Attachment aAdjunto = new Attachment(sCE.sAdjuntos);
mmMensaje.Attachments.Add(aAdjunto);
}

switch (sCE.nPrioridad)
{
case 1: mmMensaje.Priority = MailPriority.Low; break;
case 2: mmMensaje.Priority = MailPriority.High; break;
default: mmMensaje.Priority = MailPriority.Normal; break;
}

scSMTP.Credentials = new NetworkCredential(sCE.sUsuario, sCE.sPassword);
scSMTP.Send(mmMensaje);
}
catch (Exception ex)
{
bResult = false;
}

return bResult;
}



Descifra un valor encriptado con la función CifrarValor


Referencias usadas:

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;


Descifra un valor encriptado con la función anterior, 
debemos pasarles las mismas claves.


*********************************************************************************


public string DescifrarValor(string sValor)
{
  string sResultado = string.Empty;
  TripleDESCryptoServiceProvider oTripleDESC = 
    new TripleDESCryptoServiceProvider();
  try
  {
    byte[] bIN = Convert.FromBase64String(sValor);
    using (MemoryStream oOutStream = new MemoryStream())
    {
      CryptoStream oCryptoStream =
        new CryptoStream(oOutStream, 
         oTripleDESC.CreateDecryptor(bClave, bVector), 
          CryptoStreamMode.Write);

      oCryptoStream.Write(bIN, 0, bIN.Length);
      oCryptoStream.FlushFinalBlock();

      sResultado = Encoding.UTF8.GetString(oOutStream.ToArray());
    }
  }
  catch (Exception ex)
  {
    throw new System.Exception(ex.Message, ex.InnerException);
  }

  return sResultado;
}

Encriptar un texto

Referencias usadas:

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;



Debemos declarar y no perder estas dos variables:

byte[] bClave = 
  Encoding.UTF8.GetBytes("b%`^x&amH~a!x@Y#c$p;J*M-e^L_");
byte[] bVector = 
  Encoding.UTF8.GetBytes("p$ctuW^%");

La función encripta una cadena de texto:

***********************************************************************
public string CifrarValor(string sValor)
{
  string sResultado = string.Empty;
  TripleDESCryptoServiceProvider oTripleDESC = 
     new TripleDESCryptoServiceProvider();
           
  try
  {
    byte[] bIN = Encoding.UTF8.GetBytes(sValor);
    using (MemoryStream oOutStream = new MemoryStream())
    {
      CryptoStream oCryptoStream =
        new CryptoStream(oOutStream, 
             oTripleDESC.CreateEncryptor(bClave, bVector),
                 CryptoStreamMode.Write);
                   
      oCryptoStream.Write(bIN, 0, bIN.Length);
      oCryptoStream.FlushFinalBlock();

      sResultado = Convert.ToBase64String(oOutStream.ToArray());
    }
  }
  catch (Exception ex)
  {
    throw new System.Exception(ex.Message, ex.InnerException);
   }

  return sResultado;
}

Leer una clave en el registro


Referencias usadas:

using System;
using Microsoft.Win32;


Devuelve el valor de una clave determinada del registro de windows.


*******************************************************************************


public string DevuelveClaveDelRegistro(string sRuta, string sClave)
{
  string sResultado = string.Empty;
  RegistryKey obReg = 
        Registry.LocalMachine.OpenSubKey("SOFTWARE")
                      .OpenSubKey(sRuta, true);
             
  if (obReg != null)
  {
    if (obReg.GetValue(sClave) != null)
      sResultado = obReg.GetValue(sClave).ToString();
  }

  return sResultado;
}

Crear una clave en el registro


Referencias usadas:

using System;
using Microsoft.Win32;


Crear una clave con su valor en la carpeta de destino
dentro del registro de windows.

Deberemos incluir:
using Microsoft.Win32;

**********************************************************************************

public bool CrearClave(string sRuta, string sClave, string sValor)
{
  bool Result = false;
  RegistryKey obReg =
    Registry.LocalMachine.OpenSubKey("SOFTWARE")
                                               .OpenSubKey(sRuta, true);
  if (obReg == null)
    obReg =
      Registry.LocalMachine.OpenSubKey("SOFTWARE", true)
                                                     .CreateSubKey(sRuta);

  try
  {
    obReg.SetValue(sClave, sValor);
    obReg.Close();

    Result = true;
  }
  catch (Exception ex)
  {
    throw new System.Exception(ex.Message, ex.InnerException);
  }
  return Result;
}

Validar un string


Referencias usadas:

using System.Text.RegularExpressions;


Esta función recibe dos strings como parámetros, el primero 
es el string a validar, el segundo es la cadena origen.


**************************************************************************


public bool ValidaString(string sTexto, string sPattern)
{
   Regex reg = new Regex(sPattern);
   bool Respuesta = false;
          
   try
   {
      if (reg.IsMatch(sTexto))
         Respuesta = true;
   }
   catch
   {
      Respuesta =  false;
   }
   finally
   {
      reg = null;
   }

   return Respuesta;
}

***************************************************************************


Para validar una dirección de correo electrónico (mail):


*************************************************************************

public bool ComprobarMail(string sTexto)

   string sModelo = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
   return ValidaString(sTexto, sModelo);
}

Comprobar controles

Referencias usadas:

using System.Windows.Forms;

Recorre la colección de controles del objeto contenedor
para comprobar si la propiedad Text es vacia o es nula.
true: si todos tienen la propiedad Text rellena; false: en caso contrario

************************************************************************

public bool ComprobarDatosControles(Control contenedor)
{
   foreach (Control control in contenedor.Controls)
   {
      if (control.GetType() == typeof(TextBox) ||
            control.GetType() == typeof(ComboBox))
      {
         if (string.IsNullOrEmpty(control.Text))
            return false;
       }
    }
    return true;
}