/** * */ public static string exibirCopiasOcultas(this LogEmail Email) { var listaDestinos = Email.listaEmailDestino.Where(x => x.flagCopia == "N" && x.flagCopiaOculta == "S").ToList(); string html = htmlContato(listaDestinos); return(html); }
private async Task <LogEmail> createEmail(string subject, string to, string body) { LogEmail email = new LogEmail(); email.Subject = subject; email.Body = body; email.To = to; email.CreatedDate = DateTime.Now; email.Sent = false; this.Db.LogEmails.Add(email); // Sending Email TODO EmailUtility emailutility = new EmailUtility(this.emailConfig); var data = await emailutility.SendEmailAsync(email.To, subject, body); if (string.IsNullOrWhiteSpace(data)) { email.Sent = true; } else { email.Error = data; } await this.Db.SaveChangesAsync(); return(email); }
/// <summary> /// Logs the email. /// </summary> /// <param name="ex">The email to log.</param> /// <returns>id of email logged (-1 if log fails)</returns> public static long LogEmail(string toAddresses, string ccAddresses, string bccAddresses, string subject, string body, string fromAddress, string procedureUsed, string errorMessage) { long id = -1; try { //Some temp variables to remember the IDs. bool saved = false; string errorMsg = string.Empty; LogEmail le = null; //Prepare the email to be logged to the database. le = new LogEmail(); le.StatusId = 1; le.Sender = fromAddress; le.ToAddresses = toAddresses; le.CcAddresses = ccAddresses; le.BccAddresses = bccAddresses; le.Subject = subject; le.Body = body; le.Procedure_Used = procedureUsed; le.ErrorMessage = errorMessage; id = le.Add(out saved, out errorMsg); } catch (Exception) { } return(id); }
public LogEmail GetById(int id) { LogEmail objLogEmail = null; String sql = "SELECT * FROM TH_LOG_EMAIL WHERE IDLOGEMAIL = @codigo"; OleDbParameter codigo = UtilDA.SetParameters("@codigo", OleDbType.Integer, id); using (var dtr = UtilDA.ExecuteReader(cmd, CommandType.Text, sql, cnx, codigo)) { objLogEmail = new LogEmail(); objLogEmail.IdLog = DataConvert.ToInt(dtr["IdLogEmail"]); objLogEmail.CorreoDestino = DataConvert.ToString(dtr["CorreoDestino"]); objLogEmail.CorreoDestinoCC = DataConvert.ToString(dtr["CorreoDestinoCC"]); objLogEmail.FechaEnvio = DataConvert.ToDateTime(dtr["FechaEnvio"]); objLogEmail.Mensaje = DataConvert.ToString(dtr["Mensaje"]); objLogEmail.Asunto = DataConvert.ToString(dtr["Asunto"]); objLogEmail.Estado = DataConvert.ToString(dtr["Estado"]); objLogEmail.Descripcion = DataConvert.ToString(dtr["Descripcion"]); objLogEmail.Intento = DataConvert.ToInt32(dtr["Intento"]); objLogEmail.FechaCreacion = DataConvert.ToDateTime(dtr["FechaCrea"]); objLogEmail.UsuarioCreacion = DataConvert.ToString(dtr["UserCrea"]); objLogEmail.FechaModificacion = DataConvert.ToDateTime(dtr["FechaMod"]); objLogEmail.UsuarioModificacion = DataConvert.ToString(dtr["UserMod"]); objLogEmail.MensajeImagen = DataConvert.ToString(dtr["MensajeImage"]); objLogEmail.IdObra = DataConvert.ToInt(dtr["IdObra"]); } UtilDA.Close(cnx); return(objLogEmail); }
public ActionResult visualizarEmail(int id, bool flagConfiavel = false) { LogEmail OEmail = this.OEmailBL.carregar(id); ViewBag.flagConfiavel = flagConfiavel; return(View(OEmail)); }
public static void SendEmail(string subjectTemplate, string bodyTemplate, string from, string[] to, string[] cc, string[] bcc, string stateCode, string countyCode, string localCode, string contact, string email, string title, string phone, string electionKey, string officeKey, string politicianKey, string partyKey, string partyEmail, int visitorId, int donorId, int logBatchId = -1, int retryMax = 3) { var wasSent = false; var subject = string.Empty; var body = string.Empty; string errorMessage = null; try { var substitution = GetSubstititionsForEmail(stateCode, countyCode, localCode, contact, email, title, phone, electionKey, officeKey, politicianKey, partyKey, partyEmail, visitorId, donorId); subject = substitution.Substitute(subjectTemplate); body = substitution.Substitute(bodyTemplate); if (to.Length <= 0) { return; } SendEmail(subject, body, from, to, cc, bcc, retryMax); wasSent = true; } catch (Exception e) { errorMessage = e.Message; var inner = e.InnerException; while (inner != null) { errorMessage += "::" + inner.Message; inner = inner.InnerException; } throw; } finally { try { if (logBatchId >= 0) { foreach (var toAddr in to) { LogEmail.Insert(logBatchId, DateTime.UtcNow, wasSent, stateCode, countyCode, localCode, electionKey, officeKey, politicianKey, visitorId, contact, toAddr, subject, body, 0, false, errorMessage); } } } // ReSharper disable once EmptyGeneralCatchClause catch { } } }
/** * */ public static string exibirMensagem(this LogEmail Email, bool flagConfiavel = false) { string mensagem = Email.corpoMensagem.Replace("script", "#script#"); if (!flagConfiavel) { mensagem = mensagem.Replace("http", "#http#"); } mensagem = mensagem.Replace("\n", "<br />"); return(mensagem); }
private void dgvEmail_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (proceso) { proceso = false; if (e.ColumnIndex == 7) { LogEmail logEmail = (LogEmail)dgvEmail.CurrentRow.DataBoundItem; FowardEmails fowardEmail = new FowardEmails(logEmail); fowardEmail.ShowDialog(); EnlazarGrilla(); } proceso = true; } }
/** * */ public static string exibirRemetente(this LogEmail Email) { string remetente = ""; if (!String.IsNullOrEmpty(Email.nomeRemetente)) { remetente = String.Concat(Email.nomeRemetente, " <", Email.emailRemetente, "> "); } else { remetente = Email.emailRemetente; } return(remetente); }
public static void Log_Email(string email, string rotina, Status status, string infoAdicionais) { LogEmail logEmail = new LogEmail { Data = DateTime.Now.ToString("yyyyMMdd"), Hora = DateTime.Now.ToString("HH:mm:ss.fff"), Email = email, Rotina = rotina, Status = status.ToString(), InfoAdicionais = infoAdicionais, Aplicacao = Service_Config.NomeServico }; LogDAO logDAO = new LogDAO(); logDAO.RegistrarLogEmail(logEmail, ConexaoGestor.Conexao()); }
/** * Conectar no servidor para fazer o download dos e-mails */ public async Task <List <LogEmail> > downloadAsync(string host, int nroPorta, bool flagSSL, string usuario, string senha, List <string> emailJaBaixados) { //Criar lista para armazenar as novas mensagens. List <LogEmail> listaNovasMensagens = new List <LogEmail>(); Task <List <LogEmail> > OTask = new Task <List <LogEmail> >(() => { using (MailKit.Net.Pop3.Pop3Client client = new MailKit.Net.Pop3.Pop3Client()) { client.Connect(host, nroPorta, flagSSL); client.Authenticate(usuario, senha); client.AuthenticationMechanisms.Remove("XOAUTH2"); int limit = client.Count; int lastcount; for (int i = 0; i < limit; i++) { lastcount = (limit - 1) - i; var NovaMensagem = client.GetMessage(lastcount); LogEmail NovoEmail = this.mapper(NovaMensagem, lastcount); bool flagSucesso = this.salvarEmail(NovoEmail); if (flagSucesso) { client.DeleteMessage(lastcount); } } client.Disconnect(true); } return(listaNovasMensagens); }); OTask.Start(); try { listaNovasMensagens = await OTask; } catch (Exception ex) { UtilLog.saveError(ex.GetBaseException(), String.Concat(ex.Message, "\n", ex.StackTrace)); } return(listaNovasMensagens); }
public ActionResult restaurarMensagem(int id) { LogEmail OEmail = this.OEmailBL.carregar(id); if (OEmail == null) { return(Json(new { flagErro = true, message = "Registro não localizado" }, JsonRequestBehavior.AllowGet)); } if (!OEmail.dtExclusao.HasValue) { return(Json(new { flagErro = true, message = "Mensagem não está na lixeira no momento." }, JsonRequestBehavior.AllowGet)); } this.OEmailBL.restaurar(id); return(Json(new { flagErro = false, message = "Mensagem recuperada da lixeira com sucesso!" }, JsonRequestBehavior.AllowGet)); }
public ActionResult enviarParaLixeira(int id) { LogEmail OEmail = this.OEmailBL.carregar(id); if (OEmail == null) { return(Json(new { flagErro = true, message = "Registro não localizado" }, JsonRequestBehavior.AllowGet)); } if (OEmail.dtExclusao.HasValue) { return(Json(new { flagErro = true, message = "Mensagem já na lixeira." }, JsonRequestBehavior.AllowGet)); } this.OEmailBL.lixeira(id); return(Json(new { flagErro = false, message = "Mensagem enviada para a lixeira com sucesso!" }, JsonRequestBehavior.AllowGet)); }
public ActionResult registrarVisualizacao(int id) { LogEmail OEmail = this.OEmailBL.carregar(id); if (OEmail == null) { return(Json(new { flagErro = true, message = "Registro não localizado" }, JsonRequestBehavior.AllowGet)); } if (OEmail.dtPrimeiraAbertura.HasValue) { return(Json(new { flagErro = true, message = "Visualização já registrada." }, JsonRequestBehavior.AllowGet)); } this.OEmailBL.registrarLeitura(id); return(Json(new { flagErro = false, message = "Visualização registrada com sucesso!" }, JsonRequestBehavior.AllowGet)); }
/** * Salvar o e-mail e os destinatários */ public bool salvarEmail(LogEmail NovoEmail) { NovoEmail.setDefaultInsertValues <LogEmail>(); NovoEmail.listaEmailDestino.ForEach(x => { x.setDefaultInsertValues <LogEmailDestino>(); }); this.db.LogEmail.Add(NovoEmail); this.db.SaveChanges(); bool flagEnviado = (NovoEmail.id > 0); //Disparar o Evento do envio de e-mail if (flagEnviado) { this.onEmailEnviado.publish(NovoEmail); } return(flagEnviado); }
public bool Update(LogEmail datos) { String sql = "UPDATE TH_LOG_EMAIL SET CorreoDestino = @correoDestino, CorreoDestinoCC = @correoDestinoCC, Estado = @estado, Intento = @intento, " + "FechaEnvio = @fechaEnvio, Descripcion = @descripcion, FechaMod = @fechaMod, UserMod = @usuarioMod,MensajeImagen = @mensajeImagen WHERE IDLOGEMAIL = @idLog "; OleDbParameter correoDestino = UtilDA.SetParameters("@correoDestino", OleDbType.VarChar, datos.CorreoDestino); OleDbParameter correoDestinoCC = UtilDA.SetParameters("@correoDestinoCC", OleDbType.VarChar, datos.CorreoDestinoCC); OleDbParameter estado = UtilDA.SetParameters("@estado", OleDbType.VarChar, datos.Estado); OleDbParameter intento = UtilDA.SetParameters("@intento", OleDbType.Integer, datos.Intento); OleDbParameter fechaEnvio = UtilDA.SetParameters("@fechaEnvio", OleDbType.Date, datos.FechaEnvio); OleDbParameter descripcion = UtilDA.SetParameters("@descripcion", OleDbType.VarChar, datos.Descripcion); OleDbParameter fechaMod = UtilDA.SetParameters("@userCrea", OleDbType.Date, DateTime.Now); OleDbParameter usuarioMod = UtilDA.SetParameters("@usuarioMod", OleDbType.VarChar, Sesion.usuario.Login); OleDbParameter mensajeImagen = UtilDA.SetParameters("@mensajeImagen", OleDbType.VarChar, datos.MensajeImagen); OleDbParameter idLog = UtilDA.SetParameters("@idLog", OleDbType.Integer, datos.IdLog); return(UtilDA.ExecuteNonQuery(cmd, CommandType.Text, sql, cnx, false, correoDestino, correoDestinoCC, estado, intento, fechaEnvio, descripcion, fechaMod, usuarioMod, mensajeImagen, idLog)); }
/** * */ public static string exibirDestinosEnviados(this LogEmail Email) { var listaDestinos = Email.listaEmailDestino.Where(x => x.flagCopia == "N" && x.flagCopiaOculta == "N").ToList(); StringBuilder html = new StringBuilder(); listaDestinos.ForEach(item => { if (!String.IsNullOrEmpty(item.nomeDestino)) { html.Append(item.nomeDestino); } else { html.Append(item.emailDestino); } }); return(html.ToString()); }
public LogEmail SaveLogEmail(EmailDTO email, Exception ex) { string to = ""; foreach (string t in email.To) { to += t + ";"; } LogEmail log = new LogEmail { Para = to, Assunto = email.Subject, Erro = $"{ex.Message}" }; db.LogEmails.Add(log); db.SaveChanges(); return(log); }
/// <summary> /// Registra el email en la base de datos. /// </summary> private async Task _registerLogEmail() { var addresses = new List <string>(); foreach (var to in To) { addresses.Add(to.Address); } var registerLogEmail = new LogEmail { From = From.Address, To = string.Join(", ", addresses), Subject = Subject, Message = Body, SendAt = DateTime.Now }; await _logEmailRepository.CreateAsync(registerLogEmail); }
public bool Insert(LogEmail datos) { String sql = "INSERT INTO TH_LOG_EMAIL(CorreoDestino, CorreoDestinoCC, FechaEnvio, Mensaje, Asunto, Estado, Descripcion,FechaCrea,UserCrea,Intento,IdObra, MensajeImagen) " + "VALUES(@correoDestino, @correoDestinoCC, @fechaEnvio, @mensaje, @asunto, @estado, @descripcion, @fechaCrea, @userCrea, @intento,@idObra,@mensajeImagen)"; OleDbParameter correoDestino = UtilDA.SetParameters("@correoDestino", OleDbType.VarChar, datos.CorreoDestino); OleDbParameter correoDestinoCC = UtilDA.SetParameters("@correoDestinoCC", OleDbType.VarChar, datos.CorreoDestinoCC); OleDbParameter fechaEnvio = UtilDA.SetParameters("@fechaEnvio", OleDbType.Date, datos.FechaEnvio); OleDbParameter mensaje = UtilDA.SetParameters("@mensaje", OleDbType.VarChar, datos.Mensaje); OleDbParameter asunto = UtilDA.SetParameters("@asunto", OleDbType.VarChar, datos.Asunto); OleDbParameter estado = UtilDA.SetParameters("@estado", OleDbType.VarChar, datos.Estado); OleDbParameter descripcion = UtilDA.SetParameters("@descripcion", OleDbType.VarChar, datos.Descripcion); OleDbParameter fechaCreacion = UtilDA.SetParameters("@fechaCrea", OleDbType.Date, DateTime.Now); OleDbParameter usuarioCrea = UtilDA.SetParameters("@userCrea", OleDbType.VarChar, Sesion.usuario.Login); OleDbParameter intento = UtilDA.SetParameters("@intento", OleDbType.Integer, datos.Intento); OleDbParameter idobra = UtilDA.SetParameters("@idObra", OleDbType.Integer, datos.IdObra); OleDbParameter mensajeImagen = UtilDA.SetParameters("@mensajeImagen", OleDbType.VarChar, datos.MensajeImagen); return(UtilDA.ExecuteNonQuery(cmd, CommandType.Text, sql, cnx, false, correoDestino, correoDestinoCC, fechaEnvio, mensaje, asunto, estado, descripcion, fechaCreacion, usuarioCrea, intento, idobra, mensajeImagen)); }
public void registraEmail(int id_usu, string emisor, string receptor, string tema, string mensaje) { try { //id_usu, emisor, receptor, tema, mensaje, fecha_actual LogEmail email = new LogEmail(); email.id_receptor = id_usu; email.emisor_email = emisor; email.receptor_email = receptor; email.tema = tema; email.mensaje = mensaje; email.fecha_envio_email = DateTime.Now; _db.LogEmail.Add(email); _db.SaveChanges(); } catch (Exception e) { throw e; } }
private void dgvEmail_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { DataGridViewCellStyle red = this.dgvEmail.DefaultCellStyle.Clone(); red.ForeColor = Color.Red; red.Font = new Font(red.Font, FontStyle.Bold); red.Alignment = DataGridViewContentAlignment.MiddleLeft; foreach (DataGridViewRow dtr in dgvEmail.Rows) { LogEmail logEmail = (LogEmail)dtr.DataBoundItem; if (logEmail.Estado == "FALLO") { dtr.DefaultCellStyle = red; dtr.Cells["Mensaje"].Style = new DataGridViewCellStyle { Alignment = DataGridViewContentAlignment.MiddleCenter }; } } }
public List <LogEmail> GetCorreoFechas(DateTime fechaInicio, DateTime fechaFin) { String sql = "SELECT * FROM TH_LOG_EMAIL WHERE FechaCrea BETWEEN @fechaInicio AND @fechaFin ORDER BY FECHACREA DESC"; OleDbParameter pFecha = UtilDA.SetParameters("@fechaInicio", OleDbType.Date, fechaInicio); OleDbParameter pFechaFin = UtilDA.SetParameters("@fechaFin", OleDbType.Date, fechaFin); LogEmail objLogEmail = null; List <LogEmail> ListaLogEmail = new List <LogEmail>(); using (var dtr = UtilDA.ExecuteReader(cmd, CommandType.Text, sql, cnx, pFecha, pFechaFin)) { while (dtr.Read()) { objLogEmail = new LogEmail() { IdLog = DataConvert.ToInt(dtr["IdLogEmail"]), CorreoDestino = DataConvert.ToString(dtr["CorreoDestino"]), CorreoDestinoCC = DataConvert.ToString(dtr["CorreoDestinoCC"]), FechaEnvio = DataConvert.ToDateTime(dtr["FechaEnvio"]), Mensaje = DataConvert.ToString(dtr["Mensaje"]), Asunto = DataConvert.ToString(dtr["Asunto"]), Estado = DataConvert.ToString(dtr["Estado"]), Descripcion = DataConvert.ToString(dtr["Descripcion"]), Intento = DataConvert.ToInt(dtr["Intento"]), FechaCreacion = DataConvert.ToDateTime(dtr["FechaCrea"]), UsuarioCreacion = DataConvert.ToString(dtr["UserCrea"]), FechaModificacion = DataConvert.ToDateTime(dtr["FechaMod"]), UsuarioModificacion = DataConvert.ToString(dtr["UserMod"]), MensajeImagen = DataConvert.ToString(dtr["MensajeImagen"]), IdObra = DataConvert.ToInt(dtr["IdObra"]) }; ListaLogEmail.Add(objLogEmail); } } UtilDA.Close(cnx); return(ListaLogEmail); }
public async Task <ActionResult> changePassword(string id_usu) { try { var usuarios = _db.Usuario.FirstOrDefault(x => x.id_usu == id_usu); var mail = _db.Usuario.Where(x => x.id_usu == id_usu); var pass = Membership.GeneratePassword(4, 0); //usuarios.ForEach(p => p.pass_usu = pass); usuarios.pass_usu = pass; _db.SaveChanges(); var mensaje = usuarios.Nom_usu + "\n Su contraseña se ha creado con éxito:\n"; List <Task> SendEmailClave = new List <Task>(); foreach (var item in mail) { SendEmailClave.Add(Helper.SendEmailClave("*****@*****.**", item.email, "Nueva Contraseña", mensaje, pass)); LogEmail email = new LogEmail(); email.id_receptor = item.id; email.emisor_email = "*****@*****.**"; email.receptor_email = item.email; email.tema = "Nueva Contraseña"; email.mensaje = mensaje + " " + pass; email.fecha_envio_email = DateTime.Now; _db.LogEmail.Add(email); //registraEmail2(item.id, "*****@*****.**", item.email, "Nueva Contraseña", mensaje + " " +pass); } await Task.WhenAll(SendEmailClave); _db.SaveChanges(); return(RedirectToAction("Login", "Account")); } catch (Exception e) { App_Start.ErrorService.LogError(e); throw e; //return RedirectToAction("Login", "Account"); } }
public IList <LogEmail> GetLista() { String sql = "SELECT * FROM TH_LOG_EMAIL ORDER BY FECHACREA DESC"; LogEmail objLogEmail = null; List <LogEmail> ListaLogEmail = new List <LogEmail>(); using (var dtr = UtilDA.ExecuteReader(cmd, CommandType.Text, sql, cnx)) { while (dtr.Read()) { objLogEmail = new LogEmail() { IdLog = DataConvert.ToInt(dtr["IdLogEmail"]), CorreoDestino = DataConvert.ToString(dtr["CorreoDestino"]), CorreoDestinoCC = DataConvert.ToString(dtr["CorreoDestinoCC"]), FechaEnvio = DataConvert.ToDateTime(dtr["FechaEnvio"]), Mensaje = DataConvert.ToString(dtr["Mensaje"]), Asunto = DataConvert.ToString(dtr["Asunto"]), Estado = DataConvert.ToString(dtr["Estado"]), Descripcion = DataConvert.ToString(dtr["Descripcion"]), Intento = DataConvert.ToInt(dtr["Intento"]), FechaCreacion = DataConvert.ToDateTime(dtr["FechaCrea"]), UsuarioCreacion = DataConvert.ToString(dtr["UserCrea"]), FechaModificacion = DataConvert.ToDateTime(dtr["FechaMod"]), UsuarioModificacion = DataConvert.ToString(dtr["UserMod"]), MensajeImagen = DataConvert.ToString(dtr["MensajeImagen"]), IdObra = DataConvert.ToInt(dtr["IdObra"]) }; ListaLogEmail.Add(objLogEmail); } } UtilDA.Close(cnx); return(ListaLogEmail); }
public void RegistrarLogEmail(LogEmail logEmail, string conexao) { if (!Log_Config.LogEmail) { return; } string query = "INSERT INTO " + Tabelas_Guardian.LogEmail + " " + "(DATA, HORA, EMAIL, ROTINA, STATUS, INFO_ADICIONAIS, APLICACAO) " + "VALUES (" + " '" + logEmail.Data + "', " + " '" + logEmail.Hora + "', " + " '" + logEmail.Email + "', " + " '" + logEmail.Rotina + "', " + " '" + logEmail.Status + "', " + " '" + logEmail.InfoAdicionais + "', " + " '" + logEmail.Aplicacao + "' " + ")"; try { using (SqlConnection connection = new SqlConnection(conexao)) { using (SqlCommand command = new SqlCommand(query, connection)) { connection.Open(); command.ExecuteNonQuery(); } } } catch (Exception ex) { Guardian_LogTxt.LogAplicacao("Registrar Log Email ", "Erro " + ex.ToString() + Environment.NewLine + " Status: " + Log_Config.LogEmail + " Query: " + query); } }
public FowardEmails(LogEmail logEmail) { this.logEmail = logEmail; completeHtml = logEmail.Mensaje; InitializeComponent(); }
public static bool SendMail(IList <string> mailAdresses, IList <string> ccAddresses, string originalHtml, string originalSubject, ILogEmailRepository logEmailRepository, byte[] attachment, LogEmail logEmail) { ContactCenterDA.Repositories.CC.TH.ObraRepository obraRepository = new ContactCenterDA.Repositories.CC.TH.ObraRepository(); try { var smtpClient = new SmtpClient(); #region Get Config Variables String correo = ""; String password = ""; if (Sesion.aplicacion.CorreoNotificacion.Equals(String.Empty)) { correo = ConfigurationManager.AppSettings["mailAccount"]; password = ConfigurationManager.AppSettings["mailPassword"]; } else { correo = Sesion.aplicacion.CorreoNotificacion; password = Sesion.aplicacion.Contraseña; } var mailAccount = correo; var mailPassword = password; var smtp = ConfigurationManager.AppSettings["smtp"]; var mailDisplayName = ConfigurationManager.AppSettings["mailDisplayName"]; var port = ConfigurationManager.AppSettings["port"]; var sslEnabled = Convert.ToBoolean(ConfigurationManager.AppSettings["sslEnabled"]); var domain = ConfigurationManager.AppSettings["Domain"]; #endregion #region Create SMTP smtpClient.Host = smtp; smtpClient.Port = Convert.ToInt16(port); smtpClient.UseDefaultCredentials = false; smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; if (domain != null) { smtpClient.Credentials = new NetworkCredential(mailAccount, mailPassword, domain); } else { smtpClient.Credentials = new NetworkCredential(mailAccount, mailPassword); } smtpClient.EnableSsl = sslEnabled; #endregion Create SMTP #region Create Mail an recievers var mail = new MailMessage(); mail.From = new MailAddress(mailAccount, mailDisplayName); foreach (var mailDirection in mailAdresses.Where(x => !string.IsNullOrEmpty(x))) { mail.To.Add(new MailAddress(mailDirection.ToLower())); } foreach (var mailCC in ccAddresses.Where(x => !string.IsNullOrEmpty(x))) { mail.CC.Add(new MailAddress(mailCC.ToLower())); } #endregion #region Create Mail Variables string htmlBody = originalHtml; string subject = originalSubject; #endregion Create Mail Variables #region Get Mail Body embedded images paths Byte[] ba = obraRepository.GetImage(logEmail.IdObra); MemoryStream ms = new MemoryStream(ba); Image ImageCabe = ContactCenterBL.Properties.Resources.cabecera; Byte[] imageCabeByte = Convertir_Imagen_Bytes(ImageCabe); MemoryStream ca = new MemoryStream(imageCabeByte); #endregion Get Mail Body embedded images paths #region Set embedded images mail id var cabecera = new LinkedResource(ca, MediaTypeNames.Image.Jpeg); cabecera.ContentId = "Cabecera"; //cabecera.TransferEncoding = TransferEncoding.Base64; var logo = new LinkedResource(ms, MediaTypeNames.Image.Jpeg); //logo.TransferEncoding = TransferEncoding.Base64; logo.ContentId = "ImagenObra"; var imageText = logEmail.MensajeImagen; Image imageMail; AlternateView html = null; if (imageText.Equals(String.Empty)) // legacy emails { html = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html); html.LinkedResources.Add(logo); html.LinkedResources.Add(cabecera); } else { Image image = Image.FromStream(ca); Guid id = Guid.NewGuid(); image.Save($"C:\\BackupTeatro\\{id.ToString()}.jpg"); string path = $"C:\\BackupTeatro\\{id.ToString()}.jpg"; Image image2 = Image.FromStream(ms); Guid id2 = Guid.NewGuid(); image2.Save($"C:\\BackupTeatro\\{id2.ToString()}.jpg"); string path2 = $"C:\\BackupTeatro\\{id2.ToString()}.jpg"; htmlBody = htmlBody.Replace("%Cabecera", path); htmlBody = htmlBody.Replace("%ImagenObra", path2); imageText = imageText.Replace("%Cabecera", path); imageText = imageText.Replace("%ImagenObra", path2); imageMail = TheArtOfDev.HtmlRenderer.WinForms.HtmlRender.RenderToImageGdiPlus(imageText); //imageMail.Save($"C:\\BackupTeatro\\test2.jpg"); //Image imagex = Image.FromFile($"C:\\BackupTeatro\\test2.jpg"); Byte[] imageMailBytes = Convertir_Imagen_Bytes(imageMail); MemoryStream imageMailMemoryStream = new MemoryStream(imageMailBytes); var imageMailLinked = new LinkedResource(imageMailMemoryStream, MediaTypeNames.Image.Jpeg); imageMailLinked.ContentId = "obraimagen"; Byte[] pdfFile = PdfSharpConvert(htmlBody); MemoryStream pdfStream = new MemoryStream(pdfFile); mail.Attachments.Add(new Attachment(pdfStream, "Confirmación de compra.pdf")); if (File.Exists(path2)) { File.Delete(path2); } if (File.Exists(path)) { File.Delete(path); } htmlBody = htmlBody.Replace($"C:\\BackupTeatro\\{id.ToString()}.jpg", "%Cabecera"); htmlBody = htmlBody.Replace($"C:\\BackupTeatro\\{id2.ToString()}.jpg", "%ImagenObra"); imageText = imageText.Replace($"C:\\BackupTeatro\\{id.ToString()}.jpg", "%Cabecera"); imageText = imageText.Replace($"C:\\BackupTeatro\\{id2.ToString()}.jpg", "%ImagenObra"); var newHtml = ContactCenterBL.Properties.Resources._base; html = AlternateView.CreateAlternateViewFromString(newHtml, null, MediaTypeNames.Text.Html); //html.TransferEncoding = TransferEncoding.Base64; html.LinkedResources.Add(imageMailLinked); } //mail.Attachments.Add(new Attachment(imageMailMemoryStream, "Compra.jpg")); #endregion #region Set Body and Images //html.LinkedResources.Add(cabecera); #endregion Get Mail Body embedded images paths #region Set values to mail mail.Subject = subject; mail.IsBodyHtml = true; //Attachment inlineLogo = new Attachment(@"../../Resources/cabecera_correo2.jpg"); //string contentID = "cabe"; //inlineLogo.ContentId = contentID; //inlineLogo.ContentDisposition.Inline = true; //inlineLogo.ContentDisposition.DispositionType = DispositionTypeNames.Inline; //mail.Attachments.Add(inlineLogo); mail.AlternateViews.Add(html); #endregion Set values to mail #region Send Mail smtpClient.Send(mail); logEmail.Asunto = subject; logEmail.CorreoDestino = string.Join(",", mailAdresses.Select(x => x.ToString()).ToArray()); logEmail.CorreoDestinoCC = string.Join(",", ccAddresses.Select(x => x.ToString()).ToArray()); logEmail.Estado = "OK"; logEmail.FechaEnvio = DateTime.Now; logEmail.FechaModificacion = DateTime.Now; logEmail.UsuarioModificacion = Sesion.usuario.Login; logEmail.Mensaje = htmlBody; logEmail.Intento = logEmail.Intento + 1; logEmail.Descripcion = String.Empty; logEmailRepository.Update(logEmail); smtpClient.Dispose(); mail.Dispose(); logo.Dispose(); return(true); #endregion Send Mail } catch (Exception ex) { logEmail.CorreoDestino = string.Join(",", mailAdresses.Select(x => x.ToString()).ToArray()); logEmail.CorreoDestinoCC = string.Join(",", ccAddresses.Select(x => x.ToString()).ToArray()); logEmail.FechaEnvio = DateTime.Now; logEmail.FechaModificacion = DateTime.Now; logEmail.UsuarioModificacion = Sesion.usuario.Login; logEmail.Intento = logEmail.Intento + 1; logEmail.Estado = "FALLO"; logEmail.Descripcion = ex.Message; logEmailRepository.Update(logEmail); return(false); } }
public static void SendMail(IList <string> mailAdresses, IList <string> ccAddresses, Enumerables.MailAction action, ILogEmailRepository logEmailRepository, Reserva reserva, byte[] attachment = null) { ContactCenterDA.Repositories.CC.TH.ObraRepository obraRepository = new ContactCenterDA.Repositories.CC.TH.ObraRepository(); string htmlBody = ""; string htmlImageBody = ""; string subject = ""; try { var smtpClient = new SmtpClient(); #region Get Config Variables String correo = ""; String password = ""; if (Sesion.aplicacion.CorreoNotificacion.Equals(String.Empty)) { correo = ConfigurationManager.AppSettings["mailAccount"]; password = ConfigurationManager.AppSettings["mailPassword"]; } else { correo = Sesion.aplicacion.CorreoNotificacion; password = Sesion.aplicacion.Contraseña; } var mailAccount = correo; var mailPassword = password; var smtp = ConfigurationManager.AppSettings["smtp"]; var mailDisplayName = ConfigurationManager.AppSettings["mailDisplayName"]; var port = ConfigurationManager.AppSettings["port"]; var sslEnabled = Convert.ToBoolean(ConfigurationManager.AppSettings["sslEnabled"]); var domain = ConfigurationManager.AppSettings["Domain"]; #endregion #region Create SMTP smtpClient.Host = smtp; smtpClient.Port = Convert.ToInt16(port); smtpClient.UseDefaultCredentials = false; smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; if (domain != null) { smtpClient.Credentials = new NetworkCredential(mailAccount, mailPassword, domain); } else { smtpClient.Credentials = new NetworkCredential(mailAccount, mailPassword); } smtpClient.EnableSsl = sslEnabled; #endregion Create SMTP #region Create Mail an recievers var mail = new MailMessage(); mail.From = new MailAddress(mailAccount, mailDisplayName); foreach (var mailDirection in mailAdresses.Where(x => !string.IsNullOrEmpty(x))) { mail.To.Add(new MailAddress(mailDirection.ToLower())); } foreach (var mailCC in ccAddresses.Where(x => !string.IsNullOrEmpty(x))) { mail.CC.Add(new MailAddress(mailCC.ToLower())); } #endregion #region Create Mail Variables //System.Globalization.CultureInfo cultureinfo = new System.Globalization.CultureInfo("es-PE"); var nombre = reserva.Cliente.Nombre + " " + reserva.Cliente.ApellidoPaterno + " " + reserva.Cliente.Apellidomaterno; var obra = reserva.Obra.Nombre; var fecha = reserva.FechaReserva.ToString("dd/MM/yyyy" /*, cultureinfo*/); var teatro = reserva.Obra.Teatro.Nombre; var hora = reserva.Horario; var totalObras = reserva.ListaDetalles.Count(); var ubicacion = reserva.Asientos; var precio = reserva.PrecioTotal; #endregion Create Mail Variables #region Set Mail Variable Values #endregion Set Mail Variable Values #region Set Mail Body switch (action) { case Enumerables.MailAction.TeatroConfirmacionReserva: htmlBody = ContactCenterBL.Properties.Resources.nuevomail; htmlBody = htmlBody.Replace("%Nombre", nombre); htmlBody = htmlBody.Replace("%Obra", obra); htmlBody = htmlBody.Replace("%Fecha", fecha); htmlBody = htmlBody.Replace("%Teatro", teatro); htmlBody = htmlBody.Replace("%Hora", fecha + " - " + hora); htmlBody = htmlBody.Replace("%Total", totalObras.ToString()); htmlBody = htmlBody.Replace("%Ubicacion", ubicacion); htmlBody = htmlBody.Replace("%Precio", precio.ToString("#.00")); htmlImageBody = ContactCenterBL.Properties.Resources.detail; htmlImageBody = htmlImageBody.Replace("%Nombre", nombre); htmlImageBody = htmlImageBody.Replace("%Obra", obra); htmlImageBody = htmlImageBody.Replace("%Fecha", fecha); htmlImageBody = htmlImageBody.Replace("%Teatro", teatro); htmlImageBody = htmlImageBody.Replace("%Hora", fecha + " - " + hora); htmlImageBody = htmlImageBody.Replace("%Total", totalObras.ToString()); htmlImageBody = htmlImageBody.Replace("%Ubicacion", ubicacion); htmlImageBody = htmlImageBody.Replace("%Precio", precio.ToString("#.00")); List <String> zonas = new List <String>(); foreach (DetalleReserva detalleRes in reserva.ListaDetalles.OrderBy(tx => tx.NombreZona).ToList()) { if (!zonas.Contains(detalleRes.NombreZona)) { zonas.Add(detalleRes.NombreZona); } } string detalle = ""; string filAsiento = ""; int contador = 0; foreach (String nomZona in zonas) { foreach (DetalleReserva detalleRes2 in reserva.ListaDetalles.Where(tx => tx.NombreZona == nomZona)) { filAsiento += detalleRes2.NombreFila + " / " + detalleRes2.NombreAsiento + ", "; } filAsiento = filAsiento.TrimEnd(',', ' '); //detalle += "<tr><td style= 'text-align:right;'>Sector</td><td>:</td><td></td><td></td><td style= 'text-align:left;'>" + nomZona + "</td></tr><tr><td style= 'text-align:right;' >Ubicaciones</td><td>:</td><td></td><td></td><td style= 'text-align:left;'>" + filAsiento + "</td></tr>"; detalle += $"<p style='margin-top:3%; margin-bottom: 2%'>ZONA: {nomZona}</p> <p style='margin-top:3%; margin-bottom: 2%'> UBICACIÓN: {filAsiento}</p>"; filAsiento = ""; } htmlBody = htmlBody.Replace("varDetalle", detalle); htmlImageBody = htmlImageBody.Replace("varDetalle", detalle); break; default: throw new ArgumentOutOfRangeException(nameof(action), action, null); } #endregion Set Mail Body #region Set Mail Subject switch (action) { case Enumerables.MailAction.TeatroConfirmacionReserva: subject = Constantes.Subjects.TeatroConfirmacionReserva; break; default: throw new ArgumentOutOfRangeException(nameof(action), action, null); } #endregion Set Mail Subject #region Get Mail Body embedded images paths Byte[] ba = obraRepository.GetImage(reserva.Obra.IdObra); MemoryStream ms = new MemoryStream(ba); //var cabeceraImgPath = Path.Combine("../../Resources/cabecera_correo2.jpg"); //var rootFolder = AppDomain.CurrentDomain.BaseDirectory; //var cabepath = Path.Combine(rootFolder, "../../Resources/cabecera_correo2.jpg"); Image ImageCabe = ContactCenterBL.Properties.Resources.cabecera; Byte[] imageCabeByte = Convertir_Imagen_Bytes(ImageCabe); MemoryStream ca = new MemoryStream(imageCabeByte); Image image = Image.FromStream(ca); Guid id = Guid.NewGuid(); image.Save($"C:\\BackupTeatro\\{id.ToString()}.jpg"); string path = $"C:\\BackupTeatro\\{id.ToString()}.jpg"; Image image2 = Image.FromStream(ms); Guid id2 = Guid.NewGuid(); image2.Save($"C:\\BackupTeatro\\{id2.ToString()}.jpg"); string path2 = $"C:\\BackupTeatro\\{id2.ToString()}.jpg"; htmlBody = htmlBody.Replace("%Cabecera", path); htmlBody = htmlBody.Replace("%ImagenObra", path2); htmlImageBody = htmlImageBody.Replace("%Cabecera", path); htmlImageBody = htmlImageBody.Replace("%ImagenObra", path2); Image imageMail = TheArtOfDev.HtmlRenderer.WinForms.HtmlRender.RenderToImageGdiPlus(htmlImageBody); //imageMail.Save($"C:\\BackupTeatro\\test2.jpg"); //Image imagex = Image.FromFile($"C:\\BackupTeatro\\test2.jpg"); Byte[] imageMailBytes = Convertir_Imagen_Bytes(imageMail); MemoryStream imageMailMemoryStream = new MemoryStream(imageMailBytes); //mail.Attachments.Add(new Attachment(imageMailMemoryStream, "Compra.jpg")); var imageMailLinked = new LinkedResource(imageMailMemoryStream, MediaTypeNames.Image.Jpeg); imageMailLinked.ContentId = "obraimagen"; Byte[] pdfFile = PdfSharpConvert(htmlBody); MemoryStream pdfStream = new MemoryStream(pdfFile); mail.Attachments.Add(new Attachment(pdfStream, "Confirmación de compra.pdf")); if (File.Exists(path2)) { File.Delete(path2); } if (File.Exists(path)) { File.Delete(path); } htmlBody = htmlBody.Replace($"C:\\BackupTeatro\\{id.ToString()}.jpg", "%Cabecera"); htmlBody = htmlBody.Replace($"C:\\BackupTeatro\\{id2.ToString()}.jpg", "%ImagenObra"); htmlImageBody = htmlImageBody.Replace($"C:\\BackupTeatro\\{id.ToString()}.jpg", "%Cabecera"); htmlImageBody = htmlImageBody.Replace($"C:\\BackupTeatro\\{id2.ToString()}.jpg", "%ImagenObra"); #endregion Get Mail Body embedded images paths #region Set embedded images mail id //var cabecera = new LinkedResource(ca, MediaTypeNames.Image.Jpeg); //cabecera.ContentId = "Cabecera"; ////cabecera.TransferEncoding = TransferEncoding.Base64; //var logo = new LinkedResource(ms, MediaTypeNames.Image.Jpeg); //logo.ContentId = "ImagenObra"; ////logo.TransferEncoding = TransferEncoding.Base64; #endregion #region Set Body and Images var newHtml = ContactCenterBL.Properties.Resources._base; var html = AlternateView.CreateAlternateViewFromString(newHtml, null, MediaTypeNames.Text.Html); //html.TransferEncoding = TransferEncoding.Base64; html.LinkedResources.Add(imageMailLinked); //html.LinkedResources.Add(cabecera); #endregion Set Body and Images #region Set values to mail mail.Subject = subject; mail.SubjectEncoding = Encoding.UTF8; mail.IsBodyHtml = true; mail.AlternateViews.Add(html); #endregion Set values to mail #region Send Mail smtpClient.SendAsync(mail, null); smtpClient.SendCompleted += (s, e) => { LogEmail logEmail = new LogEmail(); logEmail.Asunto = subject; logEmail.CorreoDestino = string.Join(",", mailAdresses.Select(x => x.ToString()).ToArray()); logEmail.CorreoDestinoCC = string.Join(",", ccAddresses.Select(x => x.ToString()).ToArray()); logEmail.Estado = "OK"; logEmail.IdObra = reserva.Obra.IdObra; logEmail.FechaEnvio = DateTime.Now; logEmail.MensajeImagen = htmlImageBody; logEmail.FechaCreacion = DateTime.Now; logEmail.UsuarioCreacion = Sesion.usuario.Login; logEmail.Mensaje = htmlBody; logEmail.Intento = 1; logEmail.Descripcion = String.Empty; if (e.Error != null) { logEmail.Estado = "FALLO"; if (e.Error.InnerException != null) { logEmail.Descripcion = e.Error.InnerException.Message; } else { logEmail.Descripcion = e.Error.Message; } } logEmailRepository.Insert(logEmail); if (e.Error != null) { MessageBox.Show("No se envió el correo\n\n" + "Cliente: \n" + nombre + "\n" + "Obra: \n" + obra + "\n" + "Fecha Reserva: \n" + reserva.FechaReserva.ToShortDateString() + "\n" + "Correo: \n" + reserva.Cliente.Correo + "\n\n" + "Error: \n" + e.Error.Message, "Error enviando email", MessageBoxButtons.OK, MessageBoxIcon.Error); } smtpClient.Dispose(); mail.Dispose(); //logo.Dispose(); }; #endregion Send Mail } catch (Exception ex) { LogEmail logEmail = new LogEmail(); logEmail.Asunto = subject; logEmail.CorreoDestino = string.Join(",", mailAdresses.Select(x => x.ToString()).ToArray()); logEmail.CorreoDestinoCC = string.Join(",", ccAddresses.Select(x => x.ToString()).ToArray()); logEmail.Estado = "OK"; logEmail.IdObra = reserva.Obra.IdObra; logEmail.FechaEnvio = DateTime.Now; logEmail.MensajeImagen = htmlImageBody; logEmail.FechaCreacion = DateTime.Now; logEmail.UsuarioCreacion = Sesion.usuario.Login; logEmail.Mensaje = htmlBody; logEmail.Intento = 1; logEmail.Estado = "FALLO"; logEmail.Descripcion = ex.Message; logEmailRepository.Insert(logEmail); MessageBox.Show("No se envió el correo\n\n" + "Cliente: \n" + reserva.Cliente.Nombre + " " + reserva.Cliente.ApellidoPaterno + " " + reserva.Cliente.Apellidomaterno + "\n" + "Obra: \n" + reserva.Obra.Nombre + "\n" + "Fecha Reserva: \n" + reserva.FechaReserva.ToShortDateString() + "\n" + "Correo: \n" + reserva.Cliente.Correo + "\n\n" + "Error: \n" + ex.Message, "Error enviando email", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/** * */ public static string cssClasseLeitura(this LogEmail Email) { return(Email.dtPrimeiraAbertura.HasValue? "lido": "nao-lido"); }