miércoles, 19 de marzo de 2008

Metodo para enviar correo desde .NET

public string EnviaMail(string from, string to, string cc, string bcc, string subject, string body)
{
 try
 {
   string host = System.Configuration.ConfigurationManager.AppSettings["Host"];
   string usuario = System.Configuration.ConfigurationManager.AppSettings["Usuario"];
   string password = System.Configuration.ConfigurationManager.AppSettings["Password"];
   if (string.IsNullOrEmpty(body))
   body = subject;
   using (System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(from, to, subject, body))
   {
      string[] addresses;
      if (!string.IsNullOrEmpty(to))
      {
       addresses = to.Split(';');
       for (int con = 0; con < addresses.Length; con++)
       message.CC.Add(addresses[con]);
      }
      if (!string.IsNullOrEmpty(cc))
      {
       addresses = cc.Split(';');
       for (int con = 0; con < addresses.Length; con++)
       message.CC.Add(addresses[con]);
      }
      if (!string.IsNullOrEmpty(bcc))
      {
       addresses = bcc.Split(';');
       for (int con = 0; con < addresses.Length; con++)
       message.Bcc.Add(addresses[con]);
      }
      message.IsBodyHtml = true;
      System.Net.Mail.SmtpClient mail = new System.Net.Mail.SmtpClient(host);
      if (!string.IsNullOrEmpty(usuario))
       mail.Credentials = new System.Net.NetworkCredential(usuario, password);
      mail.Send(message);
   }
   return "Mensaje enviado correctamente";
   }
   catch (System.Net.Mail.SmtpException ex)
   {
      return ex.Message;
   }
}

No hay comentarios: