protected void SubmitBtn_Click(object sender, EventArgs e) { AccessDB dbObj = new AccessDB(); dbObj.Open(); dbObj.Query = string.Format("Select emailaddress,CAST( AES_DECRYPT( passwd, 'kalli' ) AS CHAR( 100 ) ) from tbluserlogin where emailaddress ='{1}'", Constants.AESKey, UserNameTbx.Text); dbObj.ExecuteQuery(); if (dbObj.Dataset.Tables[0].Rows.Count > 0) { Mail mailObj = new Mail(); mailObj.To = UserNameTbx.Text; mailObj.Subject = "Reply: Forgot Password Request"; mailObj.MailBody = string.Format("Dear Ma'am/Sir, \r\n Username:{0} \r\n Password:{1} \r\n Regards, \r\n Admin team.", UserNameTbx.Text, dbObj.Dataset.Tables[0].Rows[0][1]); mailObj.SendMailMessage(); VerificationLbl.Text = "Your password has been sent to your email."; VerificationLbl.Visible = true; } else { VerificationLbl.Text = "The UserName provided is not valid.Kindly verify and retry / contact the Admin Team."; VerificationLbl.Visible = true; } dbObj.Close(); }
public static void Send(Mail mail) { MailMessage msg = new MailMessage(); msg.From = new MailAddress(mail.From, "Money Pacific Service"); msg.To.Add(new MailAddress(mail.To)); msg.Subject = mail.Subject; msg.Body = mail.Body; msg.IsBodyHtml = true; msg.BodyEncoding = new System.Text.UTF8Encoding(); msg.Priority = MailPriority.High; SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; System.Net.NetworkCredential user = new System.Net.NetworkCredential( ConfigurationManager.AppSettings["sender"], ConfigurationManager.AppSettings["senderPass"] ); smtp.EnableSsl = true; smtp.Credentials = user; smtp.Port = 587; //or use 465 object userState = msg; try { //you can also call client.Send(msg) smtp.SendAsync(msg, userState); } catch (SmtpException) { //Catch errors... } }
public void SaveRead_Test() { var mail = new Mail(logger); var mlName = "1ban"; MlDb mlDb = new MlDb(logger, dir,mlName); mlDb.Remove();//もし、以前のメールが残っていたらTESTが誤動作するので、ここで消しておく Assert.AreEqual(mlDb.Count(), 0); var max = 10;//試験件数10件 //保存と、 for (int i = 0; i < max; i++) { var b = mlDb.Save( mail); Assert.AreEqual(b,true);//保存が成功しているか Assert.AreEqual(mlDb.Count(), i+1);//連番がインクリメントしているか } //範囲外のメール取得でnullが返るか //no==1..10が取得可能 var m = mlDb.Read(0);//範囲外 Assert.IsNull(m); //範囲内 for (int no = 1; no <= max; no++) { m = mlDb.Read(no); Assert.NotNull(mlDb.Read(no)); } //範囲外 m = mlDb.Read(11); Assert.IsNull(m); mlDb.Remove(); }
// tag::buildAndSendMail[] public void DoBuildAndSendMail(MailMan m, MailAddress mAddress, MailBody mBody) { // Build the mail Mail mail = new Mail(mAddress, mBody); // Send the mail m.SendMail(mail); }
public Mensaje createComentario([FromBody]UtilsJson.AContacto comentario) { Mensaje mensaje = null; try { //datos logueo string nombre = comentario.nombre_contacto; string telefono = comentario.telefono_contacto; string email = comentario.email_contacto; string messangeC = comentario.comentario_contacto; Contacto contacto = new Contacto(nombre, telefono, email, messangeC); contacto.fecha_ult_modificacion = DateTime.Now; _repositorio.SaveOrUpdate(contacto); //Envio email confirmacion para habilitar el perfil StringBuilder bodyMail = new StringBuilder(); bodyMail.AppendLine("Comentario enviado por: " + nombre); bodyMail.AppendLine("Telefono: " + telefono); bodyMail.Append(comentario); string subject = "Comentario o sugerencia. " + email; Mail mail = new Mail("*****@*****.**", subject, bodyMail); mail.sendMail(); mensaje = new Mensaje(EnumTipoMensaje.Notificacion, "Notificación", "Comentario procesado exitosamente."); } catch (Exception ex) { mensaje = new Mensaje(EnumTipoMensaje.Error, "Error", "Ocurrio un error mientras se procesaba su solicitud."); } return mensaje; }
public async Task SendAsync(IdentityMessage message) { //var myMessage = new SendGridMessage(); //myMessage.AddTo(message.Destination); //myMessage.From = new MailAddress("*****@*****.**", "fzrain"); //myMessage.Subject = message.Subject; //myMessage.Text = message.Body; //myMessage.Html = message.Body; //var credentials = new NetworkCredential("fzy55601", "fzy86087108"); //// Create a Web transport for sending email. //var transportWeb = new Web(credentials); //// Send the email. //await transportWeb.DeliverAsync(myMessage); String apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY", EnvironmentVariableTarget.User); dynamic sg = new SendGridAPIClient(apiKey); Email from = new Email("*****@*****.**"); String subject = "Hello World from the SendGrid CSharp Library"; Email to = new Email("*****@*****.**"); Content content = new Content("text/plain", "Textual content"); Mail mail = new Mail(from, subject, to, content); dynamic response = sg.client.mail.send.post(requestBody: mail.Get()); }
public static string GetEmailBody(Mail emailName, object model) { var templatePath = physicalApplicationPath + @"Views\EmailTemplates\" + emailName + ".cshtml"; var template = System.IO.File.ReadAllText(templatePath, System.Text.Encoding.Default); return Razor.Parse(template, model); }
protected void btnSubmit_Click(object sender, EventArgs e) { if (!Page.IsValid) return; int receiverID=(int)ViewState["receiverID"]; using (MooDB db = new MooDB()) { Mail mail=new Mail() { From = ((SiteUser)User.Identity).GetDBUser(db), To = (from u in db.Users where u.ID == receiverID select u).Single<User>(), Title = txtTitle.Text, Content = txtContent.Text, IsRead = false, }; db.Mails.AddObject(mail); db.SaveChanges(); Logger.Info(db,string.Format("向用户#{0}发送邮件#{1}",receiverID,mail.ID)); } PageUtil.Redirect("创建成功", "~/Mail/List.aspx"); }
public IActionResult Index(Mail Data) { if (ModelState.IsValid) { StringBuilder message = new StringBuilder(); MailAddress from = new MailAddress(Data.Email); message.Append("Name: " + Data.Name + "\n"); message.Append("Email: " + Data.Email + "\n"); message.Append("Subject: " + Data.Subject + "\n"); message.Append("Subject: \n" + Data.Message); MailMessage mail = new MailMessage(); SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.UseDefaultCredentials = false; smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "K33ls3n2188#"); smtp.EnableSsl = true; mail.From = from; mail.To.Add("*****@*****.**"); mail.Subject = "Keelsen Contact Form: " + Data.Subject + " (" + Data.Email + ")"; mail.Body = message.ToString(); smtp.Send(mail); Data.Done = true; } return View(Data); }
protected void SubmitBtn_Click(object sender, ImageClickEventArgs e) { Mail mailObj = new Mail(); mailObj.MailBody = CommentTB.Text; //Will by default have the from address as '*****@*****.**' mailObj.From = Session["UserLogin"].ToString(); mailObj.Subject = string.Format("{0}:{1}", Session["UserLogin"].ToString(), ReasonDDL.SelectedValue); mailObj.To = ConfigurationManager.AppSettings["AdminEmail"]; mailObj.SendMailMessage(); #region mailToAllAdmins //Send to all Admins .. // AccessDB dbObj = new AccessDB(); // dbObj.Open(); /*dbObj.Dataset.Reset(); dbObj.Query = string.Format(@"Select emailaddress from tbluserlogin where isadmin=true"); dbObj.ExecuteQuery(); for (int i = 0; i < dbObj.Dataset.Tables[0].Rows.Count; i++) { mailObj.To = dbObj.Dataset.Tables[0].Rows[i][0].ToString(); mailObj.SendMailMessage(); }*/ #endregion ConfMsgLbl.Visible = true; }
public async Task Handle(SendMail command, IAggregateRepository repository) { var mail = new Mail(); mail.RequestMail(command); await repository.Create(mail.RaiseNewEvents()); await mail.SendMail(this.mailService); await repository.Update(mail.RaiseNewEvents()); }
public static async Task SendEmail(string email, string subject, string content, EmailConfig config) { dynamic sg = new SendGridAPIClient(config.SendGridApiKey); Email from = new Email(config.EmailFrom); Email to = new Email(email); Mail mail = new Mail(from, subject, to, new Content("text/html", content)); dynamic response = await sg.client.mail.send.post(requestBody: mail.Get()); }
public object Create(object parent, object configContext, System.Xml.XmlNode section) { Mail mail = new Mail(); mail.StaffDomain = section.Attributes["staffDomain"] != null ? section.Attributes["staffDomain"].Value : mail.StaffDomain; return mail; }
public GlimpseMail(Mail Mail) { if (Mail != null) { this.ToEmail = Mail.ToEmail; this.ToName = Mail.ToName; this.Subject = Mail.Subject; this.Body = Mail.Body; } }
public void Test_New() { var from = new Node ("Node1"); var mail = new Mail (from, "Node2", "Hello World"); Assert.AreEqual (from, mail.From); Assert.AreEqual ("Node2", mail.Address); Assert.AreEqual ("Hello World", mail.Letter); }
protected void buttonSend_Click(object sender, EventArgs e) { try { this.sendMail = new Mail(HttpUtility.HtmlEncode(this.txtBoxMail.Text)); this.sendMail.SendEmailWithNewPassword(); this.txtBoxMail.Text = ""; } catch { } }
protected override void AddHeader(MailMessage message, Mail mail) { SendGridOptions options = _options(mail); options.Headers.ToList().ForEach(kvp => message.Headers.Add(kvp.Key, kvp.Value)); string smtpapi = options.Header.AsJson(); if (!string.IsNullOrEmpty(smtpapi)) message.Headers.Add("X-Smtpapi", smtpapi); }
public void DisableBcc() { var header = new Header(); var sendgrid = new Mail(header); sendgrid.DisableBcc(); String json = header.AsJson(); Assert.AreEqual("{\"filters\" : {\"bcc\" : {\"settings\" : {\"enable\" : \"0\"}}}}", json); }
public async Task Handle(RetryMail command, IAggregateRepository repository) { var mail = new Mail(); var load = await repository.Get(); mail.LoadFromHistory(load.List); mail.RetryMail(); await repository.Update(mail.RaiseNewEvents(), load.LastEventNumber); await mail.SendMail(this.mailService); await repository.Update(mail.RaiseNewEvents()); }
public void DisableBypassListManagement() { var header = new Header(); var sendgrid = new Mail(header); sendgrid.DisableBypassListManagement(); String json = header.JsonString(); Assert.AreEqual("{\"filters\" : {\"bypass_list_management\" : {\"settings\" : {\"enable\" : \"0\"}}}}", json); }
public void DisableClickTracking() { var header = new Header(); var sendgrid = new Mail(header); sendgrid.DisableClickTracking(); String json = header.JsonString(); Assert.AreEqual("{\"filters\" : {\"clicktrack\" : {\"settings\" : {\"enable\" : \"0\"}}}}", json); }
public override Mail Read(string name, int no) { var f = string.Format("{0}\\{1}.{2}", tmpDir, no, ext); if (File.Exists(f)) { var mail = new Mail(null); mail.Read(f); return mail; } return null; }
public void MailExecute() { Mail task = new Mail(); task.BuildEngine = new MockBuild(); task.SmtpServer = "localhost"; task.From = "*****@*****.**"; task.To = new string[] { "*****@*****.**" }; task.Subject = "This is a test of Mail Task"; task.Body = "This is a test email from the Mail Task"; Assert.IsTrue(task.Execute(), "Execute Failed"); }
public void Test_New() { var mail = new Mail (new Node ("From"), "Address", "Letter"); var rec = new DeliveryRecord (1, mail); Assert.AreEqual (1, rec.Time); Assert.AreEqual ("From", rec.From); Assert.AreEqual ("Address", rec.Address); Assert.AreEqual ("String", rec.LetterType); Assert.AreEqual ("Letter", rec.Letter); }
protected void btnTestMessage_Click(object sender, EventArgs e) { var mail = new Mail { Subject = "Test Message", Body = "Email Notifications Are Working!", MailTo = Settings.SmtpMailTo }; mail.Send(); EndUserMessage = "Test Message Sent"; }
public Task<string> SaveAsync(IMimeMessage message, CancellationToken cancellationToken) { Console.WriteLine(" "); Console.WriteLine(message.Mime); Mail mail = new Mail(); mail.From = message.From.User + "@" + message.From.Host; mail.To = message.To[0].User + "@" + message.To[0].Host; string str = message.Mime.ToString(); return Task.FromResult(String.Empty); }
public void SendEmail(EmailModel email) { dynamic sg = new SendGridAPIClient("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"); Email from = new Email("*****@*****.**","Brilliant Engineering Ltd"); String subject = email.Subject; Email to = new Email(email.EmailAddress); Content content = new Content("text/html", email.Body); Mail mail = new Mail(from, subject, to, content); dynamic response = sg.client.mail.send.post(requestBody: mail.Get()); }
protected void Page_Load(object sender, EventArgs e) { int mail_id; ISession session = (ISession)Context.Items["NHibernateSession"]; this.village = ((inPage)this.Master).CurrentVillage; int.TryParse(Request["mail"], out mail_id); Player user = session.Load<Player>(Session["user"]); Detail = user.GetMailDetail(mail_id, session); if (Detail == null) { Response.Redirect(string.Format("list_mail.aspx?id={0}", this.village), false); } }
protected void buttonSend_Click(object sender, EventArgs e) { try { this.sendMail = new Mail(HttpUtility.HtmlEncode(this.txtBoxMail.Text)+lblEmail.Text); this.sendMail.SendEmailWithNewPassword(); this.txtBoxMail.Text = ""; } catch { Response.Redirect(NEXT_PAGE_SESSION); } }
public Initialization2() { var tsDir = new TsDir(); //var tsOption = new TsOption(tsDir); //var manageDir = tsDir.Src + "\\TestDir"; //TmpDir2 = string.Format("{0}/../../TestDir", Directory.GetCurrentDirectory()); var optionDef = tsDir.Src + "\\Option.def"; //Docs Docs = new List<string>(); var lines = File.ReadAllLines(optionDef, Encoding.GetEncoding(932)); foreach (MlDocKind docKind in Enum.GetValues(typeof(MlDocKind))) { var tag = string.Format("MEMO=Ml\b{0}Document=", docKind.ToString().ToLower()); bool hit = false; foreach (var l in lines) { if (l.IndexOf(tag) == 0) { Docs.Add(l.Substring(tag.Length)); hit = true; break; } } if (!hit) { Docs.Add(""); } } Kernel = new Kernel(null, null, null, null); Logger = Kernel.CreateLogger("LOG", true, null); domainList = new List<string>() { "example.com" }; MlAddr = new MlAddr(mlName, domainList); var mailQueue = new MailQueue(tsDir.Src + "TestDir"); var oneOption = new Option(Kernel,"",""); var mailBox = new MailBox(Kernel, oneOption); MailSave = new MailSave(Kernel,mailBox,Logger,mailQueue,"",domainList); MlOption = CreateMlOption(); //MlUserList = CreateMlUsers(); Ml = new Ml(Kernel, Logger, MailSave, MlOption, mlName, domainList); //30件のメールを保存 for (int i = 0; i < 30; i++) { var mail = new Mail(null); mail.Init(Encoding.ASCII.GetBytes("\r\n"));//区切り行(ヘッダ終了) mail.AddHeader("subject", string.Format("[{0}:{1:D5}]TITLE", mlName, i + 1)); mail.Init(Encoding.ASCII.GetBytes("1\r\n"));//本文 mail.Init(Encoding.ASCII.GetBytes("2\r\n"));//本文 mail.Init(Encoding.ASCII.GetBytes("3\r\n"));//本文 Ml.Save(mail); } }
private void btnSend_Click(object sender, EventArgs e) { //input validation try { if ((txtTo.Text.Trim() != "") && (txtSubject.Text.Trim() != "") && (rtbBody.Text.Trim() != "")) { string subject = ""; string body = ""; //remove special char from body and subject text subject = RemoveSpecialCharacters(txtSubject.Text.Trim()); body = RemoveSpecialCharacters(rtbBody.Text.Trim()); MailMessage m = new MailMessage(txtFrom.Text, txtTo.Text, subject, body); if (txtCc.Text.Trim() != "") { string[] lstCC = txtCc.Text.Trim().Split(','); foreach (string c in lstCC) { MailAddress cc = new MailAddress(c); m.CC.Add(cc); } } m.IsBodyHtml = false; //Save to db Mail mail = new Mail(); mail.MailID = Convert.ToInt32(lblMailId.Text.Trim()); mail.From = txtFrom.Text.Trim(); mail.To = txtTo.Text.Trim(); mail.CC = txtCc.Text.Trim(); mail.BCC = ""; mail.Subject = subject; mail.Body = body; mail.IsSent = true; string saveMessage = DbAccess.SaveDraftEmail(mail); if (saveMessage == "Success") { //Send to SMTP server string message = Send(m); MessageBox.Show(message, "Email Client", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Email Saving Failed.", "Email Client", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { if (txtTo.Text.Trim() == "") { MessageBox.Show("To Email Address requird.", "Email Client", MessageBoxButtons.OK, MessageBoxIcon.Error); txtTo.Focus(); } else if (txtSubject.Text.Trim() == "") { MessageBox.Show("Email Subject requird.", "Email Client", MessageBoxButtons.OK, MessageBoxIcon.Error); txtSubject.Focus(); } else { MessageBox.Show("Email Body text requird.", "Email Client", MessageBoxButtons.OK, MessageBoxIcon.Error); rtbBody.Focus(); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Email Client", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public string SendMail(string MemberID, string exp, string nom, string obj, string msg, string device, string version) { DateTime dt = DateTime.Now; string comment = ""; string code = "ok"; string retour = "1"; try { int id = 0; Member member = null; Membre membre = null; string message = "Vous avez un message à partir de l'application mobile du district : www.rotary1730.org<br/>"; message += "Nom & Prenom : " + nom + "<br/>"; message += "Email : " + exp + "<br/>"; message += "Message : <br/>"; message += msg; PortalSettings ps = PortalController.GetCurrentPortalSettings(); if (!string.IsNullOrEmpty(MemberID)) { int.TryParse(MemberID, out id); if (id > 0) { member = DataMapping.GetMember(id); } } if (member != null) { membre = memberToMembre(member); Mail.SendEmail(exp, ps.Email, membre.email, obj, message); } else //Envoie au webmaster { Mail.SendEmail(exp, ps.Email, ps.Email, obj, message); } } catch (Exception ee) { code = "erreur"; comment = ee.ToString(); Functions.Error(ee); retour = "0"; } if (retour == "1") { comment = "Mail envoyé de " + exp + " à Member ID " + MemberID; } else { if (comment == "") { comment = "Mail NON envoyé de " + exp + " à Member ID " + MemberID; } } DataMapping.InsertLogWS(os, device, version, getIP(), dt, getDuree(dt), "SendMail", code, comment, ""); return(retour); }
} // IsLicenseKeyValid public override void Execute() { if (this.isLicenseKeyValid) { Mail mail = new Mail(); TimeZoneInfo dublinTimeZone = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time"); DateTime startTime = DateTime.UtcNow; DateTime dublinStartTime = TimeZoneInfo.ConvertTimeFromUtc(startTime, dublinTimeZone); //Irish pacnet office boundary hour to receive pacnet confirmation regarding money transfer const int boundaryHour = 15; const int boundaryMinutes = 20; DateTime irishOfficeBoundaryMoment = startTime.Date.AddHours(boundaryHour).AddMinutes(boundaryMinutes); for (;;) { DateTime now = DateTime.UtcNow; DateTime dublinNow = TimeZoneInfo.ConvertTimeFromUtc(now, dublinTimeZone); bool boundaryMomentHasPassed = dublinNow > irishOfficeBoundaryMoment; //checking either has an hour passed since request for confirmation or is it later than 15:20 GMT and it is necessary to notify the top-up if (now.Subtract(startTime).CompareTo(this.totalWaitingTime) > 0 || (dublinStartTime < irishOfficeBoundaryMoment && boundaryMomentHasPassed)) { Log.Info("Confirmation email did not arrive, not waiting for it any more. Alert Ezbob top-up"); var topup = new TopUpDelivery(this.underwriterId, this.amount, 2); topup.Execute(); break; } // if try { var imap = new Imap { // Enable SSL/TLS if necessary SslMode = MailBee.Security.SslStartupMode.OnConnect }; imap.Connect(this.server, this.port); Log.Info("Connected to the server"); imap.Login(this.loginAddress, this.loginPassword); Log.Info("Logged into the server"); imap.SelectFolder("Inbox"); if (FetchMaessages(imap)) { break; } imap.Disconnect(); } catch (PacnetMailProcessorException pex) { Log.Info("PacnetMailProcessorException: {0}", pex); } catch (MailBeeStreamException mex) { Log.Info("MailBeeStreamException: {0}", mex); } catch (Exception e) { Log.Info("Some generic Exception: {0}", e); } // try Log.Info("Sleeping..."); Thread.Sleep(this.mailboxReconnectionIntervalSeconds * 1000); } // for } }
public void SendMail(Mail mail) => _client.ServiceProxy.SendMail(mail);
public ActionResult SendMail(FormCollection form) { var model = Session[CommonConstants.USER_SESSION]; var temp = new USER_INFORMATION(); var merchant = new MERCHANT(); if (model != null) { temp = (USER_INFORMATION)model; HttpClient client = new AccessAPI().Access(); HttpResponseMessage response = client.GetAsync(string.Format("api/MERCHANT/FindMerchant?merchantCode={0}", temp.UserName)).Result; if (response.IsSuccessStatusCode) { merchant = response.Content.ReadAsAsync <MERCHANT>().Result; } } else { return(View("Index")); } var fbMail = new Mail(); fbMail.Subject = form["Subject"]; fbMail.Content = form["Content"]; var Signature = "\n\n-------------\n" + merchant.MerchantName + "\n" + merchant.Owner + "\n" + merchant.Address1 + "\n" + merchant.Email + "\n" + merchant.Phone; fbMail.MailMaster = WebConfigurationManager.AppSettings["toAddress"]; fbMail.MailMerchant = WebConfigurationManager.AppSettings["fromAddress"]; fbMail.Password = WebConfigurationManager.AppSettings["Password"]; var fromAddress = new MailAddress(fbMail.MailMerchant); var toAddress = new MailAddress(fbMail.MailMaster); var smtp = new SmtpClient { Host = WebConfigurationManager.AppSettings["host"], Port = int.Parse(WebConfigurationManager.AppSettings["port"]), EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = true, Credentials = new NetworkCredential(fromAddress.Address, fbMail.Password) }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = fbMail.Subject, Body = fbMail.Content + Signature }) { try { smtp.Send(message); TempData["Message"] = "true"; return(RedirectToAction("Index")); } catch (Exception) { TempData["Message"] = "false"; return(RedirectToAction("Index")); } } }
private void syncPriceLevels_Click(object sender, EventArgs e) { var notificationEmail = Settings.GetNotificationEmail(); var priceLevels = new PriceLevels(); priceLevels.UpdateTemporaryTables(); priceLevels.Empty(); string mappedDsnName = Mapping.GetDsnName("PriceLevels"); var newMapping = new Mapping(mappedDsnName); if (newMapping.MigrateData("PriceLevels")) { if (priceLevels.Publish(out var publishDetails)) { MessageBox.Show(@"Your price levels have been published", @"Published Successfully"); Logger.Instance.Info("Price Levels synced."); if (!string.IsNullOrWhiteSpace(notificationEmail)) { Mail.SendProcessCompleteEmail(notificationEmail, publishDetails, "PriceLevel Publish", response => Logger.Instance.Info(response)); } } else { MessageBox.Show(@"Unable to publish your Price Levels", @"Publish Failed"); Logger.Instance.Error("Price Levels failed to sync."); if (!string.IsNullOrWhiteSpace(notificationEmail)) { Mail.SendProcessCompleteEmail(notificationEmail, "PriceLevel Publish failed, please check logs or contact support", "Price Level Publish", response => Logger.Instance.Info(response)); } } } else { if (!newMapping._validFields) { MessageBox.Show(@"Mapping failed, please validate your table mapping", @"Publish Failed"); if (!string.IsNullOrWhiteSpace(notificationEmail)) { Mail.SendProcessCompleteEmail(notificationEmail, "Price Level Publish failed, please check your table mapping.", "Price Level Publish", response => Logger.Instance.Info(response)); } } else { MessageBox.Show(@"An unexpected error has occured, please check your logs or contact support", @"Publish Failed"); Logger.Instance.Error("Price Levels failed to migrate."); if (!string.IsNullOrWhiteSpace(notificationEmail)) { Mail.SendProcessCompleteEmail(notificationEmail, "Price Level Publish failed, please check logs or contact support", "Price Level Publish", response => Logger.Instance.Info(response)); } } } }
private void syncProducts_Click(object sender, EventArgs e) { var bw = new BackgroundWorker(); lblStatus.Text = "Processing product sync (Preparing)\n\rPlease wait"; SetButtonState(false); bw.DoWork += (bwSender, bwEventArgs) => { var notificationEmail = Settings.GetNotificationEmail(); var products = new Products(); products.UpdateTemporaryTables(); products.Empty(); string mappedDsnName = Mapping.GetDsnName("Products"); var newMapping = new Mapping(mappedDsnName); if (newMapping.MigrateData("Products")) { if (products.Publish(out var publishDetails, bw)) { bwEventArgs.Result = new { Message = "Your products have been pushed", Title = "Published Successfully", Error = string.Empty, InfoMessage = string.Empty }; if (!string.IsNullOrWhiteSpace(notificationEmail)) { Mail.SendProcessCompleteEmail(notificationEmail, publishDetails, "Product Publish", response => Logger.Instance.Info(response)); } } else { bwEventArgs.Result = new { Message = "Please select your product table!", Title = "Publish Failed", Error = "Products failed to sync.", InfoMessage = string.Empty }; if (!string.IsNullOrWhiteSpace(notificationEmail)) { Mail.SendProcessCompleteEmail(notificationEmail, "Product Publish failed, please check logs or contact support", "Product Publish", response => Logger.Instance.Info(response)); } } } else { if (!newMapping._validFields) { bwEventArgs.Result = new { Message = "Invalid mapping fields, please validate your mapping.", Title = "Publish Failed", Error = string.Empty, InfoMessage = string.Empty }; if (!string.IsNullOrWhiteSpace(notificationEmail)) { Mail.SendProcessCompleteEmail(notificationEmail, "Product Publish failed, please validate your field mappings.", "Product Publish", response => Logger.Instance.Info(response)); } } else { bwEventArgs.Result = new { Message = "Please select your products table", Title = "Publish Failed", Error = "Products failed to migrate.", InfoMessage = string.Empty }; if (!string.IsNullOrWhiteSpace(notificationEmail)) { Mail.SendProcessCompleteEmail(notificationEmail, "Product Publish failed, please check logs or contact support", "Product Publish", response => Logger.Instance.Info(response)); } } } }; bw.ProgressChanged += Status_BackgroundWorker_ProgressChanged; bw.RunWorkerCompleted += Status_BackgroundWorker_Completed; bw.WorkerReportsProgress = true; bw.RunWorkerAsync(); }
private void syncCustomers_Click(object sender, EventArgs e) { var bw = new BackgroundWorker(); lblStatus.Text = "Processing customer sync (Preparing)\n\rPlease wait"; SetButtonState(false); bw.DoWork += (bwSender, bwEventArgs) => { var notificationEmail = Settings.GetNotificationEmail(); var customers = new Customers(); customers.UpdateTemporaryTables(); customers.Empty(); string mappedDsnName = Mapping.GetDsnName("Customers"); var newMapping = new Mapping(mappedDsnName); if (newMapping.MigrateData("Customers")) { ((BackgroundWorker)bwSender).ReportProgress(0, "Processing customer sync (Pushing)\n\rPlease wait"); if (customers.Publish(out List <string> publishDetails, (BackgroundWorker)bwSender)) { bwEventArgs.Result = new { Message = "Customers Synced", Title = "Success", Error = string.Empty, InfoMessage = string.Empty }; if (!string.IsNullOrWhiteSpace(notificationEmail)) { Mail.SendProcessCompleteEmail(notificationEmail, publishDetails, "Customers Publish", response => Logger.Instance.Info(response)); } } else { bwEventArgs.Result = new { Message = "Customers failed to sync. Do you have your API Key set?", Title = "Sync Failure", Error = "Customers failed to sync.", InfoMessage = string.Empty }; if (!string.IsNullOrWhiteSpace(notificationEmail)) { Mail.SendProcessCompleteEmail(notificationEmail, "Customers Publish failed, please check logs or contact support", $"Customers Publish", response => Logger.Instance.Info(response)); } } } else { if (!newMapping._validFields) { bwEventArgs.Result = new { Message = "All required fields indicated with a * must be mapped.", Title = "Map Required Fields", Error = string.Empty, InfoMessage = string.Empty }; } else { bwEventArgs.Result = new { Message = "Customers failed to migrate.", Title = "Unknown Error", Error = "Customers failed to migrate.", InfoMessage = string.Empty }; } } }; bw.ProgressChanged += Status_BackgroundWorker_ProgressChanged; bw.RunWorkerCompleted += Status_BackgroundWorker_Completed; bw.WorkerReportsProgress = true; bw.RunWorkerAsync(); }
private void btnSearch_Click(object sender, EventArgs e) { try { DataTable listaTickets = null; Cursor.Current = Cursors.WaitCursor; dgvSales.Columns.Clear(); dgvSales.DataSource = null; int aux = 0; int.TryParse(tbIdTicket.Text, out aux); if (aux > 0) { listaTickets = Global.common.getTicketByIdSQL(aux); } else { listaTickets = Global.common.getAllTicketsSQL(); } if ((listaTickets != null) && (listaTickets.Rows.Count > 0)) { dgvSales.DataSource = listaTickets; //Ocultamos columnas dgvSales.Columns[1].Visible = false; dgvSales.Columns[4].Visible = false; dgvSales.Columns[5].Visible = false; dgvSales.Columns[7].Visible = false; dgvSales.DefaultCellStyle.ForeColor = Color.Black; DataGridViewButtonColumn colEdit = new DataGridViewButtonColumn(); colEdit.HeaderText = "Ver detalle"; colEdit.Text = "VER DETALLE"; colEdit.UseColumnTextForButtonValue = true; colEdit.Width = 200; DataGridViewButtonColumn colDel = new DataGridViewButtonColumn(); colDel.HeaderText = "Anular ticket"; colDel.Text = "ANULAR TICKET"; colDel.UseColumnTextForButtonValue = true; colDel.Width = 170; dgvSales.EnableHeadersVisualStyles = false; dgvSales.Columns.Add(colEdit); dgvSales.Columns.Add(colDel); } else { MessageBox.Show("No hay datos", "Charlotte", MessageBoxButtons.OK, MessageBoxIcon.Information); } Cursor.Current = Cursors.Default; } catch (Exception ex) { Mail.gestionaError(ex.Message); Global.error = true; MessageBox.Show("ERROR", "Charlotte", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void Deserialize(NetDataReader reader) { Error = (UITextKeys)reader.GetByte(); Mail = reader.GetValue <Mail>(); }
private static async Task Execute(Mail pEmail) { string apiKey = ConfigurationManager.AppSettings["SendGridApiKey"]; dynamic sg = new SendGridAPIClient(apiKey); dynamic response = await sg.client.mail.send.post(requestBody : pEmail.Get()); }
public static string ImportPrisonersMails(SoftJailDbContext context, string jsonString) { StringBuilder sb = new StringBuilder(); ImportPrisonerMailsDto[] importPrisonerMailsDtos = JsonConvert.DeserializeObject <ImportPrisonerMailsDto[]>(jsonString); foreach (var prisonerMailsDto in importPrisonerMailsDtos) { if (!IsValid(prisonerMailsDto)) { sb.AppendLine(ErrorMessage); continue; } bool isIncarcerationDateValid = DateTime.TryParseExact(prisonerMailsDto.IncarcerationDate, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime incarcerationDate); if (!isIncarcerationDateValid) { sb.AppendLine(ErrorMessage); continue; } bool isReleaseDateValid = DateTime.TryParseExact(prisonerMailsDto.ReleaseDate, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime releaseDate); if (!isReleaseDateValid && prisonerMailsDto.ReleaseDate != null) { sb.AppendLine(ErrorMessage); continue; } bool areMailsValid = true; ICollection <Mail> mails = new List <Mail>(); foreach (var mailDto in prisonerMailsDto.Mails) { if (!IsValid(mailDto)) { areMailsValid = false; break; } Mail mail = new Mail() { Description = mailDto.Description, Sender = mailDto.Sender, Address = mailDto.Address }; mails.Add(mail); } if (!areMailsValid) { sb.AppendLine(ErrorMessage); continue; } Prisoner prisoner = new Prisoner() { FullName = prisonerMailsDto.FullName, Nickname = prisonerMailsDto.Nickname, Age = prisonerMailsDto.Age, IncarcerationDate = incarcerationDate, ReleaseDate = releaseDate, Bail = prisonerMailsDto.Bail, CellId = prisonerMailsDto.CellId, Mails = mails }; sb.AppendLine($"Imported {prisoner.FullName} {prisoner.Age} years old"); context.Prisoners.Add(prisoner); } context.SaveChanges(); return(sb.ToString().TrimEnd()); }
/// <summary> /// Creates a new instance of the <see cref="EmailNotifier"/>. /// </summary> public EmailNotifier() { m_mailClient = new Mail(); }
private void syncPricing_Click(object sender, EventArgs e) { var bw = new BackgroundWorker(); bw.DoWork += (bwSender, bwEventArgs) => { var notificationEmail = Settings.GetNotificationEmail(); var priceLevelPrices = new PriceLevelPrices(); priceLevelPrices.UpdateTemporaryTables(); priceLevelPrices.Empty(); bw.ReportProgress(0, "Populating Local Repository\r\nPlease Wait"); string mappedDsnName = Mapping.GetDsnName("PriceLevelPrices"); var newMapping = new Mapping(mappedDsnName); if (newMapping.MigrateData("PriceLevelPrices")) { bw.ReportProgress(0, "Preparing to publish to LinkGreen\r\nPlease Wait"); if (priceLevelPrices.Publish(out var publishDetails, bw)) { bwEventArgs.Result = new { Message = "Prices have been published successfully", Title = "Published Successfully", Error = "", InfoMessage = string.Empty }; Logger.Instance.Info("Pricing synced."); if (!string.IsNullOrWhiteSpace(notificationEmail)) { Mail.SendProcessCompleteEmail(notificationEmail, publishDetails, "Pricing Publish", response => Logger.Instance.Info(response)); } } else { bwEventArgs.Result = new { Message = "Unable to publish your prices", Title = "Publish Failed", Error = "Unable to publish your prices", InfoMessage = string.Empty }; Logger.Instance.Error("Pricing failed to sync."); if (!string.IsNullOrWhiteSpace(notificationEmail)) { Mail.SendProcessCompleteEmail(notificationEmail, "Pricing Publish failed, please check logs or contact support", "Pricing Publish", response => Logger.Instance.Info(response)); } } } else { if (!newMapping._validFields) { bwEventArgs.Result = new { Message = "Mapping failed, please validate your field mapping", Title = "Publish Failed", Error = "Mapping failed, please validate your field mapping", InfoMessage = string.Empty }; if (!string.IsNullOrWhiteSpace(notificationEmail)) { Mail.SendProcessCompleteEmail(notificationEmail, "Pricing Publish failed, please validate your field mapping.", "Pricing Publish", response => Logger.Instance.Info(response)); } } else { bwEventArgs.Result = new { Message = "An unexepcted error has occurred, please check your logs or contct support", Title = "Publish Failed", Error = "An unexepcted error has occurred, please check your logs or contct support", InfoMessage = string.Empty }; Logger.Instance.Error("Pricing failed to migrate."); if (!string.IsNullOrWhiteSpace(notificationEmail)) { Mail.SendProcessCompleteEmail(notificationEmail, "Product Publish failed, please check logs or contact support", "Pricing Publish", response => Logger.Instance.Info(response)); } } } }; bw.ProgressChanged += Status_BackgroundWorker_ProgressChanged; bw.RunWorkerCompleted += Status_BackgroundWorker_Completed; bw.WorkerReportsProgress = true; bw.RunWorkerAsync(); }
public void Seed() { var prestacion = new Prestacion { Nombre = "Odontologia General", Monto = 500, DuracionHoras = 1 }; var prestacion2 = new Prestacion { Nombre = "Ortodoncia", Monto = 1000, DuracionHoras = 2 }; var disponibilidad = new Disponibilidad(9, 23, DiasEnum.Sabado); var direCentro = new Direccion { Calle = "La famosa", Altura = 321, Localidad = "Escobar", Provincia = "BUENOS AIRES" }; var centro1 = new Centro { Direccion = direCentro, Nombre = "The best centro", }; var direPaciente1 = new Direccion { Calle = "Aristobulo del valle2", Altura = 285, Localidad = "CABA", Provincia = "BUENOS AIRES" }; var direPaciente2 = new Direccion { Calle = "Calle falsa", Altura = 123, Localidad = "CABA", Provincia = "BUENOS AIRES" }; var direProf = new Direccion { Calle = "Calle falsedad", Altura = 13323, Localidad = "CABA", Provincia = "BUENOS AIRES" }; var direAdmin = new Direccion { Calle = "Calle delAdmin", Altura = 1323, Localidad = "CABA", Provincia = "BUENOS AIRES" }; var tel1 = new Telefono { NumeroCelular = "111122222", TelefonoAlternativo = "456456456" }; var tel2 = new Telefono { NumeroCelular = "1111222223", TelefonoAlternativo = "4564564563" }; var tel3 = new Telefono { NumeroCelular = "1113332223", TelefonoAlternativo = "45634564563" }; var tel4 = new Telefono { NumeroCelular = "1111222223", TelefonoAlternativo = "4564564563" }; var mail1 = new Mail { Descripcion = "*****@*****.**" }; var mail2 = new Mail { Descripcion = "*****@*****.**" }; var mail3 = new Mail { Descripcion = "*****@*****.**" }; var mail4 = new Mail { Descripcion = "*****@*****.**" }; var profesional = new Profesional { Nombre = "Roberto", Apellido = "Garcia", Centro = centro1, Dni = "123123123", Prestacion = prestacion2, Rol = RolesEnum.PROFESIONAL, Mails = new List <Mail>(), Turnos = new List <Turno>(), Telefonos = new List <Telefono>(), Direcciones = new List <Direccion>(), Disponibilidades = new List <Disponibilidad>(), Username = "******", Password = "******".Encriptar() }; var profesional2 = new Profesional { Nombre = "Checho", Apellido = "Palavecino", Centro = centro1, Dni = "999999999", Prestacion = prestacion, Rol = RolesEnum.PROFESIONAL, Mails = new List <Mail>(), Turnos = new List <Turno>(), Telefonos = new List <Telefono>(), Direcciones = new List <Direccion>(), Disponibilidades = new List <Disponibilidad>(), Username = "******", Password = "******".Encriptar() }; var administrador = new Administrador { Nombre = "Cristofer", Apellido = "Wallace", Dni = "00000000001", Rol = RolesEnum.ADMINISTRADOR, Mails = new List <Mail>(), Telefonos = new List <Telefono>(), Direcciones = new List <Direccion>(), Username = "******", Password = "******".Encriptar() }; var paciente = new Paciente { Nombre = "Pepe", Apellido = "Paciente", Dni = "123123123", Rol = RolesEnum.CLIENTE, Direcciones = new List <Direccion>(), Mails = new List <Mail>(), Telefonos = new List <Telefono>(), Turnos = new List <Turno>(), Username = "******", Password = "******".Encriptar() }; var paciente2 = new Paciente { Nombre = "Pepe2", Apellido = "Paciente2", Dni = "123123123", Rol = RolesEnum.CLIENTE, Direcciones = new List <Direccion>(), Mails = new List <Mail>(), Telefonos = new List <Telefono>(), Turnos = new List <Turno>(), Username = "******", Password = "******".Encriptar() }; administrador.Mails.Add(mail4); administrador.Telefonos.Add(tel4); administrador.Direcciones.Add(direAdmin); profesional.Mails.Add(mail1); profesional.Telefonos.Add(tel1); profesional.Direcciones.Add(direProf); profesional.Disponibilidades.Add(disponibilidad); paciente.Telefonos.Add(tel2); paciente.Mails.Add(mail2); paciente2.Mails.Add(mail3); paciente.Direcciones.Add(direPaciente1); paciente2.Telefonos.Add(tel3); paciente2.Direcciones.Add(direPaciente2); _context.Pacientes.Add(paciente); _context.Pacientes.Add(paciente2); _context.Profesionales.Add(profesional); _context.Profesionales.Add(profesional2); _context.Administradores.Add(administrador); _context.SaveChanges(); /* if (!_context.Prestaciones.Any()) * { * * _context.Add(prestacion); * _context.SaveChanges(); * * } */ }
private void downloadOrders_Click(object sender, EventArgs e) { var syncCustomerResponse = MessageBox.Show(this, "Would you like to do a Customer sync before downloading the Orders?", "Customer Sync?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (syncCustomerResponse == DialogResult.Cancel) { return; } var skipCustomers = syncCustomerResponse == DialogResult.No; var bw = new BackgroundWorker(); lblStatus.Text = "Processing customer sync (Preparing)\n\rPlease wait"; var notificationEmail = Settings.GetNotificationEmail(); SetButtonState(false); bw.DoWork += (bwSender, bwEventArgs) => { var customers = new Customers(); if (!skipCustomers) { customers.UpdateTemporaryTables(); customers.Empty(); } string mappedDsnName = Mapping.GetDsnName("Customers"); var newMapping = new Mapping(mappedDsnName); if (skipCustomers || newMapping.MigrateData("Customers")) { if (!skipCustomers) { ((BackgroundWorker)bwSender).ReportProgress(0, "Processing customer sync (Pushing)\n\rPlease wait"); } var publishDetails = new List <string>(); if (skipCustomers || customers.Publish(out publishDetails, (BackgroundWorker)bwSender)) { if (!skipCustomers && !string.IsNullOrWhiteSpace(notificationEmail)) { Mail.SendProcessCompleteEmail(notificationEmail, publishDetails, "Customers Publish", response => Logger.Instance.Info(response)); } bwEventArgs.Result = new DownloadOrderRunner().Run((BackgroundWorker)bwSender); } else { bwEventArgs.Result = new { Message = "Customers failed to sync. Do you have your API Key set?", Title = "Sync Failure", Error = "Customers failed to sync.", InfoMessage = string.Empty }; if (!string.IsNullOrWhiteSpace(notificationEmail)) { Mail.SendProcessCompleteEmail(notificationEmail, "Customers Publish failed, please check logs or contact support", $"Customers Publish", response => Logger.Instance.Info(response)); } } } else { if (!newMapping._validFields) { bwEventArgs.Result = new { Message = "All required fields indicated with a * must be mapped.", Title = "Map Required Fields", Error = string.Empty, InfoMessage = string.Empty }; } else { bwEventArgs.Result = new { Message = "Customers failed to migrate.", Title = "Unknown Error", Error = "Customers failed to migrate.", InfoMessage = string.Empty }; } } }; bw.ProgressChanged += Status_BackgroundWorker_ProgressChanged; bw.RunWorkerCompleted += Status_BackgroundWorker_Completed; bw.WorkerReportsProgress = true; bw.RunWorkerAsync(); }
public static string ImportPrisonersMails(SoftJailDbContext context, string jsonString) { var prisonersDTOs = JsonConvert.DeserializeObject <IEnumerable <ImportPrisonerDTO> >(jsonString); var sb = new StringBuilder(); var prisoners = new List <Prisoner>(); foreach (var prisonerDTO in prisonersDTOs) { if (!IsValid(prisonerDTO)) { sb.AppendLine(errorMessage); continue; } var mails = new List <Mail>(); var isNotValidMail = false; foreach (var currentMail in prisonerDTO.Mails) { if (!IsValid(currentMail)) { sb.AppendLine(errorMessage); isNotValidMail = true; break; } var mail = new Mail { Description = currentMail.Description, Sender = currentMail.Sender, Address = currentMail.Address, }; mails.Add(mail); } if (isNotValidMail) { continue; } var prisoner = new Prisoner() { FullName = prisonerDTO.FullName, Nickname = prisonerDTO.Nickname, Age = prisonerDTO.Age, IncarcerationDate = DateTime.ParseExact(prisonerDTO.IncarcerationDate, "dd/MM/yyyy", CultureInfo.InvariantCulture), ReleaseDate = DateTime.ParseExact(prisonerDTO.IncarcerationDate, "dd/MM/yyyy", CultureInfo.InvariantCulture), Bail = prisonerDTO.Bail, CellId = prisonerDTO.CellId, Mails = mails, }; prisoners.Add(prisoner); sb.AppendLine(string.Format(successMessagePrisoners, prisoner.FullName, prisoner.Age)); } context.Prisoners.AddRange(prisoners); context.SaveChanges(); return(sb.ToString().Trim()); }
/// <Sql> /// SELECT /// * /// FROM /// list_maildata /// WHERE /// Receiptent=?Receiptent /// AND /// IsInbox=1; /// </Sql> public IEnumerable <Mail> GetInboxMail(MySqlConnection connection, Character target) { MySqlCommand command = new MySqlCommand(_query_35, connection); MySqlCommand command2 = new MySqlCommand(_query_36, connection); command.Parameters.AddWithValue("Receiptent", target.Name); command2.Parameters.AddWithValue("Receiptent", target.Name); MySqlDataReader reader = null; List <Mail> list = new List <Mail>(); try { command2.ExecuteNonQuery(); reader = command.ExecuteReader(); while (reader.Read()) { Mail mailsubject = new Mail(); mailsubject.MailId = reader.GetUInt32(0); mailsubject.MailId = reader.GetUInt32(0); mailsubject.Sender = reader.GetString(2); mailsubject.Time = reader.GetDateTime(3); mailsubject.IsRead = reader.GetByte(4); mailsubject.Topic = reader.GetString(6); mailsubject.Message = reader.GetString(7); mailsubject.Zeny = (int)reader.GetUInt32(9); if (reader.IsDBNull(8) == false) { byte[] buffer = new byte[67]; reader.GetBytes(8, 0, buffer, 0, 67); Rag2Item.Deserialize(out mailsubject.Attachment, buffer, 0); } if (mailsubject.IsRead == 0) { mailsubject.Valid = (byte)(30 - Math.Min(30, (int)((DateTime.Now - mailsubject.Time).TotalDays))); } else { DateTime dateread = reader.GetDateTime(10); mailsubject.Valid = (byte)(7 - Math.Min(7, (int)((DateTime.Now - dateread).TotalDays))); } list.Add(mailsubject); } return(list); } catch (Exception e) { __dbtracelog.WriteError("Database", e.Message); return(list); } finally { if (reader != null) { reader.Close(); } } }
protected void OnSendClick(object sender, EventArgs e) { Page.Validate(); if (!string.IsNullOrEmpty(Request.Form["codeBox"])) { PnlStatus.Visible = true; LitStatus.Text = GuiLanguage.GetGuiLanguage("Pages.Popups.WebUI.Base").GetString("MessageInvisibleTextBoxCaptcha"); } else if (Page.IsValid) { try { bool isAttachmentValid = true; List <Attachment> attachments = null; if (FuAttachment.HasFile) { if (FuAttachment.PostedFile.ContentLength <= 5242880) { if (FuAttachment.PostedFile.ContentType.StartsWith("image")) { attachments = new List <Attachment>() { new Attachment(FuAttachment.FileContent, FuAttachment.FileName) }; } else { isAttachmentValid = false; PnlStatus.Visible = true; LitStatus.Text = (new TextControl() { LanguageFile = "Popups.WebUI", TextKey = "ErrorEmailAttachmentInvalidContent" }).Text; } } else { isAttachmentValid = false; PnlStatus.Visible = true; LitStatus.Text = (new TextControl() { LanguageFile = "Popups.WebUI", TextKey = "ErrorEmailAttachmentToLarge" }).Text; } } if (isAttachmentValid) { Mail.SendMail(null, ConfigurationManager.AppSettings["FeedbackMail"].Split(',').ToList().ConvertAll(x => new MailAddress(x)), new List <MailAddress>(), new List <MailAddress>(), new MailAddress(TxtEmail.Text, TxtName.Text), _4screen.CSB.Common.SiteConfig.SiteName + " " + GuiLanguage.GetGuiLanguage("Pages.Popups.WebUI.Base").GetString("EmailFeedbackSubject"), TxtFeedback.Text, false, attachments); ClientScript.RegisterStartupScript(GetType(), "CloseWindow", "RefreshParentPage();CloseWindow();", true); } } catch { PnlStatus.Visible = true; LitStatus.Text = (new TextControl() { LanguageFile = "Pages.Popups.WebUI.Base", TextKey = "ErrorEmailFeedback" }).Text; } } }
private async void Build_Load(object sender, EventArgs e) { // Gmail IMAP4 server is "imap.gmail.com" // Get these values from App.config MailServer oServer = new MailServer("imap.gmail.com", "@gmail.com", "", ServerProtocol.Imap4); MailClient oClient = new MailClient("TryIt"); // Set SSL connection, oServer.SSLConnection = true; // Set 993 IMAP4 port oServer.Port = 993; try { oClient.Connect(oServer); MailInfo[] infos = oClient.GetMailInfos(); for (int i = 0; i < infos.Length; i++) { MailInfo info = infos[i]; Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}", info.Index, info.Size, info.UIDL); // Download email from GMail IMAP4 server Mail oMail = oClient.GetMail(info); //1st layer to isolate the spam if (oMail.From == new MailAddress("*****@*****.**")) { // check } // 2nd layer - this is an additional layer of security to isolate the spam or wrong emails. // Checking if the configured secret in github maps string password = ((EAGetMail.HeaderItem)(oMail.Headers[oMail.Headers.SearchKey("Approved")])).HeaderValue; Console.WriteLine("From: {0}", oMail.From.ToString()); Console.WriteLine("Subject: {0}\r\n", oMail.Subject); // Get the repo name from the emailbody string[] lines = oMail.HtmlBody.Split( new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); string homePath = lines.FirstOrDefault(t => t.Contains("Home")); string repoName = homePath.Substring(homePath.LastIndexOf('/')); // Passing the reponame retrived from Htmlbody as a parameter to invoke the build. // Crucial to have the same name await postRequest(repoName.Trim()); //TODO: // if success -> Mark the email as read or delete. // if failure to invoke the build -> notify with the exception message. } // Quit and purge emails marked as deleted from Gmail IMAP4 server. oClient.Quit(); } catch (Exception ep) { Console.WriteLine(ep.Message); } }
public void ActionSendMailExcute(EmailEntity emailEntity) { ViewBag.Data = emailEntity; CPViewPage.Message.MessageType = Message.MessageTypeEnum.Error; if (string.IsNullOrEmpty(emailEntity.To)) { CPViewPage.Message.ListMessage.Add("Bạn chưa nhập Email tiếp nhận."); } else { var toArr = emailEntity.To.Split(','); foreach (var i in toArr) { if (Utils.GetEmailAddress(i) == string.Empty) { CPViewPage.Message.ListMessage.Add("Định dạng Email tiếp nhận không đúng."); } } } if (!string.IsNullOrEmpty(emailEntity.Cc)) { var ccArr = emailEntity.Cc.Split(','); foreach (var i in ccArr) { if (Utils.GetEmailAddress(i) == string.Empty) { CPViewPage.Message.ListMessage.Add("Định dạng Email Cc không đúng."); } } } if (string.IsNullOrEmpty(emailEntity.Subject)) { CPViewPage.Message.ListMessage.Add("Bạn chưa nhập Tiêu đề."); } if (string.IsNullOrEmpty(emailEntity.Body)) { CPViewPage.Message.ListMessage.Add("Bạn chưa nhập Nội dung."); } if (CPViewPage.Message.ListMessage.Count == 0) { // Goi ham send mail string sendResult = Mail.SendMailUseSMTP(emailEntity.To, emailEntity.Cc, emailEntity.Subject, emailEntity.Body, emailEntity.Attach); if (!string.IsNullOrEmpty(sendResult)) { CPViewPage.Message.ListMessage.Add("Gửi mail lỗi. Hãy kiểm tra lại việc cấu hình email của bạn."); } else { CPViewPage.SetMessage("Gửi mail thành công."); // Thuc hien tang so lan gui mail them 1 var incident = ModIncidentService.Instance.CreateQuery().Where(o => o.ID == emailEntity.RecordID).ToSingle(); incident.EmailNo++; ModIncidentService.Instance.Save(incident); } } }
public void Create(Mail mail) { this.context.Mail.Add(mail); this.context.SaveChanges(); }
public IActionResult SendMail(Mail MailDetails) { try { using (MailMessage EMail = new MailMessage()) { MailAddress fromAddress = new MailAddress(MailDetails.Sender, "From LTI"); List <System.Net.Mail.Attachment> mailattachment = new List <System.Net.Mail.Attachment>(); EMail.From = fromAddress; if (!string.IsNullOrEmpty(MailDetails.To)) { foreach (string email in MailDetails.To.Split(',')) { if (!string.IsNullOrEmpty(email)) { try { EMail.To.Add(email); } catch { } } } } if (EMail.To.Count == 0) { throw new Exception("To address is not present in the mail"); } if (!string.IsNullOrEmpty(MailDetails.CC)) { foreach (string email in MailDetails.CC.Split(',')) { if (!string.IsNullOrEmpty(email)) { try { EMail.CC.Add(email); } catch { } } } } if (!string.IsNullOrEmpty(MailDetails.BCC)) { foreach (string email in MailDetails.BCC.Split(',')) { if (!string.IsNullOrEmpty(email)) { try { EMail.Bcc.Add(email); } catch { } } } } if (MailDetails.Attachments != null && MailDetails.Attachments.Any()) { foreach (var attachment in MailDetails.Attachments) { var contentType = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf); var emailAttachment = new System.Net.Mail.Attachment(attachment.Value, contentType); emailAttachment.ContentDisposition.FileName = attachment.Key; EMail.Attachments.Add(emailAttachment); } } EMail.IsBodyHtml = true; EMail.Body = MailDetails.Body; EMail.Subject = MailDetails.Subject; using (SmtpClient smtpClient = new SmtpClient()) { smtpClient.Host = "smtp.office365.com"; smtpClient.EnableSsl = true; smtpClient.Port = 587; smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.UseDefaultCredentials = true; smtpClient.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Lnt@0987654"); smtpClient.Timeout = 6000000; smtpClient.Send(EMail); } MailDetails.Status = "Success"; // return Content(HttpStatusCode.OK, true); return(Ok()); } } catch (Exception ex) { MailDetails.Status = "Fail"; return(BadRequest(ex.Message.ToString())); } }
public void Delete(Mail mail) { this.context.Mail.Remove(mail); this.context.SaveChanges(); }
//[ValidateAntiForgeryToken] public async Task <ActionResult> Create(usuarios usuario, HttpPostedFileBase file) { if (ModelState.IsValid) { DateTime today = CurrentDate.getNow(); usuario.created_at = today; usuario.updated_at = today; usuario.activo = true; if (file != null) { byte[] bNonNull = new byte[file.ContentLength]; Image img = Image.FromStream(file.InputStream, true, true); ImageCodecInfo pngInfo = ImageCodecInfo.GetImageEncoders().Where(codecInfo => codecInfo.MimeType == "image/png").First(); using (Stream s = new MemoryStream()) { using (EncoderParameters encParams = new EncoderParameters(1)) { encParams.Param[0] = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionLZW); //quality should be in the range [0..100] img.Save(s, pngInfo, encParams); } s.Position = 0; s.Read(bNonNull, 0, (int)s.Length); } usuario.foto = Convert.ToBase64String(bNonNull); } usuario.deleted_at = null; db.usuarios.Add(usuario); int i = await db.SaveChangesAsync(); if (i > 0) { usuarios createdUser = db.usuarios.Where(u => u.codigo == usuario.codigo).FirstOrDefault(); usuario_permisos usrAccesses = new usuario_permisos(); usrAccesses.usuario_id = createdUser.id; usrAccesses.created_at = today; usrAccesses.updated_at = today; switch (createdUser.tipo) { case UserProfiles.Default: goto default; case UserProfiles.Nutricionista: usrAccesses.permiso_id = db.permisos.Where(p => p.codigo_interno == "nut_home").Select(p => p.id).FirstOrDefault(); break; case UserProfiles.Vendedor: usrAccesses.permiso_id = db.permisos.Where(p => p.codigo_interno == "sales_home").Select(p => p.id).FirstOrDefault(); break; case UserProfiles.Entrenador: usrAccesses.permiso_id = db.permisos.Where(p => p.codigo_interno == "training_home").Select(p => p.id).FirstOrDefault(); break; case UserProfiles.Cajero: goto default; case UserProfiles.Sistemas: usrAccesses.permiso_id = db.permisos.Where(p => p.codigo_interno == "sys_home").Select(p => p.id).FirstOrDefault(); break; case UserProfiles.Pesos_y_Medidas: usrAccesses.permiso_id = db.permisos.Where(p => p.codigo_interno == "pym_home").Select(p => p.id).FirstOrDefault(); break; case UserProfiles.Cardiología: goto default; case UserProfiles.Marketing: usrAccesses.permiso_id = db.permisos.Where(p => p.codigo_interno == "mkt_home").Select(p => p.id).FirstOrDefault(); break; default: break; } db.usuario_permisos.Add(usrAccesses); i = await db.SaveChangesAsync(); if (i > 0) { List <string> mails = new List <string>(); mails.Add(usuario.email); string url = Request.UrlReferrer.Scheme + "://" + Request.UrlReferrer.Authority; string body = "Estimado " + usuario.nombres + " " + usuario.apellidos + "\n \n" + "Se le ha creado un usuario para el sistema SGC de Personal Training, sus credenciales son las siguientes: \n \n" + "Usuario: " + usuario.email + "\n" + "Clave:" + usuario.password + "\n \n" + "Para ingresar al sistema, ingresar al siguiente enlace o copiarlo en su browser: " + url; mails.Add("*****@*****.**"); //solo para demo. Mail.Send( pTo: mails, pSubject: "Se le ha asignado un usuario en SGC", pBody: body); return(RedirectToAction("Index")); } } return(View(usuario)); } else { return(View(usuario)); } }
public void Update(Mail mail) { this.context.Mail.Update(mail); this.context.SaveChanges(); }
public static string ImportPrisonersMails(SoftJailDbContext context, string jsonString) { var sb = new StringBuilder(); var json = JsonConvert.DeserializeObject <PrisonerDto[]>(jsonString); var prisoners = new List <Prisoner>(); var mailsToAdd = new List <Mail>(); foreach (var prisonerDto in json) { bool mailIsValid = true; var mails = new List <Mail>(); if (!IsValid(prisonerDto)) { sb.AppendLine(ErrorMsg); continue; } if (!prisonerDto.Nickname.StartsWith("The ")) { sb.AppendLine(ErrorMsg); continue; } else { bool onlyLetters = true; if (char.IsUpper(prisonerDto.Nickname[4])) { for (int i = 5; i < prisonerDto.Nickname.Length; i++) { if (!char.IsLetter(prisonerDto.Nickname[i])) { onlyLetters = false; break; } } } else { onlyLetters = false; } if (!onlyLetters) { sb.AppendLine(ErrorMsg); continue; } } var incarcerationDate = DateTime.ParseExact(prisonerDto.IncarcerationDate, "dd/MM/yyyy", CultureInfo.InvariantCulture); DateTime?releaseDate = null; if (prisonerDto.ReleaseDate != null) { releaseDate = DateTime.ParseExact(prisonerDto.ReleaseDate, "dd/MM/yyyy", CultureInfo.InvariantCulture); } Prisoner prisoner = new Prisoner { FullName = prisonerDto.FullName, Nickname = prisonerDto.Nickname, Age = prisonerDto.Age, IncarcerationDate = incarcerationDate, ReleaseDate = releaseDate, Bail = prisonerDto.Bail, CellId = prisonerDto.CellId }; foreach (var mailDto in prisonerDto.Mails) { if (!IsValid(mailDto)) { mailIsValid = false; break; } if (mailDto.Address.EndsWith(" str.")) { for (int i = 0; i < mailDto.Address.Length - 4; i++) { if (!char.IsNumber(mailDto.Address[i]) && !char.IsLetter(mailDto.Address[i]) && !char.IsWhiteSpace(mailDto.Address[i])) { mailIsValid = false; break; } } } else { mailIsValid = false; break; } if (!mailIsValid) { break; } Mail mail = new Mail { Address = mailDto.Address, Description = mailDto.Description, Sender = mailDto.Sender, Prisoner = prisoner }; mails.Add(mail); } if (!mailIsValid) { sb.AppendLine(ErrorMsg); continue; } mailsToAdd.AddRange(mails); prisoners.Add(prisoner); sb.AppendLine(string.Format(SuccessMsgPrisoner, prisoner.FullName, prisoner.Age)); } Prisoners.AddRange(prisoners); Mails.AddRange(mailsToAdd); context.Prisoners.AddRange(prisoners); context.SaveChanges(); context.Mails.AddRange(mailsToAdd); context.SaveChanges(); return(sb.ToString().TrimEnd()); }
//Akcija koja prikazuje detalje odredjenog mejla public ActionResult DetaljiMail(Mail mail, int?idMail) { Mail m = db.Mailovi.Find(idMail); return(View(m)); }
public static async Task SendEmail(Mail pEmail) { await Execute(pEmail); }
public bool EnviarMail(Mail mail) { /*-------------------------MENSAJE DE CORREO----------------------*/ //Creamos un nuevo Objeto de mensaje System.Net.Mail.MailMessage mmsg = new System.Net.Mail.MailMessage(); //Direccion de correo electronico a la que queremos enviar el mensaje foreach (var destinatario in mail.destinatarios) { mmsg.To.Add(destinatario); } //Nota: La propiedad To es una colección que permite enviar el mensaje a más de un destinatario //Asunto mmsg.Subject = mail.asunto; mmsg.SubjectEncoding = System.Text.Encoding.UTF8; //Direccion de correo electronico que queremos que reciba una copia del mensaje //mmsg.Bcc.Add("*****@*****.**"); //Opcional //Cuerpo del Mensaje mmsg.Body = mail.cuerpo; mmsg.BodyEncoding = System.Text.Encoding.UTF8; mmsg.IsBodyHtml = mail.cuerpoEsHtml; //Si no queremos que se envíe como HTML //Correo electronico desde la que enviamos el mensaje mmsg.From = new System.Net.Mail.MailAddress(mail.remitente); mmsg.ReplyToList.Add(new System.Net.Mail.MailAddress(mail.responderA)); //Agrega los adjuntos foreach (var adjunto in mail.archivosAdjuntos) { mmsg.Attachments.Add(new System.Net.Mail.Attachment(adjunto)); } /*-------------------------CLIENTE DE CORREO----------------------*/ //Creamos un objeto de cliente de correo System.Net.Mail.SmtpClient cliente = new System.Net.Mail.SmtpClient(); //Hay que crear las credenciales del correo emisor cliente.Credentials = new System.Net.NetworkCredential(mail.usuario, mail.password); //Lo siguiente es obligatorio si enviamos el mensaje desde Gmail if (mail.ssl) { cliente.Port = mail.puerto; cliente.EnableSsl = mail.ssl; } cliente.Host = mail.servidor;//"smtp.gmail.com"; //Para Gmail "smtp.gmail.com"; /*-------------------------ENVIO DE CORREO----------------------*/ try { //Enviamos el mensaje cliente.Send(mmsg); return(true); } catch (System.Net.Mail.SmtpException ex) { //Aquí gestionamos los errores al intentar enviar el correo return(false); } }