/// <summary> /// Función que permite enviar un correo /// </summary> /// <param name="from">Correo Origen</param> /// <param name="to">Correo Destino</param> /// <param name="subject">Asunto</param> /// <param name="body">Cuerpo del correo</param> /// <param name="bodyFormat">Formato del Cuerpo, puede tomar valores de la enumeración TipoCorreo</param> /// <param name="SMTPserver">Servidor de Correo</param> /// <param name="rutaArchivo">Ruta de archivo adjunto (Si existe)</param> /// <param name="URLBase">URL Base para aplicación de objetos embebidos y hojas de estilo</param> /// <param name="password">Password del correo desde el cual se envia</param> /// <returns>bool true si el envio se hizo satisfactoriamente; false si ocurrio algun error durante el envio</returns> public bool EnviarMail(string from, string to, string subject, string body, TipoCorreo bodyFormat, string SMTPserver, string rutaArchivo, string URLBase, string password) { bool error = false; try { SmtpClient client = new SmtpClient(SMTPserver, 587); //SmtpClient client = new SmtpClient("smtp.gmail.com", 587); client.EnableSsl = true; client.Credentials = new NetworkCredential(from, password); MailMessage oMsg = new MailMessage(from, to, subject, body); oMsg.IsBodyHtml = bodyFormat == TipoCorreo.HTML; if (rutaArchivo != "") { oMsg.Attachments.Add(new Attachment(rutaArchivo)); } if (URLBase != "") { oMsg.Headers.Add("Content-Base", URLBase); } client.Send(oMsg); client.Dispose(); } catch (Exception e) { error = true; mensajes = e.ToString() + "\n" + SMTPserver; } return(error); }
/* * imagenes */ public int enviarMail(string to, string subject, string body, TipoCorreo bodyFormat, ArrayList listaBytes, ArrayList listaNombres) { string from = ConfigurationManager.AppSettings["EmailFrom"]; string SMTPserver = ConfigurationManager.AppSettings["MailServer"]; int SMTPport = Convert.ToInt32(ConfigurationManager.AppSettings["MailServerPort"]); string password = ConfigurationManager.AppSettings["PasswordEMail"]; int resultado = 0; try { SmtpClient client = new SmtpClient(SMTPserver, SMTPport); client.EnableSsl = true; //comentar para caso normal. quitar comment para gmail. client.UseDefaultCredentials = false; //comentar caso normal. quitar comment para gmail. client.Credentials = new NetworkCredential(from, password); MailMessage oMsg = new MailMessage(from, to, subject, body); oMsg.IsBodyHtml = bodyFormat == TipoCorreo.HTML; oMsg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; if (listaNombres != null) { for (int i = 0; i < listaBytes.Count; i++) { if (listaNombres[i].ToString().EndsWith(".png") || listaNombres[i].ToString().EndsWith(".PNG")) { oMsg.Attachments.Add(new Attachment(new MemoryStream((byte[])listaBytes[i]), listaNombres[i].ToString() + ".png")); } if (listaNombres[i].ToString().EndsWith(".jpg") || listaNombres[i].ToString().EndsWith(".JPG")) { oMsg.Attachments.Add(new Attachment(new MemoryStream((byte[])listaBytes[i]), listaNombres[i].ToString() + ".jpg")); } } } else { for (int i = 0; i < listaBytes.Count; i++) { if (listaNombres[i].ToString().EndsWith(".png") || listaNombres[i].ToString().EndsWith(".PNG")) { oMsg.Attachments.Add(new Attachment(new MemoryStream((byte[])listaBytes[i]), "pngimagen_" + i + ".png")); } if (listaNombres[i].ToString().EndsWith(".jpg") || listaNombres[i].ToString().EndsWith(".JPG")) { oMsg.Attachments.Add(new Attachment(new MemoryStream((byte[])listaBytes[i]), "jpgimagen_" + i + ".jpg")); } } } client.Send(oMsg); client.Dispose(); resultado = 1; } catch (Exception e) { resultado = 0; throw new Exception(String.Format("Error al enviar el correo [From:{0};To:{1};SMTP:{2}:{3}] excepcion: {4}", from, to, SMTPserver, SMTPport, e.Message)); } return(resultado); }
public static void SendEmail(System.Net.Mail.MailMessage m, TipoCorreo tipo) { string NetWorkEmail = System.Configuration.ConfigurationManager.AppSettings["NetEmail"]; string NetWorkPassword = System.Configuration.ConfigurationManager.AppSettings["NetPassword"]; if (tipo == TipoCorreo.ReseteoDeClave) { m.From = new MailAddress(NetWorkEmail, "Nueva clave " + AboutInfo.Instance.ProductName); } else if (tipo == TipoCorreo.Informativo) { m.From = new MailAddress(NetWorkEmail, "Informativo " + AboutInfo.Instance.ProductName); } SmtpClient smtp = new SmtpClient(); smtp.Host = System.Configuration.ConfigurationManager.AppSettings["NetHost"]; smtp.Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["NetPort"]); smtp.EnableSsl = false; smtp.UseDefaultCredentials = false; smtp.Credentials = new NetworkCredential(NetWorkEmail, NetWorkPassword); SendEmailDelegate sd = new SendEmailDelegate(smtp.Send); AsyncCallback cb = new AsyncCallback(SendEmailResponse); sd.BeginInvoke(m, cb, sd); }
public ActionResult DeleteConfirmed(int id) { TipoCorreo tipoCorreo = db.TipoCorreos.Find(id); db.TipoCorreos.Remove(tipoCorreo); db.SaveChanges(); return(RedirectToAction("Index")); }
public static void Enviar(System.Net.Mail.MailMessage email, TipoCorreo tipo) { /* try * { SendEmail(email, tipo); } * catch * { throw new NotImplementedException("No se pudo enviar correo. Favor comunicarse con informática");} * */ }
public ActionResult Edit([Bind(Include = "TipoCorreoId,Correo,ClienteId")] TipoCorreo tipoCorreo) { if (ModelState.IsValid) { db.Entry(tipoCorreo).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.ClienteId = new SelectList(db.Clientes, "ClienteId", "ApeMat", tipoCorreo.ClienteId); return(View(tipoCorreo)); }
public ActionResult Create([Bind(Include = "TipoCorreoId,Correo,ClienteId")] TipoCorreo tipoCorreo) { if (ModelState.IsValid) { db.TipoCorreos.Add(tipoCorreo); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.ClienteId = new SelectList(db.Clientes, "ClienteId", "ApeMat", tipoCorreo.ClienteId); return(View(tipoCorreo)); }
// GET: TipoCorreos/Details/5 public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } TipoCorreo tipoCorreo = db.TipoCorreos.Find(id); if (tipoCorreo == null) { return(HttpNotFound()); } return(View(tipoCorreo)); }
// GET: TipoCorreos/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } TipoCorreo tipoCorreo = db.TipoCorreos.Find(id); if (tipoCorreo == null) { return(HttpNotFound()); } ViewBag.ClienteId = new SelectList(db.Clientes, "ClienteId", "ApeMat", tipoCorreo.ClienteId); return(View(tipoCorreo)); }
/* * Excel */ public static int enviarMail(string to, string subject, string body, TipoCorreo bodyFormat, byte[] bytes) { string tipoArchivo = ""; string from = ConfigurationManager.AppSettings["EmailFrom"]; string SMTPserver = ConfigurationManager.AppSettings["MailServer"]; int SMTPport = Convert.ToInt32(ConfigurationManager.AppSettings["MailServerPort"]); string password = ConfigurationManager.AppSettings["PasswordEMail"]; int resultado = 0; try { SmtpClient client = new SmtpClient(SMTPserver, SMTPport); client.EnableSsl = true; //comentar para caso normal. quitar comment para gmail. client.UseDefaultCredentials = false; //comentar caso normal. quitar comment para gmail. client.Credentials = new NetworkCredential(from, password); MailMessage oMsg = new MailMessage(from, to, subject, body); oMsg.IsBodyHtml = bodyFormat == TipoCorreo.HTML; oMsg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; //if(dsExcel != null && dsExcel.Tables[0].Rows.Count > 0) //{ // tipoArchivo = "GridView.xlsx"; //} //else //{ // tipoArchivo = "imgAdjunta.png"; //} oMsg.Attachments.Add(new Attachment(new MemoryStream(bytes), "GridView.xlsx")); client.Send(oMsg); client.Dispose(); resultado = 1; } catch (Exception e) { throw new Exception(String.Format("Error al enviar el correo [From:{0};To:{1};SMTP:{2}:{3}] excepcion: {4}", from, to, SMTPserver, SMTPport, e.Message)); } return(resultado); }
public int EnviarMail(string to, string subject, string body, TipoCorreo bodyFormat, string rutaArchivo) { string from = ConfigurationManager.AppSettings["EmailFrom"]; string SMTPserver = ConfigurationManager.AppSettings["MailServer"]; int SMTPport = Convert.ToInt32(ConfigurationManager.AppSettings["MailServerPort"]); string password = ConfigurationManager.AppSettings["PasswordEMail"]; int resultado = 0; try { SmtpClient client = new SmtpClient(SMTPserver, SMTPport); client.EnableSsl = true; //comentar para caso normal. quitar comment para gmail. client.UseDefaultCredentials = false; //comentar caso normal. quitar comment para gmail. client.Credentials = new NetworkCredential(from, password); //client.Timeout = 10000; //client.DeliveryMethod = SmtpDeliveryMethod.Network; MailMessage oMsg = new MailMessage(from, to, subject, body); oMsg.IsBodyHtml = bodyFormat == TipoCorreo.HTML; oMsg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; if (rutaArchivo != "") { oMsg.Attachments.Add(new Attachment(rutaArchivo)); } client.Send(oMsg); client.Dispose(); resultado = 1; } catch (Exception e) { throw new Exception(String.Format("Error al enviar el correo [From:{0};To:{1};SMTP:{2}:{3}] excepcion: {4}", from, to, SMTPserver, SMTPport, e.Message)); } return(resultado); }
public async void EnvioCorreo(TipoCorreo tipoCorreo) { var Ruta = string.Empty; var Cadena = new String[] { string.Format("{0} {1} {2}", Nombres, ApellidoPaterno, ApellidoMaterno), Codigo, DateTime.Today.ToString("D"), DateTime.Today.AddDays(90).ToString("D") }; var Contenido = new ContenidoMail(); switch (tipoCorreo) { case TipoCorreo.UsuarioNuevoExterno: Ruta = "ErickOrlando.Seguridad.Negocio.Editables.Usuarios.PlantillaCorreo.htm"; Contenido.Asunto = string.Format(Properties.Resources.msgAsuntoActivacion, this.Codigo); break; case TipoCorreo.UsuarioNuevoInterno: Ruta = "ErickOrlando.Seguridad.Negocio.Editables.Usuarios.PlantillaCorreoUsuarioAD.htm"; Contenido.Asunto = string.Format(Properties.Resources.msgAsuntoActivacion, this.Codigo); Cadena = new String[] { Nombres, Codigo, Dominio }; break; case TipoCorreo.CambioClave: Ruta = "ErickOrlando.Seguridad.Negocio.Editables.Usuarios.PlantillaContrasena.htm"; Contenido.Asunto = string.Format(Properties.Resources.msgAsuntoRestablecimiento, this.Codigo); break; } try { TextReader texto = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(Ruta)); #region Configuracion del Correo var crypto = new SimpleInteroperableEncryption(); Contenido.RemitenteMail = ConfigurationManager.AppSettings["RemitenteEmail"]; Contenido.RemitenteNombre = ConfigurationManager.AppSettings["RemitenteNombre"]; Contenido.Servidor = ConfigurationManager.AppSettings["SMTPServer"]; Contenido.Puerto = int.Parse(ConfigurationManager.AppSettings["PuertoSMTP"]); Contenido.Credenciales = new System.Net.NetworkCredential( crypto.Decrypt(ConfigurationManager.AppSettings["CredencialUser"]), crypto.Decrypt(ConfigurationManager.AppSettings["CredencialPass"])); Contenido.UsarSSL = true; Contenido.CuerpoMensaje = texto.ReadToEnd(); Contenido.ListaDestinatarios.Add(Correo); Contenido.ArrayValores = Cadena; Contenido.Html = true; texto.Close(); #endregion #region Contenido del Correo using (MailMessage mail = new MailMessage()) { mail.From = new MailAddress(Contenido.RemitenteMail, Contenido.RemitenteNombre); foreach (var Destinatario in Contenido.ListaDestinatarios) { mail.To.Add(Destinatario); } foreach (var Destinatario in Contenido.ListaDestinatariosCC) { mail.CC.Add(Destinatario); } foreach (var Destinatario in Contenido.ListaDestinatariosBCC) { mail.Bcc.Add(Destinatario); } var CuerpoHTML = new StringBuilder(); if (Contenido.ArrayValores.Length > 0) { CuerpoHTML.AppendFormat(Contenido.CuerpoMensaje, Contenido.ArrayValores); } else { CuerpoHTML.Append(Contenido.CuerpoMensaje); } CuerpoHTML.AppendLine(); CuerpoHTML.AppendLine(); CuerpoHTML.AppendLine(); CuerpoHTML.Append(Contenido.Html ? Contenido.PieDeCorreoHTML : Contenido.PieDeCorreo); mail.Subject = Contenido.Asunto; mail.Body = CuerpoHTML.ToString(); mail.IsBodyHtml = Contenido.Html; //Limpiamos el StringBuilder CuerpoHTML.Length = 0; var smtp = new SmtpClient(); smtp.Host = Contenido.Servidor; if (Contenido.Puerto.HasValue) { smtp.Port = Contenido.Puerto.Value; } if (Contenido.Credenciales != null) { smtp.Credentials = Contenido.Credenciales; } else { smtp.UseDefaultCredentials = true; } if (Contenido.Servidor.ToLower() == "localhost" || Contenido.Servidor == "127.0.0.1") { smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis; } if (!string.IsNullOrEmpty(Contenido.DirectorioRecojoIIS)) { smtp.PickupDirectoryLocation = Contenido.DirectorioRecojoIIS; } smtp.EnableSsl = Contenido.UsarSSL; //await smtp.SendMailAsync(mail); await smtp.SendMailAsync(mail); } #endregion } catch (SmtpException ex) { var msg = string.Format("{0}\n{1}", ex.Message, ex.InnerException == null ? string.Empty : ex.InnerException.Message); System.Diagnostics.Trace.WriteLine(msg); } }
public async void EnvioCorreo(TipoCorreo tipoCorreo) { var Ruta = string.Empty; var Cadena = new String[] { string.Format("{0} {1} {2}", Nombres, ApellidoPaterno, ApellidoMaterno), Codigo, DateTime.Today.ToString("D"), DateTime.Today.AddDays(90).ToString("D") }; var Contenido = new ContenidoMail(); switch (tipoCorreo) { case TipoCorreo.UsuarioNuevoExterno: Ruta = "ErickOrlando.Seguridad.Negocio.Editables.Usuarios.PlantillaCorreo.htm"; Contenido.Asunto = string.Format(Properties.Resources.msgAsuntoActivacion, this.Codigo); break; case TipoCorreo.UsuarioNuevoInterno: Ruta = "ErickOrlando.Seguridad.Negocio.Editables.Usuarios.PlantillaCorreoUsuarioAD.htm"; Contenido.Asunto = string.Format(Properties.Resources.msgAsuntoActivacion, this.Codigo); Cadena = new String[] { Nombres, Codigo, Dominio }; break; case TipoCorreo.CambioClave: Ruta = "ErickOrlando.Seguridad.Negocio.Editables.Usuarios.PlantillaContrasena.htm"; Contenido.Asunto = string.Format(Properties.Resources.msgAsuntoRestablecimiento, this.Codigo); break; } try { TextReader texto = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(Ruta)); #region Configuracion del Correo var crypto = new SimpleInteroperableEncryption(); Contenido.RemitenteMail = ConfigurationManager.AppSettings["RemitenteEmail"]; Contenido.RemitenteNombre = ConfigurationManager.AppSettings["RemitenteNombre"]; Contenido.Servidor = ConfigurationManager.AppSettings["SMTPServer"]; Contenido.Puerto = int.Parse(ConfigurationManager.AppSettings["PuertoSMTP"]); Contenido.Credenciales = new System.Net.NetworkCredential( crypto.Decrypt(ConfigurationManager.AppSettings["CredencialUser"]), crypto.Decrypt(ConfigurationManager.AppSettings["CredencialPass"])); Contenido.UsarSSL = true; Contenido.CuerpoMensaje = texto.ReadToEnd(); Contenido.ListaDestinatarios.Add(Correo); Contenido.ArrayValores = Cadena; Contenido.Html = true; texto.Close(); #endregion #region Contenido del Correo using (MailMessage mail = new MailMessage()) { mail.From = new MailAddress(Contenido.RemitenteMail, Contenido.RemitenteNombre); foreach (var Destinatario in Contenido.ListaDestinatarios) mail.To.Add(Destinatario); foreach (var Destinatario in Contenido.ListaDestinatariosCC) mail.CC.Add(Destinatario); foreach (var Destinatario in Contenido.ListaDestinatariosBCC) mail.Bcc.Add(Destinatario); var CuerpoHTML = new StringBuilder(); if (Contenido.ArrayValores.Length > 0) CuerpoHTML.AppendFormat(Contenido.CuerpoMensaje, Contenido.ArrayValores); else CuerpoHTML.Append(Contenido.CuerpoMensaje); CuerpoHTML.AppendLine(); CuerpoHTML.AppendLine(); CuerpoHTML.AppendLine(); CuerpoHTML.Append(Contenido.Html ? Contenido.PieDeCorreoHTML : Contenido.PieDeCorreo); mail.Subject = Contenido.Asunto; mail.Body = CuerpoHTML.ToString(); mail.IsBodyHtml = Contenido.Html; //Limpiamos el StringBuilder CuerpoHTML.Length = 0; var smtp = new SmtpClient(); smtp.Host = Contenido.Servidor; if (Contenido.Puerto.HasValue) smtp.Port = Contenido.Puerto.Value; if (Contenido.Credenciales != null) smtp.Credentials = Contenido.Credenciales; else smtp.UseDefaultCredentials = true; if (Contenido.Servidor.ToLower() == "localhost" || Contenido.Servidor == "127.0.0.1") smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis; if (!string.IsNullOrEmpty(Contenido.DirectorioRecojoIIS)) smtp.PickupDirectoryLocation = Contenido.DirectorioRecojoIIS; smtp.EnableSsl = Contenido.UsarSSL; //await smtp.SendMailAsync(mail); await smtp.SendMailAsync(mail); } #endregion } catch (SmtpException ex) { var msg = string.Format("{0}\n{1}", ex.Message, ex.InnerException == null ? string.Empty : ex.InnerException.Message); System.Diagnostics.Trace.WriteLine(msg); } }