public async Task Locate_Smtp_Test() { var locator = new SmtpLocator { ServiceDomain = "dev-test.rnd.ipzo.net" }; SmtpService smtp = await locator.Locate(); //smtp.Decryptor.KeyPhrase = "dev"; Assert.IsNotNull(smtp); Assert.IsNotNull(smtp.Credentials); Console.WriteLine(smtp.Credentials.UserName); Assert.AreEqual("*****@*****.**", smtp.Credentials.UserName); Console.WriteLine(smtp.Credentials.Password); }
protected void BtnEnviarRevision_Click(object sender, EventArgs e) { try{ String vQuery = "[ACSP_ObtenerUsuarios] 4,'" + Convert.ToString(Session["USUARIO"]) + "'"; DataTable vDatosResponsables = vConexion.obtenerDataTable(vQuery); Correo vCorreo = new Correo(); foreach (DataRow item in vDatosResponsables.Rows) { vCorreo.Usuario = vConexion.GetNombreUsuario(item["idUsuario"].ToString()); vCorreo.Para = item["correo"].ToString(); vCorreo.Copia = ""; } SmtpService vSmtpService = new SmtpService(); Boolean vEnvio = vSmtpService.EnviarMensaje( vCorreo.Para, typeBody.General, vCorreo.Usuario, "Se ha ingresado un nuevo informe para su revisión y envio. (No." + LbRevisionInforme.Text + ") " + vConexion.GetNombreInforme(LbRevisionInforme.Text).ToUpper() + @"<br \><br \>" + "Ingresado por:" + vConexion.GetNombreUsuario(Convert.ToString(Session["USUARIO"])), vCorreo.Copia ); if (vEnvio) { vQuery = "[ACSP_Informes] 5," + LbRevisionInforme.Text + ",1"; vConexion.ejecutarSql(vQuery); } if (vIdInforme != null) { buscarInforme(vIdInforme, true); } else { getInformes(); } CerrarModal("RevisionModal"); Mensaje("Mensaje enviado con exito", WarningType.Success); } catch (Exception Ex) { Mensaje(Ex.Message, WarningType.Danger); CerrarModal("RevisionModal"); } }
public async Task SendEmail_UsesCustomSender() { var pickupDirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "Email"); if (Directory.Exists(pickupDirectoryPath)) { var directory = new DirectoryInfo(pickupDirectoryPath); directory.GetFiles().ToList().ForEach(f => f.Delete()); } Directory.CreateDirectory(pickupDirectoryPath); var options = new Mock <IOptions <SmtpSettings> >(); options.Setup(o => o.Value).Returns(new SmtpSettings { DefaultSender = "Your Name <*****@*****.**>", DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory, PickupDirectoryLocation = pickupDirectoryPath }); var logger = new Mock <ILogger <SmtpService> >(); var localizer = new Mock <IStringLocalizer <SmtpService> >(); var smtp = new SmtpService(options.Object, logger.Object, localizer.Object); var message = new MailMessage { To = "*****@*****.**", Subject = "Test", Body = "Test Message", From = "My Name <*****@*****.**>", }; var result = await smtp.SendAsync(message); Assert.True(result.Succeeded); var file = new DirectoryInfo(pickupDirectoryPath).GetFiles().FirstOrDefault(); Assert.NotNull(file); var content = File.ReadAllText(file.FullName); Assert.Contains("From: My Name <*****@*****.**>", content); Assert.Contains("Sender: My Name <*****@*****.**>", content); }
private Boolean EnviarCorreo(int i, String vMensaje, DataTable vDatos) { Boolean vResult = false; try{ SmtpService vSmtpService = new SmtpService(); vSmtpService.EnviarMensaje( vDatos.Rows[i]["correo"].ToString(), typeBody.General, vDatos.Rows[i]["nombre"].ToString(), vMensaje, "" ); vResult = true; }catch (Exception ex) { Mensaje(ex.Message, WarningType.Danger); } return(vResult); }
private void enviaCorreo(DataTable vDatos) { //String vQuery = "RSP_ObtenerEmpleados 2," + DDLAutorizado.SelectedValue; DataTable vDatosEmpleado = vConexion.obtenerDataTable(""); SmtpService vService = new SmtpService(); foreach (DataRow item in vDatosEmpleado.Rows) { if (!item["emailEmpresa"].ToString().Trim().Equals("")) { vService.EnviarMensaje(item["emailEmpresa"].ToString(), typeBody.Seguridad, item["nombre"].ToString(), "SALIDA-" + vDatos.Rows[0]["id"].ToString() + "-" + vDatos.Rows[0]["tabla"].ToString() ); } } }
public IHttpActionResult ConfirmUser(int userId) { AppUser user = db.AppUsers.Get(userId); if (user == null) { return(NotFound()); } user.IsUserConfirmed = true; db.AppUsers.Update(user); db.Complete(); SmtpService smtpService = new SmtpService(); string mailBody = "User " + user.FullName + " Id:" + user.Id + " is confirmed."; RAIdentityUser RAUser = db.Users.GetByAppUserId(user.Id); smtpService.SendMail("User confirmation", mailBody, RAUser.Email); return(StatusCode(HttpStatusCode.NoContent)); }
public IHttpActionResult ConfirmService(int serviceId) { Service service = db.Services.Get(serviceId); if (service == null) { return(NotFound()); } service.IsConfirmed = true; db.Services.Update(service); db.Complete(); SmtpService smtpService = new SmtpService(); string mailBody = "Service " + service.Name + " Id:" + service.Id + " is confirmed."; AppUser manager = db.AppUsers.Get(service.ServiceManagerId); RAIdentityUser RAUser = db.Users.GetByAppUserId(manager.Id); smtpService.SendMail("Service confirmation", mailBody, RAUser.Email); return(StatusCode(HttpStatusCode.NoContent)); }
public void ApproveService(Service service) { var s = Context.Services.FirstOrDefault(q => q.Id == service.Id); if (s != null && !s.Approved) { s.Approved = true; Context.Entry(s).State = EntityState.Modified; Context.SaveChanges(); var manager = Context.Users.FirstOrDefault(m => m.AppUserId == service.ManagerId); if (manager == null) { return; } var subject = "Odobren servis"; var body = "Postovani,\nOvim putem zelimo da vas obavestimo da je Vas servis odobren i dostupan korisnicima da ga koriste.\nSrecan rad,\nRent-a-car tim."; var smtp = new SmtpService(); smtp.SendMail(subject, body, manager.Email); } }
public async Task EmailDetailsAsync(string to, string subject) { var appsettings = ConfigurationManager.AppSettings; MailMessage email = new MailMessage(new MailAddress(appsettings["Smtp.DefaultFromAddress"], appsettings["Smtp.DefaultFromUser"]), new MailAddress(to)); email.CC.Add(new MailAddress(appsettings["EmailTo"])); email.Subject = subject; email.IsBodyHtml = true; string message = "<html><body><table>"; //iterate over payment properties and add name and value to email message foreach (var prop in this.GetType().GetProperties()) { message += "<tr><td>" + prop.Name + "</td><td>" + prop.GetValue(this, null) + "</td></tr>"; } message += "</table></body></html>"; email.Body = message; using (var mailClient = new SmtpService()) { await mailClient.SendMailAsync(email); } }
public override WorkflowExecutionStatus Execute( Record record, RecordEventArgs e) { try { var smtpService = new SmtpService(); var template = $"~/Views/Partials/{TemplateName}"; var emailBody = File.ReadAllText(System.Web.HttpContext.Current.Server.MapPath(template)) .Replace("[[SUBJECT]]", Subject) .Replace("[[HEADING]]", Heading) .Replace("[[BODY]]", Message); smtpService.SendEmail(emailBody, ToEmail, FromEmail, FromName, Subject, ReplyTo, Bcc, Cc); return(WorkflowExecutionStatus.Completed); } catch (Exception ex) { LogHelper.Error <CustomEmailWorkflow>(ex.Message, ex); return(WorkflowExecutionStatus.Failed); } }
protected void BtnEnviar_Click(object sender, EventArgs e) { try { validaDatos(); String vQuery = "RSP_ObtenerEmpleados 2," + DDLEmpleado.SelectedValue; DataTable vDatosEmpleado = vConexion.obtenerDataTable(vQuery); SmtpService vService = new SmtpService(); Boolean vFlagEnviado = false; foreach (DataRow item in vDatosEmpleado.Rows) { if (!item["emailEmpresa"].ToString().Trim().Equals("")) { vService.EnviarMensaje(item["emailEmpresa"].ToString(), typeBody.Token, item["nombre"].ToString(), Convert.ToString(Session["TOKEN"]) ); vFlagEnviado = true; } } if (vFlagEnviado) { vQuery = "[RSP_IngresaMantenimientos] 5,'" + Session["TOKEN"].ToString() + "'," + DDLEmpleado.SelectedValue; int vVerificacion = vConexion.ejecutarSql(vQuery); if (vVerificacion == 1) { Mensaje("Token enviado con exito!", WarningType.Success); LimpiarToken(); } } } catch (Exception ex) { Mensaje(ex.Message, WarningType.Danger); } }
static void Main(string[] args) { var services = new ServiceCollection(); services.AddOptions() .Configure <SmtpOption>(opt => { opt.Host = "smtp.gmail.com"; opt.Port = 465; opt.UseSsl = true; opt.UserName = "******"; opt.Password = "******"; opt.QuitAfterSending = true; }); var provider = services.BuildServiceProvider(); var optionSnapshot = provider.GetRequiredService <IOptionsSnapshot <SmtpOption> >(); var message1 = new MimeMessage() .AddFrom("Trung Tran", "...") .AddTo("Another Trung Tran", "...") .Subject("You will be OK?") .Body(html: "<div style='color:green;font-weight:bold'>It's OK</div>", SimpleAttachment.From(@"\somefile1"), SimpleAttachment.From(@"\somefile2")); var message2 = new MimeMessage() .AddFrom("Trung Tran", "...") .AddTo("Another Trung Tran", "...") .Subject("You will be OK? (twice)") .Body(html: "<div style='color:green;font-weight:bold'>It's OK</div>"); ISmtpService smtpService = new SmtpService(optionSnapshot); smtpService.SendMailAsync(message1, message2).Wait(); }
private static EntityRecord SmtpServiceToEntityRecordConvert(SmtpService model) { if (model == null) { return(null); } EntityRecord rec = new EntityRecord(); rec["id"] = model.Id; rec["name"] = model.Name; rec["server"] = model.Server; rec["port"] = model.Port; rec["username"] = model.Username; rec["password"] = model.Password; rec["default_from_email"] = model.DefaultFromEmail; rec["default_from_name"] = model.DefaultFromName; rec["default_reply_to_email"] = model.DefaultReplyToEmail; rec["max_retries_count"] = (decimal)((int)model.MaxRetriesCount); rec["retry_wait_minutes"] = (decimal)((int)model.RetryWaitMinutes); rec["is_default"] = model.IsDefault; rec["connection_security"] = ((int)model.ConnectionSecurity).ToString(); return(rec); }
private static SmtpService EntityRecordToSmtpServiceConvert(EntityRecord rec) { if (rec == null) { return(null); } SmtpService model = new SmtpService(); model.Id = (Guid)rec["id"]; model.Name = (string)rec["name"]; model.Server = (string)rec["server"]; model.Port = (int)((decimal)rec["port"]); model.Username = (string)rec["username"]; model.Password = (string)rec["password"]; model.DefaultFromEmail = (string)rec["default_from_email"]; model.DefaultFromName = (string)rec["default_from_name"]; model.DefaultReplyToEmail = (string)rec["default_reply_to_email"]; model.MaxRetriesCount = (int)((decimal)rec["max_retries_count"]); model.RetryWaitMinutes = (int)((decimal)rec["retry_wait_minutes"]); model.IsDefault = (bool)rec["is_default"]; model.ConnectionSecurity = (SecureSocketOptions)(int.Parse((string)rec["connection_security"])); return(model); }
internal void SetSmtpService(SmtpService InService) { ParentService = InService; }
protected void BtnEnviarPermiso_Click(object sender, EventArgs e) { try{ String vNombreDepot1 = String.Empty; HttpPostedFile bufferDeposito1T = FUDocumentoPermiso.PostedFile; byte[] vFileDeposito1 = null; String vExtension = String.Empty; if (bufferDeposito1T != null) { vNombreDepot1 = FUDocumentoPermiso.FileName; Stream vStream = bufferDeposito1T.InputStream; BinaryReader vReader = new BinaryReader(vStream); vFileDeposito1 = vReader.ReadBytes((int)vStream.Length); vExtension = System.IO.Path.GetExtension(FUDocumentoPermiso.FileName); } if (DDLTipoPermiso.SelectedValue == "1006" && !FUDocumentoPermiso.HasFiles) { Response.Redirect("/pages/permissions.aspx?ex=4"); } if (DDLTipoPermiso.SelectedValue == "1026" && !FUDocumentoPermiso.HasFiles) { Response.Redirect("/pages/permissions.aspx?ex=4"); } String vArchivo = String.Empty; if (vFileDeposito1 != null) { vArchivo = Convert.ToBase64String(vFileDeposito1); } Int32 vEmergencia = CbEmergencias.Checked ? 1 : 0; String vFormato = "yyyy-MM-dd HH:mm:ss"; //"dd-MM-yyyy HH:mm:ss"; String vFeINI = Convert.ToDateTime(TxFechaInicio.Text).ToString(vFormato); String vFeFIN = Convert.ToDateTime(TxFechaRegreso.Text).ToString(vFormato); String vQuery = "RSP_IngresarPermisos 1," + DDLEmpleado.SelectedValue + "," + "" + DDLJefe.SelectedValue + "," + "" + DDLTipoPermiso.SelectedValue + "," + "'" + TxMotivo.Text + "'," + "'" + vFeINI + "'," + "'" + vFeFIN + "'," + "'" + Convert.ToString(Session["USUARIO"]) + "'," + "" + DDLCompensacion.SelectedValue + "," + "'" + TxFechaCompensacion.Text + "'," + "" + DDLParientes.SelectedValue + "," + "'" + vArchivo + "'," + "'" + vExtension + "'," + vEmergencia; Int32 vInformacion = vConexion.ejecutarSql(vQuery); //-PROD- Int32 vInformacion = 1; if (vInformacion == 1) { String vRe = ""; // begin wpadilla vQuery = "[RSP_IngresarEmpleados] 4," + DDLEmpleado.SelectedValue + ", '0'"; vConexion.ejecutarSql(vQuery); if (CbEmergencias.Checked && Session["IDTOKEN"] != null) { vQuery = "[RSP_IngresaMantenimientos] 6, " + Session["IDTOKEN"].ToString(); vConexion.ejecutarSql(vQuery); } if (DDLTipoPermiso.SelectedValue == "1011") { String vTiempo = Session["HORAS_COMPENSATORIO"].ToString(); String vCalculo = vTiempo.Contains(",") ? vTiempo.Replace(",", ".") : vTiempo; vQuery = "RSP_ObtenerGenerales 19," + DDLEmpleado.SelectedValue; DataTable vIdPermiso = vConexion.obtenerDataTable(vQuery); vQuery = "[RSP_Compensatorio] 1, '" + Session["CODIGOSAP"].ToString() + "',0,null,'" + Session["USUARIO"].ToString() + "',Null," + vCalculo + "," + vIdPermiso.Rows[0]["idPermiso"].ToString(); int vRespuesta = vConexion.ejecutarSql(vQuery); if (vRespuesta == 2) { vRe = ", se actualizó el tiempo compensatorio."; } else { vRe = ", NO se actualizó el tiempo compensatorio."; } } // end wpadilla vQuery = "RSP_ObtenerEmpleados 2," + DDLJefe.SelectedValue; DataTable vDatosJefatura = vConexion.obtenerDataTable(vQuery); vQuery = "RSP_ObtenerEmpleados 2," + DDLEmpleado.SelectedValue; DataTable vDatosEmpleado = vConexion.obtenerDataTable(vQuery); SmtpService vService = new SmtpService(); Boolean vFlagEnvioSupervisor = false; foreach (DataRow item in vDatosJefatura.Rows) { if (!item["emailEmpresa"].ToString().Trim().Equals("")) { vService.EnviarMensaje(item["emailEmpresa"].ToString(), typeBody.Supervisor, item["nombre"].ToString(), vDatosEmpleado.Rows[0]["nombre"].ToString() ); vFlagEnvioSupervisor = true; } } if (vFlagEnvioSupervisor) { foreach (DataRow item in vDatosEmpleado.Rows) { if (!item["emailEmpresa"].ToString().Trim().Equals("")) { vService.EnviarMensaje(item["emailEmpresa"].ToString(), typeBody.Solicitante, item["nombre"].ToString(), item["nombre"].ToString() ); } } Mensaje("Permiso ingresado con exito" + vRe, WarningType.Success); Response.Redirect("/pages/permissions.aspx?ex=3"); } else { Mensaje("Permiso ingresado con exito, Fallo envio de correo ponte en contacto con tu Jefe" + vRe, WarningType.Success); } } else { Mensaje("Permiso no se ingreso o ya está creado, revise sus permisos.", WarningType.Success); } LimpiarPermiso(); CargarPermisos(); CargarDiasSAP(); CargarCompensatorio(); CerrarModal("InformativoModal"); } catch (Exception Ex) { Mensaje(Ex.Message, WarningType.Danger); } }
protected void BtnCerrarHallazgo_Click(object sender, EventArgs e) { try{ if (TxPlanAccion.Text.Equals("")) { throw new Exception("Por favor ingrese el plan de acción."); } if (TxFechaResolucionCierre.Text.Equals("")) { throw new Exception("Por favor ingrese la fecha de resolución."); } if (TxComentarioCierre.Text.Equals("")) { throw new Exception("Por favor ingrese un comentario."); } String vQuery = "[ACSP_Logs] 3," + LbInforme.Text + "," + LbHallazgo.Text + ",'comentarios','" + TxComentarioCierre.Text + "','" + Session["USUARIO"].ToString() + "'"; vConexion.ejecutarSql(vQuery); vQuery = "[ACSP_Hallazgos] 13," + LbHallazgo.Text + ",0,'','" + TxComentarioCierre.Text + "',0,0,'" + TxPlanAccion.Text + "'" + "'" + TxFechaResolucionCierre.Text + "'"; if (vConexion.ejecutarSql(vQuery).Equals(1)) { String vArchivo = "NULL"; if (FUHallazgos.HasFile) { String vNombreDeposito = String.Empty; HttpPostedFile bufferDeposito1T = FUHallazgos.PostedFile; byte[] vFileDeposito1 = null; if (bufferDeposito1T != null) { vNombreDeposito = FUHallazgos.FileName; Stream vStream = bufferDeposito1T.InputStream; BinaryReader vReader = new BinaryReader(vStream); vFileDeposito1 = vReader.ReadBytes((int)vStream.Length); } String vDeposito = Convert.ToBase64String(vFileDeposito1); vQuery = "[ACSP_Archivos] 1,'" + vNombreDeposito + "','" + vDeposito + "',1"; int?vInfo = vConexion.ejecutarSQLGetValue(vQuery); if (vInfo != null) { vArchivo = Convert.ToString(vInfo); vQuery = "[ACSP_Archivos] 2,'',''," + LbHallazgo.Text + "," + vInfo; vConexion.ejecutarSql(vQuery); } } //Actualiza idArchivoCierre del hallazgo vQuery = "[ACSP_Archivos] 3,'',''," + LbHallazgo.Text + "," + vArchivo; vConexion.ejecutarSql(vQuery); vQuery = "[ACSP_ObtenerHallazgos] 6,'" + LbHallazgo.Text + "'"; DataTable vDatosHallazgo = vConexion.obtenerDataTable(vQuery); String vUsuarioCreacion = String.Empty; foreach (DataRow item in vDatosHallazgo.Rows) { vUsuarioCreacion = item["usuarioCreacion"].ToString(); } vQuery = "[ACSP_ObtenerUsuarios] 5," + vUsuarioCreacion; DataTable vDatosResponsables = vConexion.obtenerDataTable(vQuery); Correo vCorreo = new Correo(); foreach (DataRow item in vDatosResponsables.Rows) { vCorreo.Usuario = vConexion.GetNombreUsuario(item["idUsuario"].ToString()); vCorreo.Para = item["correo"].ToString(); vCorreo.Copia = ""; } SmtpService vSmtpService = new SmtpService(); vSmtpService.EnviarMensaje( vCorreo.Para, typeBody.General, vCorreo.Usuario, "Se ha actualizado el hallazgo No." + LbHallazgo.Text + @" para cierre, por favor revisar <br \><br \>" + "Creado por:" + vConexion.GetNombreUsuario(Convert.ToString(Session["USUARIO"])), vCorreo.Copia ); MensajeLoad("Hallazgo actualizado con exito", WarningType.Success); CerrarModal("CerrarHallazgoModal"); TxHallazgoAccion.Text = TxPlanAccion.Text; TxHallazgoFechaResolucion.Text = Convert.ToDateTime(TxFechaResolucionCierre.Text).ToString("yyyy-MM-dd"); TxPlanAccion.Text = ""; TxComentarioCierre.Text = ""; mostrarOcultar(); } }catch (Exception Ex) { MensajeLoad(Ex.Message, WarningType.Danger); } }
protected void BtnSolicitar_Click(object sender, EventArgs e) { try{ if (TxMotivo.Text == string.Empty || TxMotivo.Text == "") { throw new Exception("Por favor ingrese el motivo de la ampliación."); } if (TxFechaAmpliacion.Text == string.Empty || TxFechaAmpliacion.Text == "") { throw new Exception("Por favor ingrese la fecha de ampliación."); } if (Convert.ToDateTime(TxFechaAmpliacion.Text) < Convert.ToDateTime(TxHallazgoFechaResolucion.Text)) { throw new Exception("La fecha de ampliación debe ser mayor a la de resolución."); } if (Convert.ToDateTime(TxFechaAmpliacion.Text) < DateTime.Now) { throw new Exception("La fecha de ampliación debe ser mayor a la fecha actual."); } String vQuery = "", vArchivo = "", vIdArchivo = "NULL"; if (FUDocAmpliacion.HasFile) { HttpPostedFile bufferDepositoT = FUDocAmpliacion.PostedFile; String vNombreDepot = String.Empty; byte[] vFileDeposito = null; if (bufferDepositoT != null) { vNombreDepot = FUDocAmpliacion.FileName; Stream vStream = bufferDepositoT.InputStream; BinaryReader vReader = new BinaryReader(vStream); vFileDeposito = vReader.ReadBytes((int)vStream.Length); } if (vFileDeposito != null) { vArchivo = Convert.ToBase64String(vFileDeposito); } vQuery = "[ACSP_Archivos] 1,'" + FUDocAmpliacion.FileName + "','" + vArchivo + "',2"; int vRes = vConexion.ejecutarSQLGetValue(vQuery); vIdArchivo = vRes.ToString(); if (vRes > 0) { vQuery = "[ACSP_Archivos] 2,0,0," + vIdHallazgo + "," + vIdArchivo; vConexion.ejecutarSql(vQuery); } } vQuery = "[ACSP_Ampliaciones] 1," + vIdHallazgo + "," + vIdArchivo + ",'" + TxMotivo.Text + "','" + TxFechaAmpliacion.Text + "','" + Session["USUARIO"].ToString() + "'"; int vId = vConexion.ejecutarSQLGetValue(vQuery); if (vId > 0) { String vConsul = "[ACSP_Logs] 6," + vInformeQuery + "," + vIdHallazgo + ",'comentarioAmpliacion','" + TxMotivo.Text + "','" + Session["USUARIO"].ToString() + "'"; vConexion.ejecutarSql(vConsul); vQuery = "[ACSP_Hallazgos] 10," + vIdHallazgo + "," + vId; int vInfo = vConexion.ejecutarSql(vQuery); if (vInfo == 1) { vQuery = "[ACSP_ObtenerUsuarios] 7," + vIdHallazgo; DataTable vDatosResponsables = vConexion.obtenerDataTable(vQuery); Correo vCorreo = new Correo(); foreach (DataRow item in vDatosResponsables.Rows) { vCorreo.Usuario = item["idUsuario"].ToString(); vCorreo.Para = item["correo"].ToString(); vCorreo.Copia = ""; } SmtpService vSmtpService = new SmtpService(); vSmtpService.EnviarMensaje( vCorreo.Para, typeBody.General, vCorreo.Usuario, "Se ha solicitado una ampliacion para el hallazgo (No." + vIdHallazgo + ") " + @"<br \><br \>" + "Ingresado por:" + vConexion.GetNombreUsuario(Convert.ToString(Session["USUARIO"])), vCorreo.Copia ); MensajeLoad("Solicitud realizada con éxito", WarningType.Success); BtnAmpliacion.Enabled = false; BtnAmpliacion.CssClass = "btn btn-default"; ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "closeModal();", true); } } }catch (Exception ex) { MensajeLoad(ex.Message, WarningType.Danger); } }
/// <summary> /// /// </summary> /// <param name="email"></param> /// <returns></returns> /// <exception cref="MailValidationException"></exception> public ValidationStatus Validate(string email) { if (string.IsNullOrWhiteSpace(email)) { return(ValidationStatus.AddressIsEmpty); } email = email.Trim(); MailAddress mailAddress = null; try { mailAddress = new MailAddress(email); } catch (ArgumentNullException e) { return(ValidationStatus.AddressIsEmpty); } catch (ArgumentException e) { return(ValidationStatus.AddressIsEmpty); } catch (FormatException e) { return(ValidationStatus.InvalidFormat); } if (mailAddress.Address != email) { return(ValidationStatus.InvalidFormat); } ////////////////// DomainName domainName = DomainName.Parse(mailAddress.Host); if (DisposableList.DisposableMap.IsDisposable(mailAddress.Host)) { return(ValidationStatus.MailboxIsDisposable); } DnsMessage dnsResponse = DnsClient.Default.Resolve(domainName, RecordType.Mx); IList <MxRecord> mxRecords = dnsResponse.AnswerRecords.OfType <MxRecord>().ToList(); if (mxRecords.Count == 0) { return(ValidationStatus.NoMailForDomain); } foreach (MxRecord mxRecord in mxRecords) { try { SmtpService smtpService = new SmtpService(mxRecord.ExchangeDomainName.ToString()); SmtpStatusCode resultCode; if (smtpService.CheckMailboxExists(email, out resultCode)) { switch (resultCode) { case SmtpStatusCode.Ok: return(ValidationStatus.OK); case SmtpStatusCode.ExceededStorageAllocation: return(ValidationStatus.MailboxStorageExceeded); case SmtpStatusCode.MailboxUnavailable: return(ValidationStatus.MailboxUnavailable); } } } catch (SmtpClientException) { } catch (ArgumentNullException) { } } if (mxRecords.Count > 0) { return(ValidationStatus.MailServerUnavailable); } return(ValidationStatus.Undefined); }
protected void BtnAutorizarPermiso_Click(object sender, EventArgs e) { try { SmtpService vService = new SmtpService(); String vQuery = "RSP_ObtenerPermisos 2," + Session["USUARIO"] + "," + LbNumeroPermiso.Text + "," + DDLOpciones.SelectedValue; int vDatos = vConexion.ejecutarSql(vQuery); if (vDatos.Equals(1)) { vQuery = "RSP_ObtenerPermisos 3," + Session["USUARIO"] + "," + LbNumeroPermiso.Text; DataTable vDatosBusqueda = vConexion.obtenerDataTable(vQuery); foreach (DataRow item in vDatosBusqueda.Rows) { vService.EnviarMensaje(ConfigurationManager.AppSettings["RHMail"], typeBody.RecursosHumanos, "Recursos Humanos", item["Empleado"].ToString() ); vQuery = "RSP_ObtenerGenerales 8,'" + item["EmpleadoCodigo"].ToString() + "'"; DataTable vDatosEmpleado = vConexion.obtenerDataTable(vQuery); foreach (DataRow itemEmpleado in vDatosEmpleado.Rows) { vService.EnviarMensaje(itemEmpleado["correo"].ToString(), typeBody.Aprobado, itemEmpleado["nombre"].ToString(), "" ); } } Mensaje("El empleado ha sido autorizado", WarningType.Success); CerrarModal("AutorizarModal"); } else { vQuery = "RSP_ObtenerPermisos 3," + Session["USUARIO"] + "," + LbNumeroPermiso.Text; DataTable vDatosBusqueda = vConexion.obtenerDataTable(vQuery); foreach (DataRow item in vDatosBusqueda.Rows) { vQuery = "RSP_ObtenerGenerales 8,'" + item["EmpleadoCodigo"].ToString() + "'"; DataTable vDatosEmpleado = vConexion.obtenerDataTable(vQuery); foreach (DataRow itemEmpleado in vDatosEmpleado.Rows) { vService.EnviarMensaje(itemEmpleado["correo"].ToString(), typeBody.Rechazado, item["nombre"].ToString(), "" ); } } Mensaje("El empleado no ha sido autorizado", WarningType.Success); CerrarModal("AutorizarModal"); } CargarAutorizaciones(); } catch (Exception Ex) { Mensaje(Ex.Message, WarningType.Danger); } }
void EnviarCorreo() { string id = Request.QueryString["id"]; string tipo = Request.QueryString["tipo"]; string codATM = Request.QueryString["cod"]; Boolean vFlagEnvio = false; String vDestino = ""; SmtpService vService = new SmtpService(); //string vCorreoEncargadoZona = ""; //if (Convert.ToString(Session["IDZona"]) == "1") // vCorreoEncargadoZona = "*****@*****.**"; //if (Convert.ToString(Session["IDZona"]) == "2") // vCorreoEncargadoZona = "*****@*****.**"; //if (Convert.ToString(Session["IDZona"]) == "3") // vCorreoEncargadoZona = "*****@*****.**"; string vQueryD = "STEISP_ATM_Generales 33,'" + DLLtecResponsable.SelectedValue + "'"; DataTable vDatosTecnicoResponsable = vConexion.ObtenerTabla(vQueryD); DataTable vDatos = (DataTable)Session["AUTHCLASS"]; string vQueryJefes = "[STEISP_ATM_GeneralesCorrectivo] 13,'" + codATM + "','" + txtsysaid.Text + "'"; DataTable vDatosJefeAgencias = vConexion.ObtenerTabla(vQueryJefes); if (vDatos.Rows.Count > 0) { foreach (DataRow item in vDatos.Rows) { //ENVIAR A JEFE CREADOR if (!item["correo"].ToString().Trim().Equals("")) { vService.EnviarMensaje(item["correo"].ToString(), typeBody.ATM, "Notificación de Mantenimiento Correctivo ATM", "Buen día, se le notifica que se creó una solicitud de mantenimiento correctivo, el encargado es " + vDatosTecnicoResponsable.Rows[0]["nombre"].ToString() + ", mantenimiento al ATM " + txtATM.Text, "El usuario <b>" + item["Nombre"].ToString() + "</b> creó: <br> Notificación de Mantenimiento Correctivo", "", "/sites/ATM/pages/correctivo/notificarCorrectivo.aspx" ); //vFlagEnvioSupervisor = true; } //ENVIAR A EDWIN //string vNombre = "EDWIN ALBERTO URREA PENA"; vService.EnviarMensaje(ConfigurationManager.AppSettings["STEIMail"], typeBody.ATM, "Notificación de Mantenimiento correctivo ATM", "Buen día, se le notifica que se creó solicitud de mantenimiento correctivo, el encargado es " + vDatosTecnicoResponsable.Rows[0]["nombre"].ToString() + ", mantenimiento al ATM " + txtATM.Text, "El usuario <b>" + item["Nombre"].ToString() + "</b> creó: <br> Notificación de Mantenimiento", "",//vCorreoEncargadoZona, "/sites/ATM/pages/correctivo/notificarCorrectivo.aspx" ); //PRSONAL ENCARGADO DE ATM String vKioskos = "*****@*****.**"; vService.EnviarMensaje(vKioskos, typeBody.ATM, "Notificación de Mantenimiento correctivo ATM", "Buen día, se le notifica que se ha creado una solicitud de mantenimiento correctivo, el encargado es " + vDatosTecnicoResponsable.Rows[0]["nombre"].ToString() + ", mantenimiento al ATM " + txtATM.Text, "El usuario <b>" + item["Nombre"].ToString() + "</b> creó: <br> Notificación de Mantenimiento", "", "" ); } } if (vDatosTecnicoResponsable.Rows.Count > 0) { foreach (DataRow item in vDatosTecnicoResponsable.Rows) { //ENVIAR A RESPONSABLE vService.EnviarMensaje(item["correo"].ToString(), typeBody.ATM, "Notificación de Mantenimiento correctivo ATM", "Buen día, se le notifica que se creó solicitud de mantenimientocorrectivo, el encargado es " + item["nombre"].ToString() + ", mantenimiento al ATM " + txtATM.Text, "El usuario <b>" + vDatos.Rows[0]["Nombre"].ToString() + "</b> creó: <br> Notificación de Mantenimiento de ATM al que ha sido asignado como responsable.", "", "/login.spx" ); } } if (vDatosJefeAgencias.Rows.Count > 0) { foreach (DataRow item in vDatosJefeAgencias.Rows) { //ENVIAR A JEFES DE AGENCIA if (!item["correo"].ToString().Trim().Equals("")) { vService.EnviarMensaje(item["correo"].ToString(), typeBody.ATM, "Notificación de Mantenimiento ATM", "Buen día, se le notifica que se aprobó solicitud de mantenimiento correctivo, el encargado es " + vDatosTecnicoResponsable.Rows[0]["nombre"].ToString() + ", mantenimiento al ATM " + txtATM.Text, "Solicitud de mantenimiento correctivo a ATM.", "", "" ); } } } }
/// <summary> /// Returns the desired command based on the provided <see cref="OptionObject2015"/> and parameter. /// </summary> /// <param name="optionObject"></param> /// <param name="parameter"></param> /// <returns></returns> public static IRunScriptCommand GetCommand(OptionObject2015 optionObject, string parameter) { if (optionObject == null) { logger.Error("The provided {object} is null", nameof(OptionObject2015)); return(new DefaultCommand(optionObject, parameter)); } // Determine ScriptName logger.Debug("Parameter for scriptName is: " + parameter); string scriptName = parameter != null?parameter.Split(',')[0] : ""; logger.Debug("Script '" + scriptName + "' requested."); // Get Dependencies // Replace with this line when ready to do ODBC from SBOX and BLD //ConnectionStringCollection odbcConnectionStrings = ConnectionStringSelector.GetConnectionStringCollection(optionObject.Facility, optionObject.NamespaceName); ConnectionStringCollection odbcConnectionStrings = ConnectionStringSelector.GetConnectionStringCollection(optionObject.Facility); logger.Debug("Facility is: " + optionObject.Facility); var repository = new GetOdbcDataRepository(odbcConnectionStrings); logger.Debug("Repository is: " + repository.ToString()); var smtpService = new SmtpService(); logger.Debug("SMTP is: " + smtpService.ToString()); // Select Command, Not Case Sensitive switch (scriptName.ToUpperInvariant().Trim()) { // General Commands case "ADDDURATIONANDTIME": logger.Debug(nameof(AddDurationAndTimeCommand) + " selected."); return(new AddDurationAndTimeCommand(optionObject, parameter)); case "CHKCHRS": logger.Debug(nameof(ChkChrsCommand) + " selected."); return(new ChkChrsCommand(optionObject, parameter)); // PM Commands case "DIAGNOSISFORMLOAD": logger.Debug(nameof(DiagnosisFormLoadCommand) + " selected."); return(new DiagnosisFormLoadCommand(optionObject, repository)); // CWS Commands // Testing and Sample ("Utility") Commands case "GETODBCDATA": logger.Debug(nameof(GetOdbcDataCommand) + " selected."); return(new GetOdbcDataCommand(optionObject, repository)); case "HELLOWORLD": logger.Debug(nameof(HelloWorldCommand) + " selected."); return(new HelloWorldCommand(optionObject)); case "SENDTESTEMAIL": logger.Debug(nameof(SendTestEmailCommand) + " selected."); return(new SendTestEmailCommand(optionObject, parameter, smtpService)); // If nothing matches default: logger.Warn(nameof(DefaultCommand) + " selected because ScriptName '" + scriptName + "' does not match an existing command."); return(new DefaultCommand(optionObject, parameter)); } }
internal void SendEmail(Email email, SmtpService service) { try { if (service == null) { email.ServerError = "SMTP service not found"; email.Status = EmailStatus.Aborted; return; //save email in finally block will save changes } else if (!service.IsEnabled) { email.ServerError = "SMTP service is not enabled"; email.Status = EmailStatus.Aborted; return; //save email in finally block will save changes } var message = new MimeMessage(); if (!string.IsNullOrWhiteSpace(email.SenderName)) { message.From.Add(new MailboxAddress(email.SenderName, email.SenderEmail)); } else { message.From.Add(new MailboxAddress(email.SenderEmail)); } if (!string.IsNullOrWhiteSpace(email.RecipientName)) { message.To.Add(new MailboxAddress(email.RecipientName, email.RecipientEmail)); } else { message.To.Add(new MailboxAddress(email.RecipientEmail)); } if (!string.IsNullOrWhiteSpace(email.ReplyToEmail)) { message.ReplyTo.Add(new MailboxAddress(email.ReplyToEmail)); } message.Subject = email.Subject; var bodyBuilder = new BodyBuilder(); bodyBuilder.HtmlBody = email.ContentHtml; bodyBuilder.TextBody = email.ContentText; message.Body = bodyBuilder.ToMessageBody(); using (var client = new SmtpClient()) { //accept all SSL certificates (in case the server supports STARTTLS) client.ServerCertificateValidationCallback = (s, c, h, e) => true; client.Connect(service.Server, service.Port, service.ConnectionSecurity); if (!string.IsNullOrWhiteSpace(service.Username)) { client.Authenticate(service.Username, service.Password); } client.Send(message); client.Disconnect(true); } email.SentOn = DateTime.UtcNow; email.Status = EmailStatus.Sent; email.ScheduledOn = null; email.ServerError = null; } catch (Exception ex) { email.SentOn = null; email.ServerError = ex.Message; email.RetriesCount++; if (email.RetriesCount >= service.MaxRetriesCount) { email.ScheduledOn = null; email.Status = EmailStatus.Aborted; } else { email.ScheduledOn = DateTime.UtcNow.AddMinutes(service.RetryWaitMinutes); email.Status = EmailStatus.Pending; } } finally { new SmtpInternalService().SaveEmail(email); } }
internal void SendEmail(Email email, SmtpService service) { try { if (service == null) { email.ServerError = "SMTP service not found"; email.Status = EmailStatus.Aborted; return; //save email in finally block will save changes } else if (!service.IsEnabled) { email.ServerError = "SMTP service is not enabled"; email.Status = EmailStatus.Aborted; return; //save email in finally block will save changes } var message = new MimeMessage(); if (!string.IsNullOrWhiteSpace(email.Sender?.Name)) { message.From.Add(new MailboxAddress(email.Sender?.Name, email.Sender?.Address)); } else { message.From.Add(new MailboxAddress(email.Sender?.Address)); } foreach (var recipient in email.Recipients) { if (recipient.Address.StartsWith("cc:")) { if (!string.IsNullOrWhiteSpace(recipient.Name)) { message.Cc.Add(new MailboxAddress(recipient.Name, recipient.Address.Substring(3))); } else { message.Cc.Add(new MailboxAddress(recipient.Address.Substring(3))); } } else if (recipient.Address.StartsWith("bcc:")) { if (!string.IsNullOrWhiteSpace(recipient.Name)) { message.Bcc.Add(new MailboxAddress(recipient.Name, recipient.Address.Substring(4))); } else { message.Bcc.Add(new MailboxAddress(recipient.Address.Substring(4))); } } else { if (!string.IsNullOrWhiteSpace(recipient.Name)) { message.To.Add(new MailboxAddress(recipient.Name, recipient.Address)); } else { message.To.Add(new MailboxAddress(recipient.Address)); } } } if (!string.IsNullOrWhiteSpace(email.ReplyToEmail)) { string[] replyToEmails = email.ReplyToEmail.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (var replyEmail in replyToEmails) { message.ReplyTo.Add(new MailboxAddress(replyEmail)); } } else { message.ReplyTo.Add(new MailboxAddress(email.Sender?.Address)); } message.Subject = email.Subject; var bodyBuilder = new BodyBuilder(); bodyBuilder.HtmlBody = email.ContentHtml; bodyBuilder.TextBody = email.ContentText; if (email.Attachments != null && email.Attachments.Count > 0) { foreach (var att in email.Attachments) { var filepath = att; if (!filepath.StartsWith("/")) { filepath = "/" + filepath; } filepath = filepath.ToLowerInvariant(); if (filepath.StartsWith("/fs")) { filepath = filepath.Substring(3); } DbFileRepository fsRepository = new DbFileRepository(); var file = fsRepository.Find(filepath); var bytes = file.GetBytes(); var extension = Path.GetExtension(filepath).ToLowerInvariant(); new FileExtensionContentTypeProvider().Mappings.TryGetValue(extension, out string mimeType); var attachment = new MimePart(mimeType) { Content = new MimeContent(new MemoryStream(bytes)), ContentDisposition = new ContentDisposition(ContentDisposition.Attachment), ContentTransferEncoding = ContentEncoding.Base64, FileName = Path.GetFileName(filepath) }; bodyBuilder.Attachments.Add(attachment); } } ProcessHtmlContent(bodyBuilder); message.Body = bodyBuilder.ToMessageBody(); using (var client = new SmtpClient()) { //accept all SSL certificates (in case the server supports STARTTLS) client.ServerCertificateValidationCallback = (s, c, h, e) => true; client.Connect(service.Server, service.Port, service.ConnectionSecurity); if (!string.IsNullOrWhiteSpace(service.Username)) { client.Authenticate(service.Username, service.Password); } client.Send(message); client.Disconnect(true); } email.SentOn = DateTime.UtcNow; email.Status = EmailStatus.Sent; email.ScheduledOn = null; email.ServerError = null; } catch (Exception ex) { email.SentOn = null; email.ServerError = ex.Message; email.RetriesCount++; if (email.RetriesCount >= service.MaxRetriesCount) { email.ScheduledOn = null; email.Status = EmailStatus.Aborted; } else { email.ScheduledOn = DateTime.UtcNow.AddMinutes(service.RetryWaitMinutes); email.Status = EmailStatus.Pending; } } finally { new SmtpInternalService().SaveEmail(email); } }
private Result <bool> SendMailChangeVerification(string email, Customer customer) { string body = $"Dear {customer.Name}, your email address has been changed to {customer.EmailAddress}."; return(Result <bool> .FromBool(SmtpService.SendMail(email, "Your email address has changed", body))); }
public ActionResult Edit(WebOrderRequestEditViewModel viewModel) { string emailRecipientList = String.Empty; ResultContainer resultContainer = null; GRINGlobalService grinGlobalService = new GRINGlobalService(this.AuthenticatedUserSession.Environment); SmtpService smtpService = new SmtpService(); try { WebOrderRequest webOrderRequest = new WebOrderRequest(); webOrderRequest.ID = viewModel.ID; webOrderRequest.StatusCode = viewModel.Action; if (viewModel.Action == OrderRequestAction.NRRReviewEnd) { grinGlobalService.SetReviewStatus(viewModel.ID, AuthenticatedUser.Cooperator.WebCooperator.ID, false); } else { if ((viewModel.Action != "NRR_NOTE") && (viewModel.Action != "NRR_INFO")) { resultContainer = grinGlobalService.UpdateWebOrderRequest(webOrderRequest); } resultContainer = grinGlobalService.AddWebOrderRequestAction(new WebOrderRequestAction { WebOrderRequestID = viewModel.ID, ActionCode = viewModel.Action, Note = viewModel.ActionNote, CreatedByCooperatorID = AuthenticatedUser.WebUserID }); if (viewModel.Action == "NRR_APPROVE") { emailRecipientList = grinGlobalService.GetEmailNotificationList(viewModel.ID); grinGlobalService.SendEmail(viewModel.ID, "CAP", emailRecipientList); resultContainer = grinGlobalService.AddWebOrderRequestAction(new WebOrderRequestAction { WebOrderRequestID = viewModel.ID, ActionCode = viewModel.Action, Note = viewModel.ActionNote, CreatedByCooperatorID = AuthenticatedUser.WebUserID }); } else if (viewModel.Action == "NRR_REJECT") { emailRecipientList = grinGlobalService.GetEmailNotificationList(viewModel.ID); grinGlobalService.SendEmail(viewModel.ID, "CCL", emailRecipientList); grinGlobalService.SendEmail(viewModel.ID, "RRJ", viewModel.WebCooperator.EmailAddress); resultContainer = grinGlobalService.AddWebOrderRequestAction(new WebOrderRequestAction { WebOrderRequestID = viewModel.ID, ActionCode = viewModel.Action, Note = viewModel.ActionNote, CreatedByCooperatorID = AuthenticatedUser.WebUserID }); } else if (viewModel.Action == "NRR_INFO") { grinGlobalService.SendEmail(viewModel.ID, "RQI", viewModel.WebCooperator.EmailAddress); } if (resultContainer.ResultCode == ResultContainer.ResultCodeValue.Error.ToString()) { throw new Exception("Error sending mail: " + resultContainer.ResultMessage + resultContainer.ResultDescription); } } if ((viewModel.Action != "NRR_NOTE") && (viewModel.Action != "NRR_INFO")) { return(RedirectToAction("Index", "WebOrder")); } else { return(RedirectToAction("Edit", "WebOrder", new { id = viewModel.ID })); } } catch (Exception ex) { Log.Error(ex, ex.Message); return(RedirectToAction("InternalServerError", "Error")); } }
public IActionResult TestSmtpServiceOnPost(RecordDetailsPageModel pageModel) { SmtpService smtpService = null; string recipientEmail = string.Empty; string subject = string.Empty; string content = string.Empty; ValidationException valEx = new ValidationException(); if (pageModel.HttpContext.Request.Form == null) { valEx.AddError("form", "Smtp service test page missing form tag"); valEx.CheckAndThrow(); } if (!pageModel.HttpContext.Request.Form.ContainsKey("recipient_email")) { valEx.AddError("recipient_email", "Recipient email is not specified."); } else { recipientEmail = pageModel.HttpContext.Request.Form["recipient_email"]; if (string.IsNullOrWhiteSpace(recipientEmail)) { valEx.AddError("recipient_email", "Recipient email is not specified"); } else if (!recipientEmail.IsEmail()) { valEx.AddError("recipient_email", "Recipient email is not a valid email address"); } } if (!pageModel.HttpContext.Request.Form.ContainsKey("subject")) { valEx.AddError("subject", "Subject is not specified"); } else { subject = pageModel.HttpContext.Request.Form["subject"]; if (string.IsNullOrWhiteSpace(subject)) { valEx.AddError("subject", "Subject is required"); } } if (!pageModel.HttpContext.Request.Form.ContainsKey("content")) { valEx.AddError("content", "Content is not specified"); } else { content = pageModel.HttpContext.Request.Form["content"]; if (string.IsNullOrWhiteSpace(content)) { valEx.AddError("content", "Content is required"); } } var smtpServiceId = pageModel.DataModel.GetProperty("Record.id") as Guid?; if (smtpServiceId == null) { valEx.AddError("serviceId", "Invalid smtp service id"); } else { smtpService = new EmailServiceManager().GetSmtpService(smtpServiceId.Value); if (smtpService == null) { valEx.AddError("serviceId", "Smtp service with specified id does not exist"); } } List <string> attachments = new List <string>(); if (pageModel.HttpContext.Request.Form.ContainsKey("attachments")) { var ids = pageModel.HttpContext.Request.Form["attachments"].ToString().Split(",", StringSplitOptions.RemoveEmptyEntries).Select(x => new Guid(x)); foreach (var id in ids) { var fileRecord = new EqlCommand("SELECT name,path FROM user_file WHERE id = @id", new EqlParameter("id", id)).Execute().FirstOrDefault(); if (fileRecord != null) { attachments.Add((string)fileRecord["path"]); } } } //we set current record to store properties which don't exist in current entity EntityRecord currentRecord = pageModel.DataModel.GetProperty("Record") as EntityRecord; currentRecord["recipient_email"] = recipientEmail; currentRecord["subject"] = subject; currentRecord["content"] = content; pageModel.DataModel.SetRecord(currentRecord); valEx.CheckAndThrow(); try { EmailAddress recipient = new EmailAddress(recipientEmail); smtpService.SendEmail(recipient, subject, string.Empty, content, attachments: attachments); pageModel.TempData.Put("ScreenMessage", new ScreenMessage() { Message = "Email was successfully sent", Type = ScreenMessageType.Success, Title = "Success" }); var returnUrl = pageModel.HttpContext.Request.Query["returnUrl"]; return(new RedirectResult($"/mail/services/smtp/r/{smtpService.Id}/details?returnUrl={returnUrl}")); } catch (Exception ex) { valEx.AddError("", ex.Message); valEx.CheckAndThrow(); return(null); } }
protected void BtnAutorizarPermiso_Click(object sender, EventArgs e) { try{ SmtpService vService = new SmtpService(); String vQuery = "RSP_ObtenerPermisos 2," + Session["USUARIO"] + "," + LbNumeroPermiso.Text + "," + DDLOpciones.SelectedValue + ",'" + TxMotivoJefe.Text + "'"; int vDatos = vConexion.ejecutarSql(vQuery); if (vDatos.Equals(1)) { if (DDLOpciones.SelectedValue.Equals("1")) { vQuery = "RSP_ObtenerPermisos 3," + Session["USUARIO"] + "," + LbNumeroPermiso.Text; DataTable vDatosBusqueda = vConexion.obtenerDataTable(vQuery); foreach (DataRow item in vDatosBusqueda.Rows) { vService.EnviarMensaje(ConfigurationManager.AppSettings["RHMail"], typeBody.RecursosHumanos, "Recursos Humanos", item["Empleado"].ToString() ); vQuery = "RSP_ObtenerGenerales 8,'" + item["EmpleadoCodigo"].ToString() + "'"; DataTable vDatosEmpleado = vConexion.obtenerDataTable(vQuery); foreach (DataRow itemEmpleado in vDatosEmpleado.Rows) { vService.EnviarMensaje(itemEmpleado["correo"].ToString(), typeBody.Aprobado, itemEmpleado["nombre"].ToString(), "" ); } } Mensaje("El empleado ha sido autorizado", WarningType.Success); CerrarModal("AutorizarModal"); } else { if (TxMotivoJefe.Text != "" || TxMotivoJefe.Text != string.Empty) { vQuery = "RSP_ObtenerPermisos 7,''," + LbNumeroPermiso.Text + ",0,'" + TxMotivoJefe.Text + "'"; vDatos = vConexion.ejecutarSql(vQuery); vQuery = "RSP_ObtenerPermisos 3," + Session["USUARIO"] + "," + LbNumeroPermiso.Text; DataTable vDatosBusqueda = vConexion.obtenerDataTable(vQuery); foreach (DataRow item in vDatosBusqueda.Rows) { vQuery = "RSP_ObtenerGenerales 8,'" + item["EmpleadoCodigo"].ToString() + "'"; DataTable vDatosEmpleado = vConexion.obtenerDataTable(vQuery); foreach (DataRow itemEmpleado in vDatosEmpleado.Rows) { vService.EnviarMensaje(itemEmpleado["correo"].ToString(), typeBody.Rechazado, itemEmpleado["nombre"].ToString(), "Razón de Cancelación: " + TxMotivo.Text ); } // DEVOLVER TIEMPO COMPENSATORIO if (vDatosBusqueda.Rows[0]["TipoPermiso"].ToString() == "DÍAS/HORAS COMPENSATORIOS") { TimeSpan tsHorario = Convert.ToDateTime(item["FechaRegreso"]) - Convert.ToDateTime(item["FechaInicio"]); Decimal vDiasHoras = tsHorario.Hours + (Convert.ToDecimal(tsHorario.Minutes) / 60); String vCalculo = vDiasHoras.ToString().Contains(",") ? vDiasHoras.ToString().Replace(",", ".") : vDiasHoras.ToString(); vQuery = "[RSP_Compensatorio] 1,'" + item["CodigoSAP"].ToString() + "', 2,NULL,'" + Session["USUARIO"].ToString() + "',NULL," + vCalculo + "," + item["idPermiso"].ToString(); int vInfo = vConexion.ejecutarSql(vQuery); } } Mensaje("El empleado no ha sido autorizado", WarningType.Success); CerrarModal("AutorizarModal"); } else { LbAutorizarMensaje.Text = "Favor ingresar el motivo de cancelación."; } } } CargarAutorizaciones(); } catch (Exception Ex) { Mensaje(Ex.Message, WarningType.Danger); } }
public async Task <ActionResult> EmailBody() { DateTime today = DateTime.UtcNow.ToUtcID(); IMailService _mailService = new SmtpService(); UserAuthenticated _userAuth = new UserAuthenticated() { Fullname = "FSS Uploader", NIK = 10001234 }; List <SalesCustomerViewModel> listData = new List <SalesCustomerViewModel>(); listData.Add(new SalesCustomerViewModel() { Id = "232323", RayonCode = "RXDA23874324", SLMFullname = "Salesman Satu", CustomerCode = "234234", CustomerName = "Kimia Farma, AP", FormattedValidFrom = "2019-09-01", FormattedValidTo = "9999-12-31" }); listData.Add(new SalesCustomerViewModel() { Id = "232323", RayonCode = "RXDA23874324", SLMFullname = "Salesman Dua", CustomerCode = "234234", CustomerName = "Kimia Farma, AP", FormattedValidFrom = "2019-09-01", FormattedValidTo = "9999-12-31" }); listData.Add(new SalesCustomerViewModel() { Id = "232323", RayonCode = "RXDA23874324", SLMFullname = "Salesman Tiga", CustomerCode = "234234", CustomerName = "Kimia Farma, AP", FormattedValidFrom = "2019-09-01", FormattedValidTo = "9999-12-31" }); listData.Add(new SalesCustomerViewModel() { Id = "232323", RayonCode = "RXDA23874324", SLMFullname = "Salesman Empat", CustomerCode = "234234", CustomerName = "Kimia Farma, AP", FormattedValidFrom = "2019-09-01", FormattedValidTo = "9999-12-31" }); listData.Add(new SalesCustomerViewModel() { Id = "232323", RayonCode = "RXDA23874324", SLMFullname = "Salesman Lima", CustomerCode = "234234", CustomerName = "Kimia Farma, AP", FormattedValidFrom = "2019-09-01", FormattedValidTo = "9999-12-31" }); StringBuilder htmlRows = new StringBuilder(); foreach (var data in listData) { htmlRows.Append("<tr>"); htmlRows.Append($"<td style=\"text-align: center; font-family: 'Source Sans Pro', Helvetica, Arial, sans-serif; font-size: 11px; color: #333333;\">{data.Id}</td>"); htmlRows.Append($"<td style=\"text-align: center; font-family: 'Source Sans Pro', Helvetica, Arial, sans-serif; font-size: 11px; color: #333333;\">{data.RayonCode}</td>"); htmlRows.Append($"<td style=\"text-align: left; font-family: 'Source Sans Pro', Helvetica, Arial, sans-serif; font-size: 11px; color: #333333;\">{data.SLMFullname}</td>"); htmlRows.Append($"<td style=\"text-align: center; font-family: 'Source Sans Pro', Helvetica, Arial, sans-serif; font-size: 11px; color: #333333;\">{data.CustomerCode}</td>"); htmlRows.Append($"<td style=\"text-align: left; font-family: 'Source Sans Pro', Helvetica, Arial, sans-serif; font-size: 11px; color: #333333;\">{data.CustomerName}</td>"); htmlRows.Append($"<td style=\"text-align: center; font-family: 'Source Sans Pro', Helvetica, Arial, sans-serif; font-size: 11px; color: #333333;\">{data.FormattedValidFrom}</td>"); htmlRows.Append($"<td style=\"text-align: center; font-family: 'Source Sans Pro', Helvetica, Arial, sans-serif; font-size: 11px; color: #333333;\">{data.FormattedValidTo}</td>"); htmlRows.Append("</tr>"); } string partialView = System.IO.File.ReadAllText(Path.Combine(_mailService.GetDirLayout(), EmailConstant.ViewPartialMasterListDouble)); partialView = partialView.Replace("{:ROW_DOUBLE_MASTER_LIST}", htmlRows.ToString()); Dictionary <string, string> dcParams = new Dictionary <string, string>() { { "{:FULLNAME}", "NSM ABCD" }, { "{:UPLOADER_NIK}", _userAuth.NIK.ToString() }, { "{:UPLOADER_NAME}", _userAuth.Fullname }, { "{:FORMATTED_DATE}", today.ToString("yyyy-MM-dd HH:mm") }, }; string view = EmailConstant.ViewMasterListSalesUploaded; string content = _mailService.GetBodyFromView(view, dcParams); content = content.Replace("{:PARTIAL_MASTER_LIST_DOUBLE}", partialView); string subject = EmailConstant.SubjectPrefix + string.Format("{0} [{1}] Upload Hirarki Sales", _userAuth.Fullname, _userAuth.NIK); List <string> listTo = new List <string>() { "*****@*****.**" }; //await _mailService.Send(view, subject, listTo); return(Content(content)); }
protected void BtnFinalizarPermiso_Click(object sender, EventArgs e) { try{ if (DDlFinalizarPermiso.SelectedValue.Equals("1")) { String vQuery = "RSP_ObtenerPermisos 3," + Session["USUARIO"] + "," + LbFinalizarPermiso.Text; DataTable vDatosPermiso = vConexion.obtenerDataTable(vQuery); String vResponse = String.Empty; String vMensaje = String.Empty; foreach (DataRow item in vDatosPermiso.Rows) { SapConnector vConnector = new SapConnector(); vResponse = vConnector.postPermiso( Convert.ToDateTime(item["fechaInicio"].ToString()), Convert.ToDateTime(item["fechaRegreso"].ToString()), item["CodigoSAP"].ToString(), item["TipoPermisoCodigo"].ToString(), item["SubTipoPermiso"].ToString(), item["Motivo"].ToString(), ref vMensaje ); } switch (vResponse) { case "": Mensaje("Error al enviar a SAP", WarningType.Success); break; case "0": vQuery = "RSP_ObtenerPermisos 4," + Session["USUARIO"] + "," + LbFinalizarPermiso.Text + ",1"; int vDatos = vConexion.ejecutarSql(vQuery); if (vDatos.Equals(1)) { Mensaje("El empleado ha sido autorizado en SAP", WarningType.Success); } else { Mensaje("El empleado ha sido autorizado en SAP, pero no inserto la verificación", WarningType.Success); } break; case "1": Mensaje(vMensaje, WarningType.Success); break; } CerrarModal("FinalizarModal"); CargarAutorizaciones(); } else { if (TxMotivo.Text == string.Empty || TxMotivo.Text == "") { Label2.Text = "Favor ingresar el motivo de cancelación."; } else { String vQuery = "RSP_ObtenerPermisos 4," + Session["USUARIO"] + "," + LbFinalizarPermiso.Text + ",0,'" + TxMotivo.Text + "'"; int vDatos = vConexion.ejecutarSql(vQuery); if (vDatos.Equals(1)) { String vQueryCancelacion = "RSP_ObtenerPermisos 2," + Session["USUARIO"] + "," + LbFinalizarPermiso.Text + "," + 0; int vDatosCancelacion = vConexion.ejecutarSql(vQueryCancelacion); vQuery = "RSP_ObtenerPermisos 3," + Session["USUARIO"] + "," + LbFinalizarPermiso.Text; DataTable vDatosBusqueda = vConexion.obtenerDataTable(vQuery); foreach (DataRow itemEmpleado in vDatosBusqueda.Rows) { SmtpService vService = new SmtpService(); vService.EnviarMensaje(itemEmpleado["correo"].ToString(), typeBody.Rechazado, itemEmpleado["nombre"].ToString(), "Razón de Cancelación: " + TxMotivo.Text ); if (vDatosBusqueda.Rows[0]["TipoPermiso"].ToString() == "DÍAS/HORAS COMPENSATORIOS") { Boolean vDia = itemEmpleado["FechaRegreso"].ToString() == itemEmpleado["FechaInicio"].ToString() ? true : false; TimeSpan tsHorario = Convert.ToDateTime(itemEmpleado["FechaRegreso"]) - Convert.ToDateTime(itemEmpleado["FechaInicio"]); Decimal vDiasHoras = tsHorario.Hours + (Convert.ToDecimal(tsHorario.Minutes) / 60); vDiasHoras = vDia ? 8 : vDiasHoras; String vCalculo = vDiasHoras.ToString().Contains(",") ? vDiasHoras.ToString().Replace(",", ".") : vDiasHoras.ToString(); String vEmpleado = ""; if (itemEmpleado["idEmpleadoJefe"].ToString() == itemEmpleado["usuarioCreacion"].ToString()) { vEmpleado = itemEmpleado["idEmpleadoJefe"].ToString(); } else { vEmpleado = itemEmpleado["CodigoSAP"].ToString(); } vQuery = "[RSP_Compensatorio] 1,'" + vEmpleado + "', 2,NULL,'" + Session["USUARIO"].ToString() + "',NULL," + vCalculo + "," + itemEmpleado["idPermiso"].ToString(); int vInfo = vConexion.ejecutarSql(vQuery); } } Mensaje("Se ha cancelado el permiso", WarningType.Success); } else { Mensaje("No se ha podido cancelar el servicio en el sistema, contacte a sistemas", WarningType.Success); } CerrarModal("FinalizarModal"); CargarAutorizaciones(); } } }catch (Exception Ex) { Mensaje(Ex.Message, WarningType.Danger); } }