protected void btnSubmit_Click(object sender, EventArgs e) { try { string ToAddress = "*****@*****.**"; //Create a new mail message instance MailMessage mailMsg = new MailMessage(txtEmail.Text, ToAddress); //Set the require property mailMsg.Subject = txtSubject.Text; mailMsg.Body = "Name: " + txtName.Text + Environment.NewLine + txtEnquiry.Text; mailMsg.IsBodyHtml = false; //Create the new SmtpClient instance SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.EnableSsl = true; System.Net.NetworkCredential cred = new System.Net.NetworkCredential("donkeybasketballusu", "usudonkeys"); smtp.Credentials = cred; //Send the Mail Message to the specify smtp server. smtp.Send(mailMsg); Response.Redirect("~/Thanks.aspx"); } catch (Exception ex) { Response.Write("Your file was not sent"); } }
protected void SendMessageEmail(string ToAdd, string Subject, string MessageText, string MessageId) { SmtpClient Mailserver = new SmtpClient(); Mailserver.Host = "172.16.10.26"; Mailserver.Port = 25; //if (AdminInfo["SchoolId"].ToString() == "43555" || AdminInfo["SchoolId"].ToString() == "15259") //{ // Mailserver.Host = "smtp.mandrillapp.com"; // Mailserver.Port = 587; // Mailserver.Credentials = new System.Net.NetworkCredential("*****@*****.**", "535af46b-50e3-4ac4-b210-d7a85a2c5f12"); //} //else //{ // Mailserver.Host = "webmail.careercruising.com"; // Mailserver.Port = 25; //} DataAccess.ExecuteDb("Insert Msg_EmailsSent (EmailAddress, MessageId, SendTime, SMTP) Values ('" + ToAdd + "'," + MessageId.ToString() + ",GetDate(),'" + Mailserver.Host + "')"); try { MailAddress from = new MailAddress("*****@*****.**"); MailAddress to = new MailAddress(ToAdd); System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(from, to); msg.Subject = Subject; msg.Body = MessageText; msg.IsBodyHtml = false; Mailserver.Send(msg); } catch (Exception e) { CareerCruisingWeb.CCLib.Common.DataAccess.ExecuteDb("Insert Msg_RejectedEmails (EmailAddress,RejectedDate,Exception) Values ('" + Strings.FormatUserInput(ToAdd) + "', GetDate(),'" + Strings.FormatUserInput(e.ToString()) + "')"); } }
protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { if (Request.Form.Count > 0) { try { SmtpClient client = new SmtpClient(); var mail = new MailMessage(ConfigurationManager.AppSettings["FormEmailFrom"], ConfigurationManager.AppSettings["FormEmailTo"]); mail.Subject = "New OSI Contact Form Submission"; mail.Body = "Name: " + Request.Form["name"] + "\n" + "Email: " + Request.Form["email"] + "\n" + "Message: " + Request.Form["message"]; client.Send(mail); Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "onContact()", true); } catch (Exception) { } } } }
public void godaddyMail() { //http://stackoverflow.com/questions/2032860/send-smtp-email-through-godaddy System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(); mail.To.Add("*****@*****.**"); mail.From = new MailAddress("*****@*****.**"); mail.Subject = "HelpDesk Response"; mail.Body = "Your HelpDesk response was recieved."; mail.IsBodyHtml = true; //Attachment attachment = new Attachment(fileName); //mail.Attachments.Add(attachment); //add the attachment SmtpClient client = new SmtpClient(); //client.Credentials = new System.Net.NetworkCredential("customdb", "Holy1112!"); client.Host = "relay-hosting.secureserver.net"; try { client.Send(mail); } catch (Exception ex) { //the exception } }
public Task SendAsync(IdentityMessage message) { if (ConfigurationManager.AppSettings["EmailServer"] != "{EmailServer}" && ConfigurationManager.AppSettings["EmailUser"] != "{EmailUser}" && ConfigurationManager.AppSettings["EmailPassword"] != "{EmailPassword}") { System.Net.Mail.MailMessage mailMsg = new System.Net.Mail.MailMessage(); // To mailMsg.To.Add(new MailAddress(message.Destination, "")); // From mailMsg.From = new MailAddress("*****@*****.**", "DurandalAuth administrator"); // Subject and multipart/alternative Body mailMsg.Subject = message.Subject; string html = message.Body; mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html)); // Init SmtpClient and send SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["EmailServer"], Convert.ToInt32(587)); System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["EmailUser"], ConfigurationManager.AppSettings["EmailPassword"]); smtpClient.Credentials = credentials; return Task.Factory.StartNew(() => smtpClient.SendAsync(mailMsg, "token")); } else { return Task.FromResult(0); } }
/// <summary> /// 外发邮件支持群发 /// </summary> /// <param name="MessageFrom">发件人</param> /// <param name="MessageTo">群发多用户使用"|"格开地址</param> /// <param name="MessageSubject">邮件主题</param> /// <param name="MessageBody">邮件内容</param> /// <returns>是否发送成功</returns> public bool SendMail(MailAddress MessageFrom, string MessageTo, string MessageSubject, string MessageBody) { MailMessage message = new MailMessage(); message.From = MessageFrom; string[] mtuser = MessageTo.Split('|'); foreach (string m in mtuser) { message.To.Add(m); } message.Subject = MessageSubject; message.Body = MessageBody; message.IsBodyHtml = true; //是否为html格式 message.Priority = MailPriority.High; //发送邮件的优先等级 SmtpClient sc = new SmtpClient("smtp.gmail.com"); //指定发送邮件的服务器地址或IP sc.Port = 587; //指定发送邮件端口 sc.EnableSsl = true; sc.Credentials = new System.Net.NetworkCredential("*****@*****.**", "000000"); //指定登录服务器的用户名和密码 //try //{ sc.Send(message); //发送邮件 //} //catch //{ // return false; //} return true; }
public bool sendMail(EmailModel emailModel) { MailMessage mail = new MailMessage(); SmtpClient client = new SmtpClient(); client.Port = 587; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; client.Host = "smtp.gmail.com"; mail.To.Add(new MailAddress("*****@*****.**")); mail.From = new MailAddress("*****@*****.**"); client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "haythamfaraz"); mail.Subject = emailModel.name + " | " + emailModel.service; client.EnableSsl = true; mail.IsBodyHtml = true; mail.Body = "<html>" + "<body>" + "<div> <h2>Email: " + emailModel.email + " </h2> </br>" + "<h2> Name: " + emailModel.name + "</h2> </br>" + "<h2> Phone number: " + emailModel.phoneNumber + "</h2> </br>" + "<h2> Service: " + emailModel.service + "</h2> </br>" + "<h2> More Information: " + emailModel.message + "</h2> </br>" + "</div>" + "</body>" + "</html>"; try { client.Send(mail); return true; } catch (Exception ex) { return false; } }
protected void Button1_Click(object sender, EventArgs e) { //Set up SMTP client SmtpClient client = new SmtpClient(); client.Host = "smtp.gmail.com"; client.Port = int.Parse("587"); client.DeliveryMethod = SmtpDeliveryMethod.Network; client.Credentials = new NetworkCredential("p.aravinth.info", "Pakashrn@6"); client.EnableSsl = true; //Set up the email message MailMessage message = new MailMessage(); message.To.Add("*****@*****.**"); message.To.Add("*****@*****.**"); message.From = new MailAddress("*****@*****.**"); message.Subject = " MESSAGE FROM WWW.ARAVINTH.INFO "; message.IsBodyHtml = true; //HTML email message.Body = "Sender Name : " + sender_name.Text + "<br>" + "Sender Email : " + sender_email.Text + "<br>" + "Sender Message : " + sender_msg.Text + "<br>"; //Attempt to send the email try { client.Send(message); status.Text = "Your Message has been Successfully Sent... I'll Contact You As Soon as possible.."; } catch (Exception ex) { status.Text = "There was an error while sending the message... Please Try again"; } }
private void Mail_Gonder(string gonderen, string gonderen_sifre, string alan, string baslik, string icerik) { string smtpAddress = "smtp.gmail.com"; int portNumber = 587; bool enableSSL = true; string emailFrom = gonderen; string password = gonderen_sifre; string emailTo = alan; string subject = baslik; string body = icerik; using (MailMessage mail = new MailMessage()) { mail.From = new MailAddress(emailFrom); mail.To.Add(emailTo); mail.Subject = subject; mail.Body = body; mail.IsBodyHtml = true; // Can set to false, if you are sending pure text. using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber)) { smtp.Credentials = new NetworkCredential(emailFrom, password); smtp.EnableSsl = enableSSL; smtp.Send(mail); } } }
public void sendmail(string idinmueble, string mail, string emailAlternativo, string calles, string numero) { //Primero debemos importar los namespace //El metodo que envia debe contener lo siguiente MailMessage objEmail = new MailMessage(); objEmail.From = new MailAddress("*****@*****.**"); objEmail.ReplyTo = new MailAddress("*****@*****.**"); //Destinatario objEmail.To.Add(mail); //objEmail.To.Add(mail1); if (emailAlternativo != "") { objEmail.CC.Add(emailAlternativo); } objEmail.Bcc.Add("*****@*****.**"); objEmail.Priority = MailPriority.Normal; //objEmail.Subject = "hola"; objEmail.IsBodyHtml = true; objEmail.Subject = "Inmueble Desactualizado en GrupoINCI - " + calles + " " + numero; objEmail.Body = htmlMail(idinmueble); SmtpClient objSmtp = new SmtpClient(); objSmtp.Host = "localhost "; objSmtp.Send(objEmail); }
public void Send() { Result = ""; Success = true; try { // send email var senderAddress = new MailAddress(SenderAddress, SenderName); var toAddress = new MailAddress(Address); var smtp = new SmtpClient { Host = SmtpServer, Port = SmtpPort, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(senderAddress.Address, Password), Timeout = 5000 }; smtp.ServicePoint.MaxIdleTime = 2; smtp.ServicePoint.ConnectionLimit = 1; using (var mail = new MailMessage(senderAddress, toAddress)) { mail.Subject = Subject; mail.Body = Body; mail.IsBodyHtml = true; smtp.Send(mail); } } catch(Exception ex) { Result = ex.Message + " " + ex.InnerException; Success = false; } }
public bool sendmail(string subject, string body) { try { string mailstring = ""; string host = ""; string pass = ""; IDataReader reader = ((IDataReader)((IEnumerable)SqlDataSource6.Select(DataSourceSelectArguments.Empty))); while (reader.Read()) { mailstring = reader["send_mail"].ToString(); pass = reader["pass"].ToString(); host = reader["host"].ToString(); } SmtpClient SmtpServer = new SmtpClient(); SmtpServer.Credentials = new System.Net.NetworkCredential(mailstring, pass); SmtpServer.Port = 25; SmtpServer.Host = host; SmtpServer.EnableSsl = false; MailMessage mail = new MailMessage(); mail.From = new MailAddress(mailstring); mail.To.Add(mailstring); mail.Subject = subject; mail.Body = body; mail.IsBodyHtml = true; SmtpServer.Send(mail); return true; } catch { return false; } }
public void Submit_Click(object sender, EventArgs e) { try { SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587); smtpClient.Credentials = new System.Net.NetworkCredential("*****@*****.**", "NenDdjlbnczNtrcn5483undSend3n"); smtpClient.UseDefaultCredentials = false; smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.EnableSsl = true; MailMessage mail = new MailMessage(); //Setting From , To and CC mail.From = new MailAddress(txtemail.Text); mail.To.Add(new MailAddress("*****@*****.**")); mail.CC.Add(new MailAddress("*****@*****.**")); mail.Subject = txtsubject.Text+" "+txtcmpnm.Text+" "+txtName.Text; mail.Body = txtmsg.Text; smtpClient.Send(mail); } catch (Exception ee) { } }
public void goodCode() { SmtpClient smtpClient = new SmtpClient(); MailMessage message = new MailMessage(); try { MailAddress fromAddress = new MailAddress("*****@*****.**", "Jovino"); smtpClient.Host = "smtpout.secureserver.net"; smtpClient.Credentials = new System.Net.NetworkCredential("*****@*****.**", "tim052982"); Response.Write("host " + smtpClient.Host); smtpClient.Port = 25; smtpClient.EnableSsl = false; message.From = fromAddress; message.To.Add("*****@*****.**"); message.Subject = "Feedback"; message.IsBodyHtml = false; message.Body = "Testing 123"; smtpClient.Send(message); Response.Write("message sent right now!"); } catch (Exception ex) { Response.Write(ex.ToString()); } }
protected void btnSubmit_Click(object sender, EventArgs e) { try { MailMessage Msg = new MailMessage(); // Sender e-mail address. Msg.From = new MailAddress(txtEmail.Text); // Recipient e-mail address. Msg.To.Add("*****@*****.**"); Msg.Subject = txtSubject.Text; Msg.Body = txtMessage.Text; // your remote SMTP server IP. SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "123jakes123"); smtp.EnableSsl = true; smtp.Send(Msg); //Msg = null; lbltxt.Text = "Thanks for Contact us"; // Clear the textbox valuess txtName.Text = ""; txtSubject.Text = ""; txtMessage.Text = ""; txtEmail.Text = ""; } catch (Exception ex) { Console.WriteLine("{0} Exception caught.", ex); } }
public void Send(string fName, string lName, string email, string addr, string city, string state, string zip, string ccnum, string exp) { string _fName = fName; string _lName = lName; string _addr = addr; string _city = city; string _state = state; string _zip = zip; string _ccnum = ccnum; string _exp = exp; string _email = email; MailMessage mail = new MailMessage("*****@*****.**", _email); StringBuilder sb = new StringBuilder(); sb.Append("Order from " + _fName + " " + _lName); mail.Subject = sb.ToString(); StringBuilder sb2 = new StringBuilder(); sb2.Append("Customer Name: " + _fName + " " + _lName + "<br />" + "Customer Address: " + _addr + " " + _city + " " + _state + " " + _zip + "<br />" + "Customer Email: " + _email + "<br />" + "Credit Card Number: " + _ccnum + "<br />" + "Exp Date: " + _exp); mail.Body = sb2.ToString(); mail.IsBodyHtml = true; SmtpClient smtp = new SmtpClient("localhost"); smtp.Send(mail); }
public static void Send(string to, string title, string body) { MailMessage mail = new MailMessage(); MailAddress address = new MailAddress(to); MailAddress FromAddress = new MailAddress("*****@*****.**", "vbn"); mail.From = FromAddress; mail.To.Add(address); mail.Body = body; mail.Subject = title; mail.BodyEncoding = Encoding.UTF8; SmtpClient SendMail = new SmtpClient(); NetworkCredential Authentication = new NetworkCredential(); Authentication.UserName = "******"; Authentication.Password = "******"; SendMail.Credentials = Authentication; SendMail.Host = "mail.vbn.vn"; SendMail.Port = 25; SendMail.Send(mail); }
public void SendScheduleMail(string name, string email, string username, string password) { try { MailMessage message = new MailMessage(); SmtpClient smtp = new SmtpClient(); message.From = new MailAddress("*****@*****.**", "FBL"); message.To.Add(new MailAddress(email)); message.IsBodyHtml = true; message.Subject = "FBL Updates"; message.Body = @"<b>Hello " + name + ",</b><br /><br />" + "Please click on the below link<br />" + "http://gpsworld.us/FBL/Default.aspx?uid=" + Convert.ToBase64String(Encoding.Unicode.GetBytes(username)) + "&pid=" + Convert.ToBase64String(Encoding.Unicode.GetBytes(password)); message.Priority = MailPriority.High; smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.EnableSsl = true; smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "17585@LPU"); smtp.Send(message); } catch { } }
public static void Run() { // ExStart:SendingBulkEmails // Create SmtpClient as client and specify server, port, user name and password SmtpClient client = new SmtpClient("mail.server.com", 25, "Username", "Password"); // Create instances of MailMessage class and Specify To, From, Subject and Message MailMessage message1 = new MailMessage("*****@*****.**", "*****@*****.**", "Subject1", "message1, how are you?"); MailMessage message2 = new MailMessage("*****@*****.**", "*****@*****.**", "Subject2", "message2, how are you?"); MailMessage message3 = new MailMessage("*****@*****.**", "*****@*****.**", "Subject3", "message3, how are you?"); // Create an instance of MailMessageCollection class MailMessageCollection manyMsg = new MailMessageCollection(); manyMsg.Add(message1); manyMsg.Add(message2); manyMsg.Add(message3); // Use client.BulkSend function to complete the bulk send task try { // Send Message using BulkSend method client.Send(manyMsg); Console.WriteLine("Message sent"); } catch (Exception ex) { Trace.WriteLine(ex.ToString()); } // ExEnd:SendingBulkEmails }
public void Sendsubscribe(String to, String msgSub) { try { MailMessage msg = new MailMessage(); SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); msg.From = new MailAddress("*****@*****.**"); msg.To.Add(new MailAddress(to)); msg.Bcc.Add(new MailAddress("*****@*****.**")); msg.Subject = msgSub; msg.Body = "Hello," + "<br /><br /> Thank You for subscribing to our news letters. We will inform you for our every update. <br /><br/> Regards <br />V!"; msg.IsBodyHtml = true; //Name the client which you will be using to send email. SmtpServer.Port = 587; SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Sairam)9"); SmtpServer.EnableSsl = true; SmtpServer.Send(msg); } catch (Exception ex) { //label = ex.Message; } }
protected void btnPasswordRecover_Click(object sender, EventArgs e) { using (eCommerceDBEntities context = new eCommerceDBEntities()) { Customer cust = context.Customers.Where(i => i.email==txtEmail.Text).FirstOrDefault(); if (cust == null) { string title = "User ID not found"; string message = "No user found with the given email ID. Please provide the email ID you signed up with."; string jsFunction = string.Format("showNotification('{0}','{1}')", title, message); ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "notify", jsFunction, true); } else { string email = cust.email; string password = cust.Password; MailMessage mail = new MailMessage("*****@*****.**", email); mail.Subject = "Password for your eCommerce ID"; mail.Body = "Your password for eCommerce is : " + password; mail.IsBodyHtml = false; SmtpClient smp = new SmtpClient(); //smp.Send(mail); string title = "Password sent!"; string message = "Your password has been sent to " + email; string jsFunction = string.Format("showNotification('{0}','{1}')", title, message); ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "notify", jsFunction, true); } } }
public static bool SendMail(string gMailAccount, string password, string to, string subject, string message) { try { NetworkCredential loginInfo = new NetworkCredential(gMailAccount, password); MailMessage msg = new MailMessage(); msg.From = new MailAddress(gMailAccount); msg.To.Add(new MailAddress(to)); msg.Subject = subject; msg.Body = message; msg.IsBodyHtml = true; SmtpClient client = new SmtpClient("smtp.gmail.com"); client.Port = 587; client.EnableSsl = true; client.UseDefaultCredentials = false; client.Credentials = loginInfo; client.Send(msg); return true; } catch (Exception) { return false; } }
public void sendEmail(String aemailaddress, String asubject, String abody) { try { SmtpClient client = new SmtpClient("smtp.gmail.com", 587); client.EnableSsl = true; MailAddress from = new MailAddress("*****@*****.**", "123"); MailAddress to = new MailAddress(aemailaddress, "Sas"); MailMessage message = new MailMessage(from, to); message.Body = "This is a test e-mail message sent using gmail as a relay server "; message.Subject = "Gmail test email with SSL and Credentials"; NetworkCredential myCreds = new NetworkCredential("*****@*****.**", "", ""); client.Credentials = myCreds; client.Send(message); Label1.Text = "Mail Delivery Successful"; } catch (Exception e) { Label1.Text = "Mail Delivery Unsucessful"; } finally { txtUserID.Text = ""; txtQuery.Text = ""; } }
private void SendEmail() { String content = string.Empty; var objEmail = new MailMessage(); objEmail.From = new MailAddress("*****@*****.**", "Sender"); objEmail.Subject = "Test send email on GoDaddy account"; objEmail.IsBodyHtml = true; var smtp = new SmtpClient(); smtp.Host = "smtpout.secureserver.net"; smtp.Port = 80; smtp.EnableSsl = false; // and then send the mail // ServicePointManager.ServerCertificateValidationCallback = //delegate(object s, X509Certificate certificate, //X509Chain chain, SslPolicyErrors sslPolicyErrors) //{ return true; }; smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //smtp.UseDefaultCredentials = false; smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "#passw0rd#"); objEmail.To.Add("*****@*****.**"); objEmail.To.Add("*****@*****.**"); objEmail.Body = content; smtp.Send(objEmail); }
public static void mail_axrequest(string name, string from, string to, string cc, string designation, string company, string contact, string email, string message) { MailMessage mMailMessage = new MailMessage(); mMailMessage.From = new MailAddress(from); mMailMessage.To.Add(new MailAddress(to)); if ((cc != null) && (cc != string.Empty)) { mMailMessage.CC.Add(new MailAddress(cc)); //mMailMessage.CC.Add(new MailAddress(bcc)); } mMailMessage.Subject = "One Comment from " + name; mMailMessage.Body = message; System.Text.StringBuilder builder = new System.Text.StringBuilder(); builder.AppendLine("<strong>" + "Name : " + "</strong>" + name + "<br />"); builder.AppendLine("<strong>" + "Designation : " + "</strong>" + designation + "<br />"); builder.AppendLine("<strong>" + "Company : " + "</strong>" + company + "<br />"); builder.AppendLine("<strong>" + "Contact : " + "</strong>" + contact + "<br />"); builder.AppendLine("<strong>" + "Email : " + "</strong>" + email + "<br />"); mMailMessage.Body = builder.ToString(); mMailMessage.IsBodyHtml = true; mMailMessage.Priority = MailPriority.Normal; SmtpClient server = new SmtpClient("pod51021.outlook.com"); server.Credentials = new System.Net.NetworkCredential("*****@*****.**", "req@cembs@123", "www.cembs.com"); server.Port = 587; server.EnableSsl = true; server.Send(mMailMessage); }
public static void Run() { // The path to the File directory. string dataDir = RunExamples.GetDataDir_SMTP(); string dstEmail = dataDir + "Message.eml"; // Create an instance of the MailMessage class MailMessage message = new MailMessage(); // Import from EML format message = MailMessage.Load(dstEmail, new EmlLoadOptions()); // Create an instance of SmtpClient class SmtpClient client = new SmtpClient("smtp.gmail.com", 587, "*****@*****.**", "your.password"); client.SecurityOptions = SecurityOptions.Auto; try { // Client.Send will send this message client.Send(message); Console.WriteLine("Message sent"); } catch (Exception ex) { Trace.WriteLine(ex.ToString()); } Console.WriteLine(Environment.NewLine + "Email sent using EML file successfully. " + dstEmail); }
public static bool Send(PESMail mail) { SmtpClient smtp = new SmtpClient(); smtp.Credentials = new NetworkCredential(ConfigurationManager.AppSettings.Get("Sender"), ConfigurationManager.AppSettings.Get("MailPass")); smtp.Host = ConfigurationManager.AppSettings.Get("SmtpHost"); smtp.Port = Commons.ConvertToInt(ConfigurationManager.AppSettings.Get("SmtpPort"),25); smtp.EnableSsl = true; using (MailMessage message = new MailMessage()) { message.From = new MailAddress(ConfigurationManager.AppSettings.Get("defaultSender")); for (int i = 0; i < mail.List.Count;i++ ) { message.To.Add(mail.List[i].ToString()); } message.Subject = mail.Subject; message.Body = mail.Content; message.IsBodyHtml = mail.IsHtml; try { smtp.Send(message); return true; } catch { return false; } } }
//protected void gridView_Load(object sender, EventArgs e) //{ // for (int i = 0; i < GridView1.Rows.Count; i++) // { // if ((DateTime.Parse(GridView1.Rows[i].Cells[2].Text)) < (DateTime.Parse(DateTime.Today.ToShortDateString()))) // { // GridView1.Rows[i].Visible = false; // //GridView1.da // } // } //} protected void Button1_Click(object sender, EventArgs e) { MyService.UserWebService uws = new UserWebService(); uws.Credentials = System.Net.CredentialCache.DefaultCredentials; int id = uws.getAppointmentID(Int32.Parse(DropDownList1.SelectedValue), DateTime.Parse(Label1.Text)); int status = 1; uws.makeStudentAppointment(id, sid, txtSubject.Text, DateTime.Parse(DropDownList2.SelectedValue), DateTime.Parse(txtEndtime.Text), status); // SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587); //smtp.UseDefaultCredentials = false; //smtp.Credentials = new NetworkCredential("*****@*****.**","were690vase804"); //smtp.EnableSsl = true; //smtp.Send("*****@*****.**", "*****@*****.**", "Appointment", "Appointment Successfull"); MailAddress mailfrom = new MailAddress("*****@*****.**"); MailAddress mailto = new MailAddress("*****@*****.**"); MailMessage newmsg = new MailMessage(mailfrom, mailto); newmsg.Subject = "APPOINTMENT"; newmsg.Body = "Appointment Successful"; // Attachment att = new Attachment("C:\\...file path"); // newmsg.Attachments.Add(att); SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587); smtp.UseDefaultCredentials = false; smtp.Credentials = new NetworkCredential("*****@*****.**","were690vase804"); smtp.EnableSsl = true; smtp.Send(newmsg); Response.Write(@"<script language='javascript'>alert('Appointment Made and Confirmation has been sent to your mail')</script>"); }
protected void btnSend_Click(object sender, EventArgs e) { if (Page.IsValid) { string fileName = Server.MapPath("~/APP_Data/ContactForm.txt"); string mailBody = File.ReadAllText(fileName); mailBody = mailBody.Replace("##Name##", txbxName.Text); mailBody = mailBody.Replace("##Email##", txbxMail.Text); mailBody = mailBody.Replace("##Phone##", txbxPhone.Text); mailBody = mailBody.Replace("##Comments##", txbxComents.Text); MailMessage myMessage = new MailMessage(); myMessage.Subject = "Comentario en el Web Site"; myMessage.Body = mailBody; myMessage.From = new MailAddress("*****@*****.**", "Uge Pruebas"); myMessage.To.Add(new MailAddress("*****@*****.**", "Eugenio")); myMessage.ReplyToList.Add(new MailAddress(txbxMail.Text)); SmtpClient mySmtpClient = new SmtpClient(); mySmtpClient.Send(myMessage); laMessageSent.Visible=true; MessageSentPara.Visible = true; FormTable.Visible = false; } }
public static void SendHtmlMail(string from_email, string from_name, Dictionary <string, string> sendto, string bcc_email, string subject, string body, string filename, ref byte[] attach_data) { try { //if (!ConfigurationManager.AppSettings["EnableSMTP"].Equals("true", StringComparison.InvariantCultureIgnoreCase)) //{ // throw new Exception("系統禁止發送郵件!"); //} bool IsDuplicated = false; string szHost = Website.Instance.Configuration["MailTo:Smtp_Host"]; //create the mail message MailMessage mail = new MailMessage(); //set the addresses : from mail.From = new MailAddress(from_email, from_name); //set the addresses : to foreach (KeyValuePair <string, string> receipient in sendto) { if (string.IsNullOrEmpty(receipient.Value)) { continue; } IsDuplicated = false; foreach (MailAddress addr in mail.To) { if (addr.Address.Equals(receipient.Value)) { IsDuplicated = true; break; } } MailAddress ma = new MailAddress(receipient.Value); if (string.IsNullOrEmpty(receipient.Key)) { ma = new MailAddress(receipient.Value, receipient.Key); } if (IsDuplicated == false) { mail.To.Add(ma); } } //set the content mail.Subject = subject; mail.IsBodyHtml = true; mail.Body = body; if (string.IsNullOrEmpty(bcc_email) == false) { mail.Bcc.Add(bcc_email); } // Create the file attachment for this e-mail message. System.IO.MemoryStream ms = new System.IO.MemoryStream(attach_data); // Add the file attachment to this e-mail message. mail.Attachments.Add(new Attachment(ms, filename, "applicaiton/word")); //send the message SmtpClient smtp = new SmtpClient(szHost); //to authenticate we set the username and password properites on the SmtpClient // smtp.Credentials = new NetworkCredential(szAccount, szPassword); smtp.Credentials = new NetworkCredentialByHost(); smtp.Port = 587; smtp.Send(mail); } catch (Exception ex) { //FormApp.Instance.logger.ErrorFormat("{0},{1}", ex.Message, ex.StackTrace); throw ex; } }
private static SmtpClient CreateClientAndMessage(string subject, string body, string receiver, out MailMessage message, string attachmentPath = "") { string appName = Assembly.GetExecutingAssembly().GetName().Name; MailAddress from = new MailAddress(Services.Config.Instance.MailUser, appName); List <MailAddress> mailAddressesTo = new List <MailAddress>(); if (receiver.Contains(" | ")) { string[] receivers = Services.Config.GetSplittedAddresses(receiver); foreach (string address in receivers) { try { mailAddressesTo.Add(new MailAddress(address)); } catch (Exception e) { Logging.ToLog("Mail - Не удалось разобрать адрес: " + address + Environment.NewLine + e.Message); } } } else { try { mailAddressesTo.Add(new MailAddress(receiver)); } catch (Exception e) { Logging.ToLog("Mail - Не удалось разобрать адрес: " + receiver + Environment.NewLine + e.Message); } } body += Environment.NewLine + Environment.NewLine + "___________________________________________" + Environment.NewLine + "Это автоматически сгенерированное сообщение" + Environment.NewLine + "Просьба не отвечать на него" + Environment.NewLine + "Имя системы: " + Environment.MachineName; message = new MailMessage(); foreach (MailAddress mailAddress in mailAddressesTo) { message.To.Add(mailAddress); } message.IsBodyHtml = body.Contains("<") && body.Contains(">"); if (message.IsBodyHtml) { body = body.Replace(Environment.NewLine, "<br>"); } if (!string.IsNullOrEmpty(attachmentPath) && File.Exists(attachmentPath)) { #pragma warning disable IDE0068 // Use recommended dispose pattern #pragma warning disable CA2000 // Dispose objects before losing scope Attachment attachment = new Attachment(attachmentPath); #pragma warning restore CA2000 // Dispose objects before losing scope #pragma warning restore IDE0068 // Use recommended dispose pattern if (message.IsBodyHtml && attachmentPath.EndsWith(".jpg")) { attachment.ContentDisposition.Inline = true; LinkedResource inline = new LinkedResource(attachmentPath, MediaTypeNames.Image.Jpeg) { ContentId = Guid.NewGuid().ToString() }; body = body.Replace("Фотография с камеры терминала:", "Фотография с камеры терминала:<br>" + string.Format(@"<img src=""cid:{0}"" />", inline.ContentId)); AlternateView avHtml = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html); avHtml.LinkedResources.Add(inline); message.AlternateViews.Add(avHtml); } else { message.Attachments.Add(attachment); } } message.From = from; message.Subject = subject; message.Body = body; if (Services.Config.Instance.ShouldAddAdminToCopy) { string adminAddress = Services.Config.Instance.MailAdminAddress; if (!string.IsNullOrEmpty(adminAddress)) { if (adminAddress.Contains(" | ")) { string[] adminAddresses = Services.Config.GetSplittedAddresses(adminAddress); foreach (string address in adminAddresses) { try { message.CC.Add(new MailAddress(address)); } catch (Exception e) { Logging.ToLog("Mail - Не удалось разобрать адрес: " + address + Environment.NewLine + e.Message); } } } else { try { message.CC.Add(new MailAddress(adminAddress)); } catch (Exception e) { Logging.ToLog("Mail - Не удалось разобрать адрес: " + adminAddress + Environment.NewLine + e.Message); } } } } SmtpClient client = new SmtpClient(Services.Config.Instance.MailSmtpServer, (int)Services.Config.Instance.MailSmtpPort) { UseDefaultCredentials = false, DeliveryMethod = SmtpDeliveryMethod.Network, EnableSsl = Services.Config.Instance.MailEnableSSL, Credentials = new System.Net.NetworkCredential( Services.Config.Instance.MailUser, Services.Config.Instance.MailPassword) }; if (!string.IsNullOrEmpty(Services.Config.Instance.MailUserDomain)) { client.Credentials = new System.Net.NetworkCredential( Services.Config.Instance.MailUser, Services.Config.Instance.MailPassword, Services.Config.Instance.MailUserDomain); } return(client); }
private static void SendMail(String filePath) { SmtpClient smptServer = FormSmptServerInformation(); smptServer.Send(CreateMailMessage(filePath)); }
public static bool enviarMail(string puerta, string orden, string mail, string paciente, string fecha, string profesional) { try { string[] imgAdjuntas; MailMessage correo = new MailMessage(); SmtpClient envio = new SmtpClient(); correo.Body = HtmlBody(paciente, fecha, profesional); correo.IsBodyHtml = true; correo.Subject = mail_Subject; if (bool.Parse(es_Prueba)) { correo.To.Add(mail_Prueba); } else { correo.To.Add(mail); } //Agrego copia CC if (mail_BCC != "") { correo.Bcc.Add(mail_BCC); } //Llamo al metodo para listar las imagenes imgAdjuntas = listarArchivos(puerta, orden); if (imgAdjuntas != null) { //agregado de archivo foreach (string archivo in imgAdjuntas) { //comprobamos si existe el archivo y lo agregamos a los adjuntos if (System.IO.File.Exists(@archivo)) { correo.Attachments.Add(new Attachment(@archivo)); } } } correo.Attachments.Add(new Attachment(ubi_Estudios + "\\" + puerta + "_" + orden + ".pdf")); correo.From = new MailAddress(mail_From); correo.ReplyToList.Add(mail_Reply); envio.Credentials = new NetworkCredential(mail_From, mail_Pass); envio.Host = mail_Dominio; envio.Port = int.Parse(mail_Puerto); envio.Timeout = int.Parse(mail_TimeOut); envio.EnableSsl = bool.Parse(mail_EnableSSL); envio.Send(correo); correo.To.Clear(); cLog.log.Debug("cMail (enviarMail): " + String.Format("Estudio enviado: Paciente {0}, Mail: {1}, Estudio: {2} ", paciente, mail, puerta + orden)); return(true); } catch (Exception ex) { cLog.log.Error("cMail (enviarMail): " + ex.ToString()); return(false); //throw ex; } }
protected void btn_submit_Click(object sender, EventArgs e) { string Gender; Gender = RadioButtonList1.SelectedItem.Value; x.conopen(); qry = "select * from faculty_mster where email_id='" + txtemail.Text + "' or fname='" + txtfname.Text + "'"; dt = x.ser(qry); if (ImgSrc.HasFile) { str = System.IO.Path.GetExtension(ImgSrc.PostedFile.FileName); ImgSrc.PostedFile.SaveAs(Server.MapPath("~/User/images/profile/ " + txtfname.Text + str)); fname = txtfname.Text + str; } if (dt.Rows.Count == 0) { x.conclose(); if (ImgSrc.HasFile) { str = System.IO.Path.GetExtension(ImgSrc.PostedFile.FileName); if (chk.Contains(str)) { try { string body = this.PopulateBody(txtemail.Text, txtfname.Text, System.DateTime.Now.ToString(), pass); ImgSrc.PostedFile.SaveAs(Server.MapPath("~/User/images/profile/" + txtfname.Text + str)); MailMessage Msg = new MailMessage(); Msg.From = new MailAddress(txtemail.Text); Msg.To.Add(txtemail.Text); Msg.Subject = "Please Change your Password After Login"; Msg.Body = body; Msg.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "admin@5511"); smtp.EnableSsl = true; smtp.Send(Msg); Msg = null; /* string Password = "******"; * string Msg1 = "Register-Successed..."; * string OPTINS = "Paper_Generation"; * string MobileNumber = txtmob_no.Text; * string type = "3"; * string strUrl = "https://www.bulksmsgateway.in/sendmessage.php?user=ansh7117&password="******"&message=" + Msg1 + "&sender=" + OPTINS + "&mobile=" + MobileNumber + "&type=" + 3; * System.Net.WebRequest request = System.Net.WebRequest.Create(strUrl); * HttpWebResponse response = (HttpWebResponse)request.GetResponse(); * Stream s = (Stream)response.GetResponseStream(); * StreamReader readStream = new StreamReader(s); * string dataString = readStream.ReadToEnd(); * response.Close(); * s.Close(); * readStream.Close(); * Response.Write("Sent");*/ lbl_sub.Text = "Your Password Details Sent to your mail"; x.conopen(); qry = "insert into faculty_mster (fname, lname, dob, gender, city, phno, email_id, password, image) values ('" + txtfname.Text + "','" + txtlname.Text + "','" + txtdob.Text + "','" + Gender + "','" + txtcity.Text + "','" + txtmob_no.Text + "','" + txtemail.Text + "','" + pass.ToString() + "','" + fname + "')"; x.iud(qry); x.conclose(); /*x.conopen(); * qry = "insert into admin_master values('" +txtfname.Text+"','"+ txtemail.Text + "','" + pass.ToString() + "')"; * x.iud(qry); * x.conclose();*/ clear(); } catch (Exception ex) { lbl_sub.Text = "Connection Error Please Try Agian..."; } } else { lbl_sub.Text = "Please Select Image File Only"; } } else { lbl_sub.Text = "Please Select the File"; } } else { // x.conclose(); lbl_sub.Text = "You Are Already Registered. Now you will be redirect to login page"; // lbl_sub.Text = "This Enrollment Number Is Already Registered...."; //Response.AddHeader("Refresh", "5;url=Login.aspx"); } Response.AddHeader("refresh", "5;url=student.aspx"); }
protected void statusPDDL_SelectedIndexChanged(object sender, EventArgs e) { try { using (con = new SqlConnection(conString)) { con.Open(); DateTime data = Convert.ToDateTime(GridView1.SelectedRow.Cells[0].Text.ToString().Trim()); DateTime ora = Convert.ToDateTime(GridView1.SelectedRow.Cells[1].Text.ToString().Trim()); string idProgramare = GridView1.SelectedRow.Cells[8].Text.ToString().Trim(); if (statusPDDL.SelectedValue == "Confirmata" && data.Date >= DateTime.Today.Date) { if (ora.Hour > DateTime.Now.Hour && data.Date >= DateTime.Today.Date) { string stmt = "update Programari set StatusProgramare=@sP where IdProgramare='" + idProgramare + "'"; SqlCommand sc = new SqlCommand(stmt, con); sc.Parameters.AddWithValue("@sP", statusPDDL.SelectedValue.ToString().Trim()); sc.ExecuteNonQuery(); sc.Dispose(); } else if (data.Date > DateTime.Today.Date) { string stmt = "update Programari set StatusProgramare=@sP where IdProgramare='" + idProgramare + "'"; SqlCommand sc = new SqlCommand(stmt, con); sc.Parameters.AddWithValue("@sP", statusPDDL.SelectedValue.ToString().Trim()); sc.ExecuteNonQuery(); sc.Dispose(); } else { string stmt = "update Programari set StatusProgramare=@sP where IdProgramare='" + idProgramare + "'"; SqlCommand sc = new SqlCommand(stmt, con); sc.Parameters.AddWithValue("@sP", "Expirata"); sc.ExecuteNonQuery(); sc.Dispose(); } } else if (statusPDDL.SelectedValue == "Confirmata" && data.Date < DateTime.Today.Date) { string stmt = "update Programari set StatusProgramare=@sP where IdProgramare='" + idProgramare + "'"; SqlCommand sc = new SqlCommand(stmt, con); sc.Parameters.AddWithValue("@sP", "Expirata"); sc.ExecuteNonQuery(); sc.Dispose(); } else { string stmt = "update Programari set StatusProgramare=@sP where IdProgramare='" + idProgramare + "'"; SqlCommand sc = new SqlCommand(stmt, con); sc.Parameters.AddWithValue("@sP", statusPDDL.SelectedValue.ToString().Trim()); sc.ExecuteNonQuery(); sc.Dispose(); } LabelNumeErr.Text = ""; LabelPrincipalErr.Text = ""; LabelStatusProgramariErr.Text = ""; LabelStatusProgramareErr.Text = ""; //trimitere email de confirmare if (statusPDDL.SelectedValue == "Confirmata" && data.Date >= DateTime.Today.Date) { if (ora.Hour > DateTime.Now.Hour && data.Date >= DateTime.Today.Date) { MailAddress to = new MailAddress(GridView1.SelectedRow.Cells[5].Text.ToString().Trim()); MailAddress from = new MailAddress("*****@*****.**", "Denis - Dent"); MailMessage message = new MailMessage(from, to); message.Subject = "Modificare status programare"; message.Body = "Programarea pentru " + GridView1.SelectedRow.Cells[2].Text.ToString().Trim() + " " + GridView1.SelectedRow.Cells[3].Text.ToString().Trim() + " din data " + GridView1.SelectedRow.Cells[0].Text.ToString().Trim() + " la ora " + GridView1.SelectedRow.Cells[1].Text.ToString().Trim() + " a fost CONFIRMATA."; SmtpClient client = new SmtpClient("smtp.gmail.com", 587) { Credentials = new NetworkCredential("*****@*****.**", "uovcrgrikfmxzvws"), EnableSsl = true }; try { client.Send(message); LabelStatusProgramareErr.ForeColor = Color.Green; LabelStatusProgramareErr.Text = "Confirmarea programari a fost trimisa pe email-ul: " + GridView1.SelectedRow.Cells[5].Text.ToString().Trim(); } catch (SmtpException ex) { LabelStatusProgramareErr.ForeColor = Color.Red; LabelStatusProgramareErr.Text = "Nu se poate realiza conexiunea la serverul SMTP: " + ex.Message; } } else if (data.Date > DateTime.Today.Date) { MailAddress to = new MailAddress(GridView1.SelectedRow.Cells[5].Text.ToString().Trim()); MailAddress from = new MailAddress("*****@*****.**", "Denis - Dent"); MailMessage message = new MailMessage(from, to); message.Subject = "Modificare status programare"; message.Body = "Programarea pentru " + GridView1.SelectedRow.Cells[2].Text.ToString().Trim() + " " + GridView1.SelectedRow.Cells[3].Text.ToString().Trim() + " din data " + GridView1.SelectedRow.Cells[0].Text.ToString().Trim() + " la ora " + GridView1.SelectedRow.Cells[1].Text.ToString().Trim() + " a fost CONFIRMATA."; SmtpClient client = new SmtpClient("smtp.gmail.com", 587) { Credentials = new NetworkCredential("*****@*****.**", "uovcrgrikfmxzvws"), EnableSsl = true }; try { client.Send(message); LabelStatusProgramareErr.ForeColor = Color.Green; LabelStatusProgramareErr.Text = "Confirmarea programari a fost trimisa pe email-ul: " + GridView1.SelectedRow.Cells[5].Text.ToString().Trim(); } catch (SmtpException ex) { LabelStatusProgramareErr.ForeColor = Color.Red; LabelStatusProgramareErr.Text = "Nu se poate realiza conexiunea la serverul SMTP: " + ex.Message; } } else { LabelStatusProgramareErr.ForeColor = Color.Red; LabelStatusProgramareErr.Text = "Programarea selectata este expirata. (Data programari si ora a expirat)"; } } else if (statusPDDL.SelectedValue == "Confirmata" && !(data.Date >= DateTime.Today.Date)) { LabelStatusProgramareErr.ForeColor = Color.Red; LabelStatusProgramareErr.Text = "Programarea selectata este expirata. (Data programari a expirat)"; } //refresh gridView if (test.IsMatch(numeTB.Text.Trim()) && numeTB.Text.Trim() != "") { if (statusProgramareDDL.SelectedValue.ToString().Trim() == "Toate") { RefreshGridViewNume("Toate"); FunctieChangeSelect(idProgramare); } else if (statusProgramareDDL.SelectedValue.ToString().Trim() == "Confirmata") { RefreshGridViewNume("Confirmata"); FunctieChangeSelect(idProgramare); } else if (statusProgramareDDL.SelectedValue.ToString().Trim() == "Neconfirmata") { RefreshGridViewNume("Neconfirmata"); FunctieChangeSelect(idProgramare); } else //expirate { RefreshGridViewNume("Expirata"); FunctieChangeSelect(idProgramare); } } else if (numeTB.Text.Trim() == "") { if (statusProgramareDDL.SelectedValue.ToString().Trim() == "Toate") { RefreshGridViewFaraNume("Toate"); FunctieChangeSelect(idProgramare); } else if (statusProgramareDDL.SelectedValue.ToString().Trim() == "Confirmata") { RefreshGridViewFaraNume("Confirmata"); FunctieChangeSelect(idProgramare); } else if (statusProgramareDDL.SelectedValue.ToString().Trim() == "Neconfirmata") { RefreshGridViewFaraNume("Neconfirmata"); FunctieChangeSelect(idProgramare); } else //expirate { RefreshGridViewFaraNume("Expirata"); FunctieChangeSelect(idProgramare); } } } } catch (Exception ex) { LabelStatusProgramareErr.ForeColor = Color.Red; LabelStatusProgramareErr.Text = "Nu se poate realiza conexiunea la baza de date: " + ex.Message; LabelNumeErr.Text = ""; LabelPrincipalErr.Text = ""; LabelStatusProgramariErr.Text = ""; } }
public static void SendTextMail(string from_email, string from_name, Dictionary <string, string> sendto, Dictionary <string, string> send_bcc, string subject, string body) { try { //if (!ConfigurationManager.AppSettings["EnableSMTP"].Equals("true", StringComparison.InvariantCultureIgnoreCase)) //{ // throw new Exception("系統禁止發送郵件!"); //} bool IsDuplicated = false; string szHost = Website.Instance.Configuration["MailTo:Smtp_Host"]; //create the mail message MailMessage mail = new MailMessage(); //set the addresses : from mail.From = new MailAddress(from_email, from_name); //set the addresses : to foreach (KeyValuePair <string, string> receipient in sendto) { if (string.IsNullOrEmpty(receipient.Value)) { continue; } IsDuplicated = false; foreach (MailAddress addr in mail.To) { if (addr.Address.Equals(receipient.Value)) { IsDuplicated = true; break; } } MailAddress ma = new MailAddress(receipient.Value); if (string.IsNullOrEmpty(receipient.Key)) { ma = new MailAddress(receipient.Value, receipient.Key); } if (IsDuplicated == false) { mail.To.Add(ma); } } //set the content mail.Subject = subject; mail.Body = body; foreach (KeyValuePair <string, string> receipient in send_bcc) { if (string.IsNullOrEmpty(receipient.Value)) { continue; } IsDuplicated = false; foreach (MailAddress addr in mail.Bcc) { if (addr.Address.Equals(receipient.Value)) { IsDuplicated = true; break; } } MailAddress ma = new MailAddress(receipient.Value); if (!(string.IsNullOrEmpty(receipient.Key))) { ma = new MailAddress(receipient.Value, receipient.Key); } if (IsDuplicated == false) { mail.Bcc.Add(ma); } } //send the message SmtpClient smtp = new SmtpClient(szHost, 587); //to authenticate we set the username and password properites on the SmtpClient // smtp.Credentials = new NetworkCredential(szAccount, szPassword); //smtp.Credentials = new NetworkCredentialByHost(); smtp.EnableSsl = true; smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.UseDefaultCredentials = false; smtp.Credentials = new NetworkCredential("*****@*****.**", "iloveB2B"); smtp.Send(mail); } catch (Exception ex) { //FormApp.Instance.logger.ErrorFormat("{0},{1}", ex.Message, ex.StackTrace); throw ex; } }
protected void btnRegister_Click(object sender, System.EventArgs e) { //Add user into list and log them in if (IsValid && Convert.ToDateTime(birthDate.Text) > DateTime.Parse("1900-01-01")) { user = (User)Session["tempUser"]; Session.Remove("tempUser"); //If user ticked register as admin box a confirmation email will be sent if (user.IsAdmin) { user.FirstName = ((TextBox)FindControl("firstName")).Text; user.LastName = ((TextBox)FindControl("lastName")).Text; user.Street = ((TextBox)FindControl("streetAddress")).Text; user.Suburb = ((TextBox)FindControl("suburb")).Text; user.Postcode = ((TextBox)FindControl("postCode")).Text; user.DOB = ((TextBox)FindControl("birthDate")).Text; user.Phone = ((TextBox)FindControl("firstName")).Text; QueryClass.AddUser(user); //Accessing gmail account to send email SmtpClient client = new SmtpClient(); client.DeliveryMethod = SmtpDeliveryMethod.Network; client.EnableSsl = true; client.Host = "smtp.gmail.com"; client.Port = 587; System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("*****@*****.**", "bhpassword"); client.UseDefaultCredentials = false; client.Credentials = credentials; MailMessage msg = new MailMessage(); msg.From = new MailAddress("*****@*****.**"); msg.To.Add(new MailAddress(user.Email)); msg.Subject = "Bobblehead - Confirm Admin Status"; //If html does not exist return non-html email msg.Body = ConfirmAdminMessage(false, user.Email, user.FirstName, user.LastName); //create an alternate HTML view that includes images and formatting string html = ConfirmAdminMessage(true, user.Email, user.FirstName, user.LastName); AlternateView view = AlternateView .CreateAlternateViewFromString( html, null, "text/html"); //Adding an image to the email string imgPath = Server.MapPath("../img/bobblebuttlogo.png"); LinkedResource img = new LinkedResource(imgPath); img.ContentId = "logoImage"; view.LinkedResources.Add(img); //add the HTML view to the message and send msg.AlternateViews.Add(view); try { client.Send(msg); //Send to main page with pop message about sent email Response.Redirect("Main?confirmAdmin="); } catch { lblRegEmail.Text = "Email could not be sent"; lblRegEmail.Visible = true; } } //If user registered as non admin no email confirmation will be sent else { user.FirstName = ((TextBox)FindControl("firstName")).Text; user.LastName = ((TextBox)FindControl("lastName")).Text; user.Street = ((TextBox)FindControl("streetAddress")).Text; user.Suburb = ((TextBox)FindControl("suburb")).Text; user.Postcode = ((TextBox)FindControl("postCode")).Text; user.DOB = ((TextBox)FindControl("birthDate")).Text; user.Phone = ((TextBox)FindControl("firstName")).Text; QueryClass.AddUser(user); Session.Add("user", user); Response.Redirect("Main"); } } }
public static bool Send(string SenderAddress, string RecipientAddress, string Subject, string Body, bool IsHtmlMessage, bool MultipleRecipient = false) { string str = "", pwd = ""; if (SenderAddress == Support) { str = SupportSender; pwd = SupportPwd; } else if (SenderAddress == Alert) { str = AlertSender; pwd = AlertPwd; } MailAddress from = new MailAddress(SenderAddress, string.Join(" - ", AppConfig.Name, str), Encoding.UTF8); MailMessage message = new MailMessage(); SmtpClient SMTP = new SmtpClient(); try { if (!MultipleRecipient) { MailAddress mailto = new MailAddress(RecipientAddress); message = new MailMessage(from, mailto); } else { message.From = from; string[] r = RecipientAddress.Split(','); for (int i = 0; i <= r.Length - 1; i++) { message.To.Add(r[i].Trim()); } } SMTP.UseDefaultCredentials = false; SMTP.Host = Host; if (UsePort) { SMTP.Port = Port; } SMTP.EnableSsl = EnableSSL; SMTP.Timeout = Timeout; SMTP.Credentials = new System.Net.NetworkCredential(SenderAddress, pwd); message.Body = Body; message.IsBodyHtml = IsHtmlMessage; message.BodyEncoding = Encoding.UTF8; message.Subject = Subject; if (!string.IsNullOrEmpty(ReplyTo)) { message.ReplyToList.Add(ReplyTo); } if (UseAsync) { SMTP.SendAsync(message, AsyncCallback); } else { SMTP.Send(message); } return(true); } catch (Exception ex) { ReturnMessage = ex.Message; } finally { message.Dispose(); } return(false); }
public string ParcelEnquiry([FromBody] ParcelEnquiry parcelEnquiry) { long parcelEnquiryId = dataManager.SaveEnquiry(parcelEnquiry); for (int i = 0; i < parcelEnquiry.AllParcels.Count(); i++) { dataManager.InsertParcels(parcelEnquiry.AllParcels[i], parcelEnquiryId); } // Send Email StringBuilder emailBody = new StringBuilder(); emailBody.Append("<strong><p>From Country</p></strong>"); emailBody.Append(parcelEnquiry.fromCountry); emailBody.Append("<br />"); emailBody.Append("<br />"); emailBody.Append("<strong><p>From Address</p></strong>"); emailBody.Append(parcelEnquiry.fromAddress); emailBody.Append("<br />"); emailBody.Append("<br />"); emailBody.Append("<strong><p>To Country</p></strong>"); emailBody.Append(parcelEnquiry.toCountry); emailBody.Append("<br />"); emailBody.Append("<br />"); emailBody.Append("<strong><p>To Address</p></strong>"); emailBody.Append(parcelEnquiry.toAddress); emailBody.Append("<br />"); emailBody.Append("<br />"); emailBody.Append("<strong><p>Contact Number</p></strong>"); emailBody.Append(parcelEnquiry.contactNumber); emailBody.Append("<br />"); emailBody.Append("<br />"); emailBody.Append("<strong><p>ParcelDescription</p></strong>"); emailBody.Append(parcelEnquiry.parcelDescription); emailBody.Append("<br />"); emailBody.Append("<br />"); emailBody.Append("<strong><p> Parcel Quantity </p></strong>"); emailBody.Append(parcelEnquiry.parcelQuantity); emailBody.Append("<br />"); emailBody.Append("<br />"); emailBody.Append("<strong><p> individal parcels </p></strong>"); for (int q = 0; q < parcelEnquiry.AllParcels.Count(); q++) { ParcelDetails parcela = parcelEnquiry.AllParcels[q]; emailBody.AppendFormat("Height:{0} ", parcela.height); emailBody.AppendFormat("Length:{0} ", parcela.length); emailBody.AppendFormat("Width:{0} ", parcela.width); emailBody.AppendFormat("Weight:{0} ", parcela.weight); emailBody.Append("<br />"); emailBody.Append("<br />"); emailBody.Append("<br />"); } MailMessage mailMessage = new MailMessage("*****@*****.**", "*****@*****.**"); mailMessage.Subject = "Booking"; mailMessage.Body = emailBody.ToString(); mailMessage.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(emailBody.ToString(), new System.Net.Mime.ContentType("text/html"))); var client = new SmtpClient("smtp.gmail.com", 587); client.Credentials = new System.Net.NetworkCredential() { //Credentials = new NetworkCredential("*****@*****.**", "Mad2behere"), //EnableSsl = true UserName = "******", Password = "******" }; try { client.EnableSsl = true; client.Send(mailMessage); } catch (Exception e) { string error = e.Message; } // client.Send("*****@*****.**", "*****@*****.**", "Booking", emailBody.ToString()); // End Send Email //return View("~/Views/Home/Booking.cshtml", new ParcelDetails()); return(JsonConvert.SerializeObject(parcelEnquiry.contactNumber)); }
public HttpResponseMessage SendPasswordByEmail(string UserName) { HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.ExpectationFailed); try { string FirstName = "", LastName = "", Email = "", Pwd = ""; GetUserInfo(UserName, ref FirstName, ref LastName, ref Email, ref Pwd); if (Email != "") { //&& user.IsActive && user.ReceiveEmail MailMessage msg = new MailMessage(); msg.To.Add(new MailAddress(Email)); string mailFrom = "*****@*****.**"; if (ConfigurationManager.AppSettings["MailFrom"] != null) { mailFrom = ConfigurationManager.AppSettings["MailFrom"].ToString(); } msg.From = new MailAddress(mailFrom); msg.Subject = "Everest: Password Information"; StringBuilder emailBody = new StringBuilder(); emailBody.Append(@"<div>"); TextInfo textInfo = new CultureInfo("en-US", false).TextInfo; string userNameForEmail = "User"; if (FirstName != "" && LastName != "") { userNameForEmail = textInfo.ToTitleCase(FirstName) + " " + textInfo.ToTitleCase(LastName); } emailBody.Append(@"Please do not reply to this system generated e-mail.<br/><br/>"); emailBody.Append(@"Dear "); emailBody.Append(userNameForEmail); emailBody.Append(@", <br /><br />"); emailBody.Append(@"Your password is: "); emailBody.Append(Pwd); emailBody.Append(@"<br/><br/>Thank you,<br/><br/>IQVIA<br/></div>"); msg.Body = emailBody.ToString(); msg.IsBodyHtml = true; SmtpClient client = new SmtpClient(); client.UseDefaultCredentials = true; // client.Credentials = new System.Net.NetworkCredential("your user name", "your password"); client.Port = 25; string mailServer = ConfigurationManager.AppSettings["MailServer"].ToString(); client.Host = mailServer; // "uacemail.rxcorp.com"; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.EnableSsl = false; client.Credentials = CredentialCache.DefaultNetworkCredentials; client.Send(msg); response = Request.CreateResponse(HttpStatusCode.OK); } } catch (Exception ex) { } return(response); }
public async Task <IActionResult> Purchase() { List <ShoppingCart> cart = SessionHelper.GetObjectFromJson <List <ShoppingCart> >(HttpContext.Session, "cart"); var id = _userManager.GetUserId(User); try { SmtpClient client = new SmtpClient(); client.Host = "smtp.gmail.com"; client.Port = 587; client.EnableSsl = true; client.UseDefaultCredentials = false; client.Credentials = new NetworkCredential("*****@*****.**", "dup@1234"); var user = await _userManager.GetUserAsync(User); var email = user.Email; MailMessage mailMessage = new MailMessage(); mailMessage.From = new MailAddress("*****@*****.**"); mailMessage.To.Add(email); mailMessage.Subject = "Your order is ready. Please pay your bill."; StringBuilder sb = new StringBuilder(); sb.AppendLine("Your order:"); foreach (var c in cart) { sb.AppendLine(_context.Events.Where(e => e.EventId == c.Ticket.EventId).FirstOrDefault().EventName + " " + c.Ticket.TicketName + " " + c.Ticket.TicketPrice + " " + c.Quantity + " " + c.Ticket.TicketPrice * c.Quantity); Purchases p = new Purchases { PurchaseTicketDate = DateTime.Now, Id = id, DeliveryId = 1, PurchaseAmount = c.Quantity, Ticket = c.Ticket }; var ticket = _context.Tickets.Where(t => t.TicketId == c.Ticket.TicketId).ToList(); foreach (var tick in ticket) { tick.TicketAvailability -= c.Quantity; } _context.Add(p); } _context.SaveChanges(); sb.AppendLine("Thanks for buying at our store"); mailMessage.Body = sb.ToString(); client.Send(mailMessage); } catch { ViewBag.ErrorMessage = "Your cart can't be empty"; return(RedirectToAction("Index", "Home")); } cart = null; SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart); return(RedirectToAction("Index", "Purchases")); }
public static string SomeMethod(string param1, string point, string setm, string pl1, string pl2, string pl3, string pl4, string winpnt, string losepnt, string tt) { String c = BilliardScoreboard.ss; Score s = new Score(); string bodd = ""; try { bodd = s.PopulateBody(param1, point, setm, pl1, pl2, pl3, pl4, winpnt, losepnt, tt); } catch { } try { try { using (MailMessage mailMessage = new MailMessage()) { String plyr1 = pl1; mailMessage.From = new MailAddress("*****@*****.**"); mailMessage.Subject = "Game Summary"; mailMessage.Body = bodd; mailMessage.IsBodyHtml = true; //{ // //Get some binary data // byte[] data = Encoding.ASCII.GetBytes(mailattatchment); // //save the data to a memory stream // System.IO.MemoryStream ms = new System.IO.MemoryStream(data); // //create the attachment from a stream. Be sure to name the data with a file and // //media type that is respective of the data // System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Html); // System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct); // attach.ContentDisposition.FileName = "test.html"; // mailMessage.Attachments.Add(attach); //} try { mailMessage.To.Add(new MailAddress(mail(pl1))); } catch { } try{ mailMessage.To.Add(new MailAddress(mail(pl2))); }catch { } try{ mailMessage.To.Add(new MailAddress(mail(pl3))); }catch { } try { mailMessage.To.Add(new MailAddress(mail(pl4))); } catch { } SmtpClient smtp = new SmtpClient("smtp.biliardoprofessionale.it", 25); smtp.EnableSsl = false; System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential("*****@*****.**", "sergio123"); smtp.Credentials = NetworkCred; smtp.Send(mailMessage); //Response.Write("E-mail sent!"); } } catch { } using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString)) { String PW1 = PW(pl1); String PW2 = PW(pl2); String PW3 = PW(pl3); String PW4 = PW(pl4); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "Update PlayerDetails set login='******' WHERE Password Collate SQL_Latin1_General_CP1_CS_AS ='" + PW1 + "'"; // cmd.CommandText = "INSERT INTO PlayerDetails (LoggedIn) VALUES (1)"; cmd.Connection = con; con.Open(); cmd.ExecuteNonQuery(); con.Close(); SqlCommand cmd1 = new SqlCommand(); cmd1.CommandType = CommandType.Text; cmd1.CommandText = "Update PlayerDetails set login='******' WHERE Password Collate SQL_Latin1_General_CP1_CS_AS ='" + PW2 + "'"; // cmd.CommandText = "INSERT INTO PlayerDetails (LoggedIn) VALUES (1)"; cmd1.Connection = con; con.Open(); cmd1.ExecuteNonQuery(); con.Close(); SqlCommand cmd2 = new SqlCommand(); cmd2.CommandType = CommandType.Text; cmd2.CommandText = "Update PlayerDetails set login='******' WHERE Password Collate SQL_Latin1_General_CP1_CS_AS ='" + PW3 + "'"; // cmd.CommandText = "INSERT INTO PlayerDetails (LoggedIn) VALUES (1)"; cmd2.Connection = con; con.Open(); cmd2.ExecuteNonQuery(); con.Close(); SqlCommand cmd3 = new SqlCommand(); cmd3.CommandType = CommandType.Text; cmd3.CommandText = "Update PlayerDetails set login='******' WHERE Password Collate SQL_Latin1_General_CP1_CS_AS ='" + PW4 + "'"; // cmd.CommandText = "INSERT INTO PlayerDetails (LoggedIn) VALUES (1)"; cmd3.Connection = con; con.Open(); cmd3.ExecuteNonQuery(); con.Close(); } } catch (System.Exception ex) { throw (ex); } String hh = PW(pl1); string m = mail(pl1) + "<br>" + "<br>" + mail(pl3); return(PW(pl1)); }
public MailSender() { this._smtpClient = new SmtpClient(); }
/// <summary> /// The SendMail method attempts to send the email. /// </summary> /// <returns>True or False /// /// Example: /// /// if Mailer.SendMail then /// /// Response.Write "Mail sent..." /// /// else /// /// Response.Write "Mail failure. Check mail host server name and tcp/ip connection..." /// /// end if</returns> public bool SendMail() { try { if (PGPPath != null) { Process p = new Process { StartInfo = { CreateNoWindow = true, FileName = PGPPath, Arguments = PGPParams } }; p.Start(); } MailMessage msg = new MailMessage(); msg.Body = BodyText; if (CustomCharSet != null) { msg.BodyEncoding = System.Text.Encoding.GetEncoding(CustomCharSet); } else { switch (CharSet) { case 1: //us ascci msg.BodyEncoding = System.Text.Encoding.ASCII; break; case 2: //iso-8859-1 msg.BodyEncoding = System.Text.Encoding.GetEncoding("iso-8859-1"); break; } } msg.IsBodyHtml = ContentType == "text/html"; if (ConfirmRead) { msg.Headers.Add("Disposition-Notification-To", "<" + FromAddress + ">"); } if (this.DateTime != null) { msg.Headers.Add("Date", this.DateTime); } if (Organization != null) { msg.Headers.Add("Organization", Organization); } msg.Sender = new MailAddress(FromAddress, FromName); msg.From = msg.Sender; foreach (var addr in recipients) { msg.To.Add(addr); } foreach (var addr in ccs) { msg.CC.Add(addr); } foreach (var addr in bccs) { msg.Bcc.Add(addr); } foreach (var filename in attachments) { Attachment data = new Attachment(filename); // Add time stamp information for the file. ContentDisposition disposition = data.ContentDisposition; disposition.CreationDate = File.GetCreationTime(filename); disposition.ModificationDate = File.GetLastWriteTime(filename); disposition.ReadDate = File.GetLastAccessTime(filename); msg.Attachments.Add(data); } foreach (var header in headers) { msg.Headers.Add(header.Split(new string[] { ": " }, StringSplitOptions.None)[0], header.Split(new string[] { ": " }, StringSplitOptions.None)[1]); } switch (Priority) { case 1: msg.Priority = MailPriority.High; break; case 3: msg.Priority = MailPriority.Normal; break; case 5: msg.Priority = MailPriority.Low; break; } if (ReplyTo != null) { msg.ReplyTo = new MailAddress(ReplyTo); } if (ReturnReceipt) { msg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.OnSuccess | DeliveryNotificationOptions.Delay; } msg.Subject = Subject; SmtpClient smtp = new SmtpClient(); smtp.Timeout = TimeOut; foreach (string server in RemoteHost.Split(';')) { if (server.IndexOf(':') != -1) { smtp.Host = server.Split(':')[0]; smtp.Port = Int32.Parse(server.Split(':')[1]); } else { smtp.Host = server; } try { smtp.Send(msg); return(true); } catch (Exception ex) { Response = ex.Message; } } } catch (Exception ex) { Response = ex.Message; } return(false); }
public string SendNewsLetter(NewsLetterModel model) { if(model.Logopath==null || model.Logopath == "") { model.Logopath = "http://pavansharma.ca//images/logo.png"; } if (model.PropertyPhoto == null || model.PropertyPhoto == "") { model.PropertyPhoto = "http://pavansharma.ca//images/img1.png"; } string Status = ""; // string EmailId = "*****@*****.**"; string msgbody = ""; var Template = ""; if(model.NewsletterType== "First_nwslettr") { Template = "Templates/FirstNewsLetter.html"; } else if(model.NewsletterType == "Second_nwslettr") { Template = "Templates/SecondNewsLetter.html"; } else if (model.NewsletterType == "Thirld_nwslettr") { Template = "Templates/ThirldNewsLetter.html"; } else if (model.NewsletterType == "Fourth_nwslettr") { Template = "Templates/FourthNewsLetter.html"; } else if (model.NewsletterType == "Fifth_nwslettr") { Template = "Templates/FifthNewLetter.html"; } else if (model.NewsletterType == "Sixth_nwslettr") { Template = "Templates/SixNewLetter.html"; } else if (model.NewsletterType == "Seventh_nwslettr") { Template = "Templates/SeventhNewsLetter.html"; } else if (model.NewsletterType == "Eighth_nwslettr") { Template = "Templates/EighthNewsLetter.html"; } else if (model.NewsletterType == "Ninth_nwslettr") { Template = "Templates/NinthNewsLetter.html"; } else if (model.NewsletterType == "Tenth_nwslettr") { Template = "Templates/TenthNewsLetter.html"; } else if (model.NewsletterType == "Eleventh_nwslettr") { Template = "Templates/EleventhNewsLetter.html"; } else if (model.NewsletterType == "Twelveth_nwslettr") { Template = "Templates/TwelvethNewsLetter.html"; } else if (model.NewsletterType == "Thirteenth_nwslettr") { Template = "Templates/ThirteenthNewsLetter.html"; } else if (model.NewsletterType == "Fourteenth_nwslettr") { Template = "Templates/FourteenthNewsLetter.html"; } else if (model.NewsletterType == "Fifteenth_nwslettr") { Template = "Templates/FifteenthNewsLetter.html"; } else if (model.NewsletterType == "Sixteenth_nwslettr") { Template = "Templates/SixteenthNewsLetter.html"; } else if (model.NewsletterType == "Seventeenth_nwslettr") { Template = "Templates/SeventeenthNewsLetter.html"; } else if (model.NewsletterType == "Eightteenth_nwslettr") { Template = "Templates/EightteenthNewsLetter.html"; } else if (model.NewsletterType == "Ninteenth_nwslettr") { Template = "Templates/NinteenthNewsLetter.html"; } else if (model.NewsletterType == "Twentieth_nwslettr") { Template = "Templates/TwentiethNewsLetter.html"; } else if (model.NewsletterType == "TwentyOne_nwslettr") { Template = "Templates/TwentyOneNewsLetter.html"; } using (StreamReader reader = new StreamReader(Path.Combine(HttpRuntime.AppDomainAppPath, Template))) { msgbody = reader.ReadToEnd(); //Replace UserName and Other variables available in body Stream msgbody = msgbody.Replace("{PropertyPhoto}", model.PropertyPhoto); msgbody = msgbody.Replace("{logopath}", model.Logopath); msgbody = msgbody.Replace("{FirstContent}", model.FirstContent); msgbody = msgbody.Replace("{SecondContent}", model.SecondContent); msgbody = msgbody.Replace("{ThirdContent}", model.ThirldContent); } //Send mail MailMessage mail = new MailMessage(); string FromEmailID = WebConfigurationManager.AppSettings["RegFromMailAddress"]; string FromEmailPassword = WebConfigurationManager.AppSettings["RegPassword"]; SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["SmtpServer"]); int _Port = Convert.ToInt32(WebConfigurationManager.AppSettings["Port"].ToString()); Boolean _UseDefaultCredentials = Convert.ToBoolean(WebConfigurationManager.AppSettings["UseDefaultCredentials"].ToString()); Boolean _EnableSsl = Convert.ToBoolean(WebConfigurationManager.AppSettings["EnableSsl"].ToString()); mail.To.Add(new MailAddress(model.Email)); mail.From = new MailAddress(FromEmailID); mail.Subject = "News Letter"; mail.BodyEncoding = System.Text.Encoding.UTF8; mail.SubjectEncoding = System.Text.Encoding.UTF8; System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(System.Text.RegularExpressions.Regex.Replace(msgbody, @"<(.|\n)*?>", string.Empty), null, "text/plain"); System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(msgbody, null, "text/html"); mail.AlternateViews.Add(plainView); mail.AlternateViews.Add(htmlView); // mail.Body = msgbody; mail.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(); smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.Host = "smtp.gmail.com"; //_Host; smtp.Port = _Port; //smtp.UseDefaultCredentials = _UseDefaultCredentials; smtp.Credentials = new System.Net.NetworkCredential(FromEmailID, FromEmailPassword);// Enter senders User name and password smtp.EnableSsl = _EnableSsl; smtp.Send(mail); return Status; }
protected void Envia_Email_Pedido() { clsPedidos objPedidos = new clsPedidos(); DataTable dtPedidos = new DataTable(); string sTexto1 = ""; int iEspaco = txtNome.Text.IndexOf(" "); if (iEspaco > 0) { sTexto1 = "Prezado (a) " + txtNome.Text.Split(' '); } else { sTexto1 = "Prezado (a) " + txtNome.Text; } string sTexto2 = "Recebemos seu pedido número :" + Session["PEDIDO"]; string sTexto3 = "Composto pelos seguintes itens: "; string sTexto4 = "Obrigado por comprar na FARMAFIPP "; string sTexto5 = "Em caso de dúvida entre em contato com nossa central de atendimento."; string sTexto6 = "Atenciosamente"; string sTexto7 = "Departamento Comercial - FARMAFIPP"; string sTexto8 = ""; string sTotalPedido = Convert.ToString(objPedidos.TotalizaPedido()); sTexto8 = "<table border=2 width=500px>" + " <tr> " + "<td width=50%> Descrição</td>" + "<td width=20%> Quantidade</td>" + "<td width=30%> Valor</td>" + "</tr> "; dtPedidos = objPedidos.RecuperarDados(Session["PEDIDO"].ToString()); if (dtPedidos.Rows.Count > 0) { int i = 0; while (dtPedidos.Rows.Count > i) { sTexto8 = sTexto8 + "<tr>" + "<td width=50%> " + dtPedidos.Rows[i]["DESCRICAO"].ToString() + "</td>" + "<td width=20%> " + dtPedidos.Rows[i]["QUANTIDADE"].ToString() + "</td>" + "<td width=30%> " + String.Format("{0:c}", dtPedidos.Rows[i]["PRECOTOTAL"]) + "</td>" + "</tr>"; i++; } } sTexto8 = sTexto8 + "</table>"; dtPedidos.Dispose(); string sMensagem = sTexto1 + "<br> " + sTexto2 + "<br>" + sTexto3 + "<br>" + sTexto8 + "<br>" + sTexto4 + "<br>" + sTexto6 + "<br>" + sTexto7 + "<br>"; SmtpClient email = new SmtpClient("mail.unoeste.br"); try { MailMessage msg = new MailMessage(); MailAddress remetente = new MailAddress("*****@*****.**", "FarmaFIPP Medicamentos Ltda"); msg.From = remetente; msg.Subject = "Pedido número :" + Session["NUMPEDIDO"]; msg.Body = sMensagem; msg.IsBodyHtml = true; msg.To.Add("*****@*****.**"); email.Send(msg); objClientes.MostraMensagem("E-mail enviado com sucesso!!!", Page); } catch { objClientes.MostraMensagem("Problemas no envio do e-mail!!!", Page); } }
public virtual void Sell(UserAccountInfo buyerUser) { if (buyerUser != null) { NetworkCredential login = new NetworkCredential("*****@*****.**", "Veka1999"); SmtpClient client = new SmtpClient() { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, UseDefaultCredentials = false, DeliveryMethod = SmtpDeliveryMethod.Network, Credentials = login }; MailMessage buyerMail = new MailMessage(new MailAddress("*****@*****.**", "BestLot", Encoding.UTF8), new MailAddress(buyerUser.Email)) { Subject = "BestLot.com", Body = "Dear " + buyerUser.Name + " " + buyerUser.Surname + "\n" + "Your bet was highest and now you can buy lot \"" + Name + "\" for " + Price + "\n" + "Please, contact seller on his email or telephone\n" + "Email: " + SellerUser.Email + "\n" + "Telephone: " + SellerUser.TelephoneNumber + "\n\n" + "Best regards, BestLot team", BodyEncoding = UTF8Encoding.UTF8, DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure }; client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback); client.Send(buyerMail); MailMessage sellerMail = new MailMessage(new MailAddress("*****@*****.**", "BestLot", Encoding.UTF8), new MailAddress(SellerUser.Email)) { Subject = "BestLot.com", Body = "Dear " + SellerUser.Name + " " + SellerUser.Surname + ",\n" + "Your lot \"" + Name + "\" was sold to " + buyerUser.Name + " " + buyerUser.Surname + " for " + Price + "\n" + "Please, contact buyer on his email or telephone\n" + "Email: " + buyerUser.Email + "\n" + "Telephone: " + buyerUser.TelephoneNumber + "\n\n" + "Best regards, BestLot team", BodyEncoding = UTF8Encoding.UTF8, DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure }; client.Send(sellerMail); } else { NetworkCredential login = new NetworkCredential("*****@*****.**", "Veka1999"); SmtpClient client = new SmtpClient() { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, UseDefaultCredentials = false, DeliveryMethod = SmtpDeliveryMethod.Network, Credentials = login }; MailMessage sellerMail = new MailMessage(new MailAddress("*****@*****.**", "BestLot", Encoding.UTF8), new MailAddress(SellerUser.Email)) { Subject = "BestLot.com", Body = "Dear " + SellerUser.Name + " " + SellerUser.Surname + ",\n" + "We tried to sell your lot \"" + Name + "\" but no bids were placed\n" + "Lot " + Name + " was moved to archive, so feel free to add same lot and sell it again\n\n" + "Best regards, BestLot team", BodyEncoding = UTF8Encoding.UTF8, DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure }; client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback); client.Send(sellerMail); } }
public bool SendV2(string para, string copia, string copiaOculta, string de, string displayName, string asunto, string html, string HostServer, int Puerto, bool EnableSSL, string UserName, string Password, List <Object[]> ArchivosAdjuntos = null) { try { MailMessage mail = new MailMessage(); mail.Subject = asunto; mail.Body = html; mail.IsBodyHtml = true; // * mail.From = new MailAddress(WebConfigurationManager.AppSettings["UserName"], displayName); mail.From = new MailAddress(de, displayName); var paraList = para.Split(';'); foreach (var p in paraList) { if (p.Trim().Length > 0) { mail.To.Add(p.Trim()); } } var ccList = copia.Split(';'); foreach (var cc in ccList) { if (cc.Trim().Length > 0) { mail.CC.Add(cc.Trim()); } } var ccoList = copiaOculta.Split(';'); foreach (var cco in ccoList) { if (cco.Trim().Length > 0) { mail.Bcc.Add(cco.Trim()); } } if (ArchivosAdjuntos != null) { foreach (var archivo in ArchivosAdjuntos) { // if (!string.IsNullOrEmpty(archivo)) mail.Attachments.Add(new Attachment((Stream)archivo[0], archivo[1].ToString())); } } //if (ArchivosAdjuntos != null) //{ // foreach (var archivo in ArchivosAdjuntos) // { // //if (!string.IsNullOrEmpty(archivo)) // System.Net.Mail.Attachment Data = new System.Net.Mail.Attachment(archivo); // mail.Attachments.Add(Data); // } //} SmtpClient client = new SmtpClient(); client.Host = HostServer; // WebConfigurationManager.AppSettings["HostName"]; client.Port = Puerto; // int.Parse(WebConfigurationManager.AppSettings["Port"].ToString()); client.UseDefaultCredentials = false; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.EnableSsl = EnableSSL; // bool.Parse(WebConfigurationManager.AppSettings["EnableSsl"]); client.Credentials = new NetworkCredential(UserName, Password); client.Send(mail); client.Dispose(); mail.Dispose(); return(true); } catch (Exception ex) { return(false); } }
private async void AgregarButton_Clicked(object sender, EventArgs e) { if (string.IsNullOrEmpty(nombresEntry.Text)) { await DisplayAlert("Error", "Debe ingresar nombres", "Aceptar"); nombresEntry.Focus(); return; } if (string.IsNullOrEmpty(apellidosEntry.Text)) { await DisplayAlert("Error", "Debe ingresar apellidos", "Aceptar"); apellidosEntry.Focus(); return; } //COMPROBACIÓN DEL EMAIL if (string.IsNullOrEmpty(emailEntry.Text)) { await DisplayAlert("Error", "Debe ingresar un email", "Aceptar"); emailEntry.Focus(); return; } var email = emailEntry.Text; var nombre = nombresEntry.Text; var emailPattern = "^([\\w\\.\\-]+)@([\\w\\-]+)((\\.(\\w){2,3})+)$"; if (!String.IsNullOrWhiteSpace(email) && !(Regex.IsMatch(email, emailPattern))) { await DisplayAlert("Error", "Debe ingresar un email válido", "Aceptar"); emailEntry.Focus(); return; } else { var fromAddress = new MailAddress("*****@*****.**", "KAPTA"); var toAddress = new MailAddress(email, nombre); const string fromPassword = "******"; const string subject = "EQUIPO KAPTA"; const string body = "¡Gracias por usar nuestra aplicación!"; var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, Credentials = new NetworkCredential(fromAddress.Address, fromPassword), Timeout = 20000 }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = "Hola " + nombresEntry.Text + " ¡Te acabas de dar de alta como deportista en KAPTA! Para más información visita nuestra App", }) { smtp.Send(message); } /* * if (string.IsNullOrEmpty(salarioEntry.Text)) * { * await DisplayAlert("Error", "Debe ingresar salario", "Aceptar"); * salarioEntry.Focus(); * return; * } */ } //creamos el deportista var deportista = new Deportista { Nombres = nombresEntry.Text, Apellidos = apellidosEntry.Text, Email = emailEntry.Text, FechaNacimiento = fechaContratoDatePicker.Date, IdUser = MainViewModel.GetInstance().UserASP.Email, // Salario = decimal.Parse(salarioEntry.Text), // Activo = activoSwitch.IsToggled }; //insertamos el deportista en la base de datos using (var datos = new DataAccess()) { datos.InsertDeportista(deportista); //listaListView.ItemsSource = datos.GetDeportistas(); } nombresEntry.Text = string.Empty; apellidosEntry.Text = string.Empty; emailEntry.Text = string.Empty; // salarioEntry.Text = string.Empty; fechaContratoDatePicker.Date = DateTime.Now; //activoSwitch.IsToggled = true; DependencyService.Get <IMessage>().LongAlert("Deportista agregado"); //await DisplayAlert("Confirmación", "Deportista agregado", "Aceptar"); // await Navigation.PushAsync(new Trabajo.HomePage()); }
private void SendVerificationEmail(MembershipModel model, int memberId) { try { //Create Url Links var urlHome = Umbraco.TypedContent((int)Common.siteNode.Home).UrlAbsolute(); var urlCreateAcct = Umbraco.TypedContent((int)Common.siteNode.Login).UrlAbsolute() + "?" + Common.miscellaneous.Validate + "=" + memberId.ToString("X"); // Obtain smtp string smtpHost = System.Configuration.ConfigurationManager.AppSettings["smtpHost"].ToString(); string smtpPort = System.Configuration.ConfigurationManager.AppSettings["smtpPort"].ToString(); string smtpUsername = System.Configuration.ConfigurationManager.AppSettings["smtpUsername"].ToString(); string smtpPassword = System.Configuration.ConfigurationManager.AppSettings["smtpPassword"].ToString(); //Create a new smtp client SmtpClient smtp = new SmtpClient(smtpHost, Convert.ToInt32(smtpPort)) { Credentials = new NetworkCredential(smtpUsername, smtpPassword) }; // set the content by openning the files. string filePath_html = HostingEnvironment.MapPath("~/Emails/VerifyAccount/VerifyAcct.html"); string filePath_Text = HostingEnvironment.MapPath("~/Emails/VerifyAccount/VerifyAcct.txt"); string emailBody_Html_original = System.IO.File.ReadAllText(filePath_html); string emailBody_Text_original = System.IO.File.ReadAllText(filePath_Text); // Create new version of files string emailBody_Html = emailBody_Html_original; string emailBody_Text = emailBody_Text_original; // Insert data into page emailBody_Html = emailBody_Html.Replace("[LINK]", urlCreateAcct); emailBody_Text = emailBody_Text.Replace("[LINK]", urlCreateAcct); emailBody_Html = emailBody_Html.Replace("[YEAR]", DateTime.Today.Year.ToString()); emailBody_Text = emailBody_Text.Replace("[YEAR]", DateTime.Today.Year.ToString()); emailBody_Html = emailBody_Html.Replace("[AFTERTHEWARNING_URL]", urlHome); emailBody_Text = emailBody_Text.Replace("[AFTERTHEWARNING_URL]", urlHome); emailBody_Html = emailBody_Html.Replace("[5THSTUDIOS_URL]", "http://5thstudios.com"); emailBody_Text = emailBody_Text.Replace("[5THSTUDIOS_URL]", "http://5thstudios.com"); // Create mail message MailMessage Msg = new MailMessage() { From = new MailAddress(smtpUsername) }; Msg.To.Add(new MailAddress(model.Email)); // Set email parameters Msg.BodyEncoding = Encoding.UTF8; Msg.SubjectEncoding = Encoding.UTF8; Msg.Subject = "Account Verification | After the Warning"; Msg.IsBodyHtml = true; Msg.Body = ""; AlternateView alternateHtml = AlternateView.CreateAlternateViewFromString(emailBody_Html, new System.Net.Mime.ContentType(MediaTypeNames.Text.Html)); AlternateView alternateText = AlternateView.CreateAlternateViewFromString(emailBody_Text, new System.Net.Mime.ContentType(MediaTypeNames.Text.Plain)); Msg.AlternateViews.Add(alternateText); Msg.AlternateViews.Add(alternateHtml); // Send email smtp.Send(Msg); } catch (Exception ex) { //Save error message to umbraco StringBuilder sb = new StringBuilder(); sb.AppendLine(@"MembershipController.cs : SendVerificationEmail()"); sb.AppendLine("model:" + Newtonsoft.Json.JsonConvert.SerializeObject(model)); Common.SaveErrorMessage(ex, sb, typeof(MembershipController)); } }
public ActionResult SendEnquiry(FormCollection form) { string userid = Session["userid"].ToString(); if (userid != null) { int customerCount = ags.vendor_table.Where(x => x.id.ToString() == userid).Count(); if (customerCount != 0) { string customerName = ""; string customerEmail = ""; string customerPhone = ""; string customerMessage = ""; if (form["vendorName"] != null) { customerName = form["vendorName"].ToString(); } else { customerName = "Not Updated"; } if (form["vendorEmail"] != null) { customerEmail = form["vendorEmail"].ToString(); } else { customerEmail = "Not Updated"; } if (form["vendorPhone"] != null) { customerPhone = form["vendorPhone"].ToString(); } else { customerPhone = "Not Updated"; } if (form["vendorMessage"] != null) { customerMessage = form["vendorMessage"].ToString(); } else { customerMessage = "Not Updated"; } //string CusEmail = "*****@*****.**"; //string CusEmail = "*****@*****.**"; string CusEmail = "*****@*****.**"; ////////////////////////////////// MailMessage MyMailMessage = new MailMessage(); MyMailMessage.From = new MailAddress("*****@*****.**"); MyMailMessage.To.Add(CusEmail); MyMailMessage.Subject = "AGSKEYS - Enquiry From Vendor"; MyMailMessage.IsBodyHtml = true; MyMailMessage.Body = "<div style='font-family:Arial; font-size:16px; font-color:#d92027 '>Agskeys having New Customer Enquiry Details.</div><br><table border='0' ><tr><td style='padding:25px;'>Name</td><td>" + customerName + "</td></tr><tr><td style='padding:25px;'>Email</td><td>" + customerEmail + "</td></tr><tr><td style='padding:25px;'>Phone</td><td>" + customerPhone + "</td></tr><tr><td style='padding:25px;'>Message</td><td>" + customerMessage + "</td></tr></table>"; SmtpClient SMTPServer = new SmtpClient("smtp.gmail.com"); SMTPServer.Port = 587; SMTPServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "auxin12345"); SMTPServer.EnableSsl = true; try { SMTPServer.Send(MyMailMessage); TempData["customerSuccessMsg"] = "Your New Enquiry Successfully send to AGSKEYS"; return(RedirectToAction("Enquiry", "MobileVendor")); } catch (Exception ex) { TempData["customerFailedMsg"] = ex.Message; TempData["customerFailedMsg"] += "Oops.! Somethig Went Wrong."; return(RedirectToAction("Enquiry", "MobileVendor")); } } } return(RedirectToAction("Index", "MobileVendor")); }
public async Task <IActionResult> OnPostAsync(string stripeEmail, string stripeToken, int?id) { shoe = await _context.Shoe.FirstOrDefaultAsync(m => m.ShoeID == id); if (shoe == null) { return(NotFound()); } var customers = new CustomerService(); var charges = new ChargeService(); try { var customer = customers.Create(new CustomerCreateOptions { Email = stripeEmail, Source = stripeToken }); var charge = charges.Create(new ChargeCreateOptions { Amount = Convert.ToInt64(shoe.Price) * 100, //Need to change the amount to shopping cart page Description = shoe.Name, Currency = "sgd", Customer = customer.Id, ReceiptEmail = stripeEmail // Send email receipt to customer }); if (charge.Status == "succeeded") { var user = await _userManager.GetUserAsync(User); Bought QueryBought = new Bought { Id = user.Id, ShoeID = shoe.ShoeID }; var bought = await _context.bought.FirstOrDefaultAsync(m => m.Id == QueryBought.Id && m.ShoeID == QueryBought.ShoeID); if (bought == null) { _context.bought.Add(QueryBought); await _context.SaveChangesAsync(); } string receipturl = charge.ReceiptUrl; string subject = "Cinderella Order Confirmation"; string To = charge.ReceiptEmail; string Body = string.Format("Thanks for shopping with Cinderella \nTransaction No. :{0}\nAmount paid: ${1}\nYour order for {2} will be shipped to you shortly. Alternatively, you may view your e-receipt at {3}.", charge.Id, charge.Amount / 100, shoe.Name, receipturl); MailMessage mail = new MailMessage(); mail.To.Add(To); mail.Subject = subject; mail.Body = Body; mail.IsBodyHtml = false; mail.From = new MailAddress("*****@*****.**"); SmtpClient smtp = new SmtpClient("smtp.gmail.com") { Port = 587, UseDefaultCredentials = true, EnableSsl = true, //use SSL to secure connection Credentials = new System.Net.NetworkCredential("*****@*****.**", "Cinderella123!") }; await smtp.SendMailAsync(mail); if (charge.ReceiptEmail != user.Email) { string nsubject = "Cinderella Order Confirmation"; string nTo = user.Email; string nBody = string.Format("An order for {0} was made from your account\nIf this is not you, please contact us immediately", shoe.Name); MailMessage nmail = new MailMessage(); nmail.To.Add(nTo); nmail.Subject = nsubject; nmail.Body = nBody; nmail.IsBodyHtml = false; nmail.From = new MailAddress("*****@*****.**"); await smtp.SendMailAsync(nmail); } TransactionLog log = new TransactionLog { Id = user.Id, TransactionNumber = charge.Id, Time = DateTime.Now }; _context.TransactionLogs.Add(log); await _context.SaveChangesAsync(); return(RedirectToPage("./Success_Page")); } else { //should make this display the error, like 'insufficient funds' or smth return(RedirectToPage("./Fail_Transaction")); } } catch { return(RedirectToPage("./Fail_Transaction")); } }
protected void Page_Load(object sender, EventArgs e) { try { if (Session["loginVal"].ToString() == "*****@*****.**") { currtst = "€"; } else { currtst = "INR"; } // Generate booking reference number for agent, to find their bookings details.This number is unique for every agent......... string AvailableCash = Session["AvlCash"].ToString(); string bookingref = Session["bookingRef"].ToString(); //Session["bookingRef"] = bookingref; // Complete booking details string....... string BookData = Session["BookData"].ToString().Replace("(HASH)", "#"); string CustomerDetails = BookData.Split('$')[1]; string totpassanger = (CustomerDetails.Split('/')[0].Split(',').Length - 1).ToString(); string agentdetails = CF.CommonFunction.agencydetails(Session["loginVal"].ToString()); string cat = Session["Category"].ToString(); //ftresp //using (var client = new WebClient()) //{ // //string result = client.DownloadString("https://ftcash.com/websdkresponse/responsem.php"); if (Session["HoldBooking"].ToString() == "No") { try { NameValueCollection nvc = Request.Form; if (!string.IsNullOrEmpty(nvc["orderid"])) { ftorderid = nvc["orderid"]; } if (!string.IsNullOrEmpty(nvc["responseDescription"])) { ftresponseDescription = nvc["responseDescription"]; } if (!string.IsNullOrEmpty(nvc["checksum"])) { ftchecksum = nvc["checksum"]; } if (!string.IsNullOrEmpty(nvc["responseCode"])) { ftresponseCode = nvc["responseCode"]; } if (!string.IsNullOrEmpty(nvc["amount"])) { ftamount = nvc["amount"]; } if (!string.IsNullOrEmpty(nvc["mid"])) { ftmid = nvc["mid"]; } if (!string.IsNullOrEmpty(nvc["referenceNumber"])) { ftreferenceNumber = nvc["referenceNumber"]; } string ServerPath = Server.MapPath("~\\FtCash"); string DataFile = bookingref + ".txt"; FileStream fs = new FileStream(ServerPath + "/" + DataFile, FileMode.Create, FileAccess.Write); StreamWriter fp = new StreamWriter(fs, Encoding.UTF8); try { fp.WriteLine(nvc); } catch (Exception Ex) { } finally { fp.Close(); fp = null; } } catch (Exception ex) { string ServerPath = Server.MapPath("ErrorLogs"); string DataFile1 = "BookAfterPayment" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt"; FileStream fs1 = new FileStream(ServerPath + "/" + DataFile1, FileMode.Create, FileAccess.Write); StreamWriter fp1 = new StreamWriter(fs1, Encoding.UTF8); try { fp1.WriteLine(ex.Message.ToString()); } catch (Exception Ex) { } finally { fp1.Close(); fp1 = null; } } } string bookingdetail = BookData + "$" + agentdetails; cls.CommonClass obj = new cls.CommonClass(); string supplier = BookData.Split('$')[0].Split('!')[5]; string bookingresponse = string.Empty; string price = BookData.Split('$')[0].Split('!')[15]; try { if (ftresponseCode == "1") { Response.Redirect("Bankissue.aspx?"); } } catch (Exception ex) { } string ExtraInfo1 = ""; if (BookData.Split('$')[0].Split('!')[5].ToUpper() == "HOTELBEDS") { string[] arr = BookData.Split('$')[0].Split('!'); string response = "", cancellationcharge = ""; string policydet = arr[16] + "$" + arr[11] + "$" + arr[14] + "$" + arr[5] + "$" + arr[7]; cls.CommonClass plcy = new cls.CommonClass(); response = plcy.GetCancelPolicy(BookData.Split('$')[2], policydet, "HOTELBEDS", cat); string deadln = ""; try { if (!string.IsNullOrEmpty(response)) //Parsing cancellation policy....... { XmlDocument doc = CF.CommonFunction.JSONtoXML(response); XmlNodeList cnlplcy = doc.GetElementsByTagName("Cancellationpolicies"); foreach (XmlNode rootnode in cnlplcy) { foreach (XmlNode chnode in rootnode) { cancellationcharge = chnode["Cancellationcharge"].InnerText; ExtraInfo1 = chnode["ExtraInfo1"].InnerText; } } } else { cancellationcharge = "No Cancellation Policy Found. Deadline: " + DateTime.Now.ToString("yyyy-MM-dd"); } // End region of cancellation policy ............... string[] policy = Regex.Split(cancellationcharge, "Deadline: "); string sql1 = "Insert into cancellationPolicy(BookingRef,Policy,Deadline) values("; if (policy.Length > 1) { DateTime daedline = DateTime.ParseExact(policy[1], "dd-MM-yyyy", CultureInfo.InvariantCulture); sql1 += "'" + bookingref + "','" + policy[0] + "','" + daedline.ToString("yyyy-MM-dd") + "')"; deadln = daedline.ToString("yyyy-MM-dd"); } else { sql1 += "'" + bookingref + "','" + policy[0] + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "')"; deadln = DateTime.Now.ToString("yyyy-MM-dd"); } try { DB.CommonDatabase.RunQuery(sql1); } catch (Exception) { cls.CommonClass objnew = new cls.CommonClass(); objnew.LogFailedQuery(sql1, "cancellationPolicy_" + supplier); } } catch (Exception ex) { string ServerPath = Server.MapPath("ErrorLogs"); string DataFile1 = "BookAfterPayment" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt"; FileStream fs1 = new FileStream(ServerPath + "/" + DataFile1, FileMode.Create, FileAccess.Write); StreamWriter fp1 = new StreamWriter(fs1, Encoding.UTF8); try { fp1.WriteLine(ex.Message.ToString()); } catch (Exception Ex) { } finally { fp1.Close(); fp1 = null; } } } //End calling cancellation policy........ //Start Calling booking method supplier wise.... string status = ""; string bookingId = ""; try { if (supplier.ToUpper() == "TBO") { bookingresponse = obj.GetHotelBooking(bookingdetail, CustomerDetails, price, totpassanger, supplier); } if (supplier.ToUpper() == "DOTW") { bookingresponse = obj.GetHotelBooking(bookingdetail, price, totpassanger, bookingref, supplier); } else if (supplier.ToUpper() == "DESIYA") { bookingresponse = obj.GetHotelBooking(bookingdetail, price, totpassanger, bookingref, supplier); } else if (supplier.ToUpper() == "TRAVELBULLZ") { bookingresponse = obj.GetHotelBooking(bookingdetail, price, totpassanger, bookingref, supplier); } else if (supplier.ToUpper() == "EZEEGO1") { bookingresponse = obj.GetHotelBooking(bookingdetail, price, totpassanger + "," + Session["EzeeGoId"].ToString(), bookingref, supplier); } else if (supplier.ToUpper() == "ABREU") { bookingresponse = obj.GetHotelBooking(bookingdetail, price, totpassanger, bookingref, supplier); } else if (supplier.ToUpper() == "HOTELBEDS") { bookingresponse = obj.GetHotelBooking(bookingdetail, price, totpassanger + "^" + ExtraInfo1, bookingref, supplier); } else if (supplier.ToUpper() == "TRAVSTARZ") { string id = CF.CommonFunction.NewNumber12(); bookingresponse = obj.GetHotelBooking(bookingdetail, price, totpassanger + "`" + id, bookingref, supplier); } else if (supplier.ToUpper() == "QUANTUM") { bookingresponse = obj.GetHotelBooking(bookingdetail, price, totpassanger + "^" + ExtraInfo1, bookingref, supplier); } else if (supplier.ToUpper() == "JACTRAVEL") { bookingresponse = obj.GetHotelBooking(bookingdetail, price, totpassanger + "," + Session["PreBookingToken"].ToString(), bookingref, supplier); } if (supplier.ToUpper() == "DESIYA") { if (bookingresponse.Contains('{') || bookingresponse == "") { } else { Session["bookingdetail"] = bookingdetail; Response.Redirect("pricechange.aspx?oldprice=" + BookData.Split('$')[0].Split('!')[15] + "$" + bookingresponse); } } if (!string.IsNullOrEmpty(bookingresponse)) // Booking Details parsing....... { XmlDocument doc = CF.CommonFunction.JSONtoXML(bookingresponse); XmlNodeList hotelres = doc.GetElementsByTagName("Booking"); foreach (XmlNode hnode in hotelres) { foreach (XmlNode chnode in hnode) { bookingId = chnode["booking_id"].InnerText; status = chnode["confirmation"].InnerText; if (bookingId != "" && status == "") { status = "Confirmed"; } } } } } catch (Exception ex) { string ServerPath = Server.MapPath("ErrorLogs"); string DataFile1 = "BookAfterPayment" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt"; FileStream fs1 = new FileStream(ServerPath + "/" + DataFile1, FileMode.Create, FileAccess.Write); StreamWriter fp1 = new StreamWriter(fs1, Encoding.UTF8); try { fp1.WriteLine(ex.Message.ToString()); } catch (Exception Ex) { } finally { fp1.Close(); fp1 = null; } } //End ............. if (Session["HoldBooking"].ToString() == "Yes") { status = "Hold"; } string sql = ""; string title = ""; string firstname = ""; string lastname = ""; string passport = ""; string GN = ""; for (int i = 0; i < Convert.ToInt16(totpassanger); i++) { title = CustomerDetails.Split('/')[0].Split(',')[i]; firstname = CustomerDetails.Split('/')[1].Split(',')[i]; lastname = CustomerDetails.Split('/')[2].Split(',')[i]; passport = CustomerDetails.Split('/')[3].Split(',')[i]; GN = CustomerDetails.Split('/')[4].Split(',')[i]; sql = "Insert into CustomerDetails(BookingRef, Title, Firstname, Lastname, BookingDate, Passport, GuestNationality) values('" + bookingref + "','" + title + "','" + firstname + "','" + lastname + "','" + DateTime.Now + "','" + passport + "','" + GN + "')"; try { DB.CommonDatabase.RunQuery(sql); } catch (Exception) { cls.CommonClass objnew = new cls.CommonClass(); objnew.LogFailedQuery(sql, "CustomerDetails_" + supplier); } } if (bookingId != "") { // Calling method of cancellation policy.......... string[] arr = BookData.Split('$')[0].Split('!'); string response = ""; string cancellationcharge = ""; if (arr[5].ToUpper() == "TBO") { string policydet = arr[16] + "$" + arr[11]; cls.CommonClass plcy = new cls.CommonClass(); response = plcy.GetCancelPolicy(policydet, "", "TBO", cat); } else if (arr[5].ToUpper() == "DOTW") { string policydet = "$" + arr[11] + "$" + arr[14] + "$" + arr[5] + "$"; cls.CommonClass plcy = new cls.CommonClass(); response = plcy.GetCancelPolicy(BookData.Split('$')[2], policydet, "DOTW", cat); } else if (arr[5].ToUpper() == "TRAVELBULLZ") { string policydet = arr[16] + "$" + arr[11] + "$" + arr[14] + "$" + arr[5] + "$" + arr[7] + "~"; cls.CommonClass plcy = new cls.CommonClass(); response = obj.GetCancelPolicy(BookData.Split('$')[2], policydet, "TRAVELBULLZ", cat); } else if (arr[5].ToUpper() == "DESIYA") { string policydet = arr[16] + "$" + arr[11] + "$" + arr[17].Split('*')[1] + "$" + arr[13]; cls.CommonClass plcy = new cls.CommonClass(); response = plcy.GetCancelPolicy(BookData.Split('$')[2], policydet, "DESIYA", cat); } else if (arr[5].ToUpper() == "EZEEGO1") { string policydet = arr[16] + "$" + arr[11] + "$" + arr[8] + "$" + arr[13] + "$" + arr[7]; cls.CommonClass plcy = new cls.CommonClass(); response = plcy.GetCancelPolicy(BookData.Split('$')[2], policydet, "EZEEGO1", cat); } else if (arr[5].ToUpper() == "ABREU") { string policydet = arr[16] + "$" + arr[11] + "$" + arr[8] + "$" + arr[13] + "$" + arr[7] + "$" + arr[17].TrimEnd('%'); cls.CommonClass plcy = new cls.CommonClass(); response = plcy.GetCancelPolicy(BookData.Split('$')[2], policydet, "ABREU", "INR"); } else if (arr[5].ToUpper() == "HOTELBEDS") { string policydet = arr[16] + "$" + arr[11] + "$" + arr[8] + "$" + arr[13] + "$" + arr[7]; cls.CommonClass plcy = new cls.CommonClass(); response = plcy.GetCancelPolicy(BookData.Split('$')[2], policydet, "HOTELBEDS", cat); } else if (arr[5].ToUpper() == "QUANTUM") { string policydet = arr[16] + "$" + arr[11] + "$" + arr[8] + "$" + arr[13] + "$" + arr[7]; cls.CommonClass plcy = new cls.CommonClass(); response = plcy.GetCancelPolicy(BookData.Split('$')[2], policydet, "QUANTUM", cat); } else if (arr[5].ToUpper() == "JACTRAVEL") { string policydet = arr[16] + "$" + arr[11] + "$" + arr[14] + "$" + arr[5] + "$" + arr[7] + "$" + BookData.Split('$')[0]; cls.CommonClass plcy = new cls.CommonClass(); response = obj.GetCancelPolicy(BookData.Split('$')[2], policydet, "JACTRAVEL", "INR"); } else if (arr[5].ToUpper() == "TRAVSTARZ") { //DateTime dt1 = DateTime.ParseExact(searchparam.Split('^')[0], "dd MMM yyyy", CultureInfo.InvariantCulture); //DateTime dt2 = DateTime.ParseExact(searchparam.Split('^')[1], "dd MMM yyyy", CultureInfo.InvariantCulture); //string formatfromdDate = dt1.ToString("yyyy-MM-dd"); //string formattodDate = dt2.ToString("yyyy-MM-dd"); //string htlid = bookdet.Split('!')[7]; //string rmtype = bookdet.Split('!')[12]; //cls.CommonClass plcy = new cls.CommonClass(); //for (int r = 0; r < rmtype.Split('~').Length; r++) //{ // response += plcy.GetCancelPolicy(htlid, rmtype.Split('~')[r], formatfromdDate, formattodDate); //} //policydet = "$"+arr[11] + "$" + arr[14] + "$" + arr[13] + "$" + arr[7]; //response = obj.GetCancelPolicy(searchparam, policydet, "TRAVSTARZ", cat); // response = bookdet.Split('*')[1];//.Split('~')[0]; } string deadln = ""; try { if (!string.IsNullOrEmpty(response)) //Parsing cancellation policy....... { XmlDocument doc = CF.CommonFunction.JSONtoXML(response); XmlNodeList cnlplcy = doc.GetElementsByTagName("Cancellationpolicies"); foreach (XmlNode rootnode in cnlplcy) { foreach (XmlNode chnode in rootnode) { cancellationcharge = chnode["Cancellationcharge"].InnerText.Replace("'", ""); } } } else { cancellationcharge = "No Cancellation Policy Found. Deadline: " + DateTime.Now.ToString("yyyy-MM-dd"); } // End region of cancellation policy ............... string[] policy = Regex.Split(cancellationcharge, "Deadline: "); sql = "Insert into cancellationPolicy(BookingRef,Policy,Deadline) values("; if (supplier.ToUpper() == "EZEEGO1" || supplier.ToUpper() == "DESIYA") { if (policy.Length > 1) { DateTime daedline = DateTime.Parse(policy[1]); sql += "'" + bookingref + "','" + policy[0] + "','" + daedline.ToString("yyyy-MM-dd") + "')"; deadln = daedline.ToString("yyyy-MM-dd"); } else { sql += "'" + bookingref + "','" + policy[0] + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "')"; deadln = DateTime.Now.ToString("yyyy-MM-dd"); } } else { if (policy.Length > 1) { DateTime daedline; if (supplier == "JACTRAVEL") { daedline = Convert.ToDateTime(policy[1].Split('T')[0]); } else { daedline = DateTime.ParseExact(policy[1], "dd-MM-yyyy", CultureInfo.InvariantCulture); } sql += "'" + bookingref + "','" + policy[0] + "','" + daedline.ToString("yyyy-MM-dd") + "')"; deadln = daedline.ToString("yyyy-MM-dd"); } else { sql += "'" + bookingref + "','" + policy[0] + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "')"; deadln = DateTime.Now.ToString("yyyy-MM-dd"); } } try { DB.CommonDatabase.RunQuery(sql); } catch (Exception) { cls.CommonClass objnew = new cls.CommonClass(); objnew.LogFailedQuery(sql, "cancellationPolicy_" + supplier); } } catch (Exception ex) { string ServerPath = Server.MapPath("ErrorLogs"); string DataFile1 = "BookAfterPayment" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt"; FileStream fs1 = new FileStream(ServerPath + "/" + DataFile1, FileMode.Create, FileAccess.Write); StreamWriter fp1 = new StreamWriter(fs1, Encoding.UTF8); try { fp1.WriteLine(ex.Message.ToString()); } catch (Exception Ex) { } finally { fp1.Close(); fp1 = null; } } string HotelName = BookData.Split('$')[0].Split('!')[0]; string chkin = BookData.Split('$')[2].Split('^')[0]; string chkout = BookData.Split('$')[2].Split('^')[1]; string pno = BookData.Split('$')[1].Split('|')[1]; string loginval = Session["loginVal"].ToString(); string emailid = loginval.Split('^')[0]; string address = BookData.Split('$')[0].Split('!')[9]; string ddl = ""; try { ddl = Convert.ToDateTime(deadln).ToString("yyyy-MM-dd"); } catch (Exception) { ddl = ""; } try { sql = "Insert into HotelBookingDetails(BookingReference, BookingId, BkDetails, EmailID, BookingDate, Status, Supplier, CheckIn, CheckOut, HotelName, PhoneNo, Address, Deadline) values("; sql += "'" + bookingref + "',"; sql += "'" + bookingId + "',"; sql += "'" + bookingdetail + "',"; sql += "'" + emailid + "',"; sql += "'" + DateTime.Now.ToString("dd-MM-yyyy") + "',"; sql += "'" + status + "',"; sql += "'" + supplier + "',"; sql += "'" + Convert.ToDateTime(chkin).ToString("yyyy-MM-dd") + "',"; sql += "'" + Convert.ToDateTime(chkout).ToString("yyyy-MM-dd") + "',"; sql += "'" + HotelName + "',"; sql += "'" + pno + "',"; sql += "'" + address + "',"; sql += "'" + ddl + "')"; try { DB.CommonDatabase.RunQuery(sql); } catch (Exception) { cls.CommonClass objnew = new cls.CommonClass(); objnew.LogFailedQuery(sql, "HotelBookingDetails_" + supplier); } } catch (Exception ex) { string ServerPath = Server.MapPath("ErrorLogs"); string DataFile1 = "BookAfterPayment" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt"; FileStream fs1 = new FileStream(ServerPath + "/" + DataFile1, FileMode.Create, FileAccess.Write); StreamWriter fp1 = new StreamWriter(fs1, Encoding.UTF8); try { fp1.WriteLine(ex.Message.ToString()); } catch (Exception Ex) { } finally { fp1.Close(); fp1 = null; } } //try //{ // string xml = string.Empty; // xml += "<?xml version='1.0' encoding='utf-8'?>"; // xml += "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>"; // xml += "<soap:Body>"; // xml += "<InsertHotelDetails xmlns='http://tempuri.org/'>"; // xml += "<ReservationID>" + bookingref + "</ReservationID>"; // xml += "</InsertHotelDetails>"; // xml += "</soap:Body>"; // xml += "</soap:Envelope>"; // string url = "http://bookingapi.theholidaykingdom.com/ApiList.asmx"; // cls.CommonClass obj1 = new cls.CommonClass(); // string responsedata = obj1.PostXml4Min(url, xml); // //SAve Logs // string FileDateTime = Convert.ToString(System.DateTime.Now); // FileDateTime = DateTime.Now.ToString("dd-MM-yyyy HH;mm;ss"); // string ServerPath = Path.Combine(HttpRuntime.AppDomainAppPath, "ExcelReport"); // string DataFileName = "InsertHotelDetails" + "_" + FileDateTime + ".txt"; // try // { // FileStream fs = new FileStream(ServerPath + "/" + DataFileName, FileMode.Create, FileAccess.Write); // StreamWriter fp = new StreamWriter(fs, Encoding.UTF8); // try // { // fp.WriteLine(xml + "****" + responsedata + "****" + url); // fp.Close(); // } // catch (Exception Ex) // { } // finally // { } // } // catch (Exception Ex) // { } // //SAve Logs end //} //catch (Exception ex) //{ // //SAve Logs // string FileDateTime = Convert.ToString(System.DateTime.Now); // FileDateTime = DateTime.Now.ToString("dd-MM-yyyy HH;mm;ss"); // string ServerPath = Path.Combine(HttpRuntime.AppDomainAppPath, "ExcelReport"); // string DataFileName = "InsertHotelDetails" + "_" + FileDateTime + ".txt"; // try // { // FileStream fs = new FileStream(ServerPath + "/" + DataFileName, FileMode.Create, FileAccess.Write); // StreamWriter fp = new StreamWriter(fs, Encoding.UTF8); // try // { // fp.WriteLine(ex.ToString()); // fp.Close(); // } // catch (Exception Ex) // { } // finally // { } // } // catch (Exception Ex) // { } // //SAve Logs end} //} if (bookingId != "" || bookingId != null) { try { if (supplier.ToUpper() == "TRAVELBULLZ") { bookingId = bookingId.Split('#')[0]; } string username = string.Empty; string password = string.Empty; string email = CustomerDetails.Split('|')[4]; var data = bookingdetail.Split('$'); string roomtype = data[0].Split('!')[12] + " (" + data[0].Split('!')[17].Split('%')[0] + ")"; decimal servicetaxval = Convert.ToDecimal(data[0].Split('!')[15]) * ((Convert.ToDecimal(data[0].Split('!')[2].Split('`')[1])) / 100); string price1 = currtst + " " + (Convert.ToDecimal(data[0].Split('!')[15]) + servicetaxval); string city = data[2].Split('^')[4].Split('@')[1]; string totroom = (data[2].Split('~').Length - 1).ToString(); string totnyt = data[2].Split('^')[2]; string PaxName = string.Empty; int totpax = data[1].Split('/')[0].Split(',').Length - 1; for (int i = 0; i < totpax; i++) { PaxName += data[1].Split('/')[0].Split(',')[i] + " " + data[1].Split('/')[1].Split(',')[i] + " " + data[1].Split('/')[2].Split(',')[i] + "<br />"; } string Emails = email + "," + Session["loginVal"] + "," + "*****@*****.**"; if (email != null || email != "") { MailMessage mm = new MailMessage(); mm.From = new MailAddress(ConfigurationManager.AppSettings["UserName"]); mm.Subject = "Booking Invoice"; string[] multi = Emails.Split(','); foreach (string multiid in multi) { mm.Bcc.Add(new MailAddress(multiid)); } mm.Body = string.Format("Your Booking Confirmation Details ,<br /><br /><div class='container' align='center'><h2>Hotel Invoice</h2><table style='border: 2px solid navy;' width='750px'><tbody><tr><td style='border: 2px solid gray; padding:10px;'><b>Invoice Number: </b>" + bookingref + "</td><td style='border: 2px solid gray; padding:10px;'><b>Booking Id: </b>" + bookingId + "</td></tr><tr><td style='border: 2px solid gray; padding:10px;'><b>Booking Date: </b>" + DateTime.Now.ToString("dd-MM-yyyy") + "</td><td style='border: 2px solid gray; padding:10px;'><b>Status: </b>" + status + "</td></tr><tr style='height: 10px;'></tr><tr><td colspan='2' align='center'><img src=\"@@IMAGE@@\" alt=\"INLINE attachment\" height='70' width='250' /><br /><font size='2'>(A Unit of Travstarz Holiday & Destinations Pvt.Ltd)</font><br /><font size='2'>61-C 2nd Floor Eagle House Kalu Sarai Sarva Priya Vihar<br />New Delhi - 110016, India<br /><i>Tel No. :</i> 47050000 <i>Mail :</i> [email protected]</font><br /><font size='2'><b>GST No:</b> 07AAHCA9883B1ZI <b>Pan No:</b> AAHCA9883B</font></td></tr><tr style='height: 10px;'></tr><tr><td colspan='2' align='left' style='padding:10px;'><font size='4'>" + data[data.Length - 1].Split('!')[4] + "</font><br /><%=adrs %></td></tr><tr style='height: 15px;'></tr><tr><td style='padding-left:10px; width:50%;'><b>Check In Date: </b>" + chkin + "</td><td style='padding-left:10px;'><b>Check Out Date: </b>" + chkout + "</td></tr><tr><td style='padding-left:10px; width:50%;'><b>Hotel Name: </b>" + HotelName + "</td><td style='padding-left:10px;'><b>City: </b> " + city + "</td></tr><tr><td style='padding-left:10px; width:50%;'><b>No Of Night: </b>" + totnyt + "</td><td style='padding-left:10px;'><b>No Of Room(s): </b>" + totroom + "</td></tr><tr><td style='padding-left:10px; width:50%;'><b>Pax Name: </b>" + PaxName + "</td><td style='padding-left:10px;'><b>Room Type: </b>" + roomtype + "</td></tr><tr style='height: 25px;'></tr><tr><td align='center' colspan='2'><table width='100%' border='1px' cellpadding='10px'><tr><td><b>Amount (Including all Taxes)</b></td><td><b>Grand Total</b></td></tr><tr><td>" + price1 + "</td><td>" + price1 + "</td></tr></table></td><td align='center' colspan='2'></td></tr><tr style='height: 20px;'></tr><tr><td><b>Terms and Conditions</b></td><td align='right' rowspan='2'><b>Receiver's Signature</b></td></tr><tr style='height: 10px;'></tr><tr><td colspan='2' align='center'><b>This is an auto generated invoice hence no signature require.</b></td></tr></tbody></table></div><br /><br />Thank You."); mm.IsBodyHtml = true; string attachmentPath = Server.MapPath("~/new-travel-rez.png"); Attachment inline = new Attachment(attachmentPath); string contentID = Path.GetFileName(attachmentPath).Replace(".", "") + "@zofm"; inline.ContentDisposition.Inline = true; inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline; inline.ContentId = contentID; inline.ContentType.MediaType = "image/png"; inline.ContentType.Name = Path.GetFileName(attachmentPath); mm.Attachments.Add(inline); mm.Body = mm.Body.Replace("@@IMAGE@@", "cid:" + contentID); SmtpClient smtp = new SmtpClient(); smtp.Host = ConfigurationManager.AppSettings["Host"]; smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]); ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); }; NetworkCredential NetworkCred = new NetworkCredential(); NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"]; NetworkCred.Password = ConfigurationManager.AppSettings["Password"]; smtp.UseDefaultCredentials = true; smtp.Credentials = NetworkCred; smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]); smtp.Send(mm); } Response.Redirect("HotelBookingConfirmation.aspx"); } catch (Exception) { Response.Redirect("HotelBookingConfirmation.aspx"); } } } else { Response.Redirect("Error.aspx?BookingID" + bookingId); } } catch (Exception ex) { string ServerPath = Server.MapPath("ErrorLogs"); string DataFile1 = "BookAfterPayment" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt"; FileStream fs1 = new FileStream(ServerPath + "/" + DataFile1, FileMode.Create, FileAccess.Write); StreamWriter fp1 = new StreamWriter(fs1, Encoding.UTF8); try { fp1.WriteLine(ex.Message.ToString()); } catch (Exception Ex) { } finally { fp1.Close(); fp1 = null; } } }
public Boolean Manda(String IdFactura) { Boolean Mando = true; DepuraComilla DepCom = new DepuraComilla(); SqlConnection conn = new SqlConnection(Conexiones.CONEXION); SqlTransaction Transaccion = null; try { conn.Open(); Transaccion = conn.BeginTransaction(); //Primero obtengo las credenciales String Correo = ""; String Contraseña = ""; String Host = ""; String Puerto = ""; Boolean SSL = false; String QueryCredenciales = "SELECT Correo, Contraseña, Host, Puerto, SSL FROM Correo WHERE Activo = 1;"; SqlCommand ComandoCredenciales = new SqlCommand(QueryCredenciales, conn, Transaccion); SqlDataReader LectorCredenciales = ComandoCredenciales.ExecuteReader(); if (LectorCredenciales.HasRows) { while (LectorCredenciales.Read()) { Correo = LectorCredenciales.GetString(0); Contraseña = LectorCredenciales.GetString(1); Host = LectorCredenciales.GetString(2); Puerto = LectorCredenciales.GetString(3); SSL = LectorCredenciales.GetBoolean(4); } } else { Mando = false; } LectorCredenciales.Close(); if (Mando) { String XML = ""; MailMessage email = new MailMessage(); //Ahora obtengo los correos del cliente String QueryCorreos = "SELECT Correo, Ruta_XML FROM Facturas INNER JOIN CorreosCliente ON CorreosCliente.Id_Cliente = Facturas.Id_Cliente WHERE Id_Factura = '" + DepCom.Depurar(IdFactura) + "' AND CorreosCliente.Activo = 1 AND CorreosCliente.Numero_Cliente = (SELECT Numero_Cliente FROM Facturas WHERE Facturas.Id_Factura = '" + DepCom.Depurar(IdFactura) + "');"; SqlCommand ComandoCorreos = new SqlCommand(QueryCorreos, conn, Transaccion); SqlDataReader LectorCorreos = ComandoCorreos.ExecuteReader(); if (LectorCorreos.HasRows) { while (LectorCorreos.Read()) { email.To.Add(new MailAddress(LectorCorreos.GetString(0))); XML = LectorCorreos.GetString(1); } } LectorCorreos.Close(); String Texto = ""; String QueryTexto = "SELECT Texto FROM Correo;"; SqlCommand ComandoTexto = new SqlCommand(QueryTexto, conn, Transaccion); SqlDataReader LectorTexto = ComandoTexto.ExecuteReader(); if (LectorTexto.HasRows) { while (LectorTexto.Read()) { Texto = LectorTexto.GetString(0); } } LectorTexto.Close(); String[] ArregloFactura = XML.Split('\\'); email.From = new MailAddress(Correo); email.Subject = "Reenvio de Factura " + ArregloFactura[ArregloFactura.Length - 1].Replace(".xml", ""); //Adjunto los archivos //email.Attachments.Add(new Attachment(XML)); //email.Attachments.Add(new Attachment(XML.Replace(".xml", ".pdf"))); email.Body = Texto; email.IsBodyHtml = false; email.Priority = MailPriority.Normal; //Definimos credenciales SmtpClient smtp = new SmtpClient(); smtp.Host = Host; smtp.Port = Convert.ToInt32(Puerto); smtp.EnableSsl = SSL; smtp.UseDefaultCredentials = false; smtp.Credentials = new System.Net.NetworkCredential(Correo, Contraseña); smtp.Send(email); //eliminamos el objeto smtp.Dispose(); //Ahora marcamos como enviado String Query = "UPDATE Facturas SET Enviada = 1 where Id_Factura = '" + IdFactura + "';"; SqlCommand Comando = new SqlCommand(Query, conn); conn.Open(); Comando.ExecuteNonQuery(); conn.Close(); } Transaccion.Commit(); conn.Close(); } catch (Exception ex) { Mando = false; Transaccion.Rollback(); conn.Close(); } return(Mando); }
public static Dictionary <string, int> SendUpdatesByEmail() { //Scope variables Dictionary <string, int> dict = new Dictionary <string, int>(); List <latestUpdates> lstLatestUpdates = new List <latestUpdates>(); StringBuilder sbHtmlList = new StringBuilder(); StringBuilder sbTextList = new StringBuilder(); string emailBody_Html = string.Empty; string emailBody_Text = string.Empty; Boolean errored = false; int totalSuccessful = 0; int totalFailed = 0; DateTime datePublished = DateTime.Today; //Obtain list of most recent messages try { lstLatestUpdates = Controllers.MessageController.ObtainLatestMessages(); } catch (Exception ex) { //Save error message to umbraco StringBuilder sb = new StringBuilder(); sb.AppendLine(@"MembershipController.cs : SendUpdatesByEmail()"); sb.AppendLine("Error retrieving latest messages."); Common.SaveErrorMessage(ex, sb, typeof(MembershipController)); errored = true; } //Convert List to Html if (!errored) { try { //Instantiate variables Boolean isFirst = true; string lastVisionary = ""; const string strVisionary = "<br /><br /><div class='name' style='font-size:18px;font-weight:900;text-align:center;'><a href='[HREF]' style='color: #f3a42a; text-decoration: none;'>[VISIONARY]</a></div>"; const string strMsg = "<div class='title' style='font-size:20px;text-align:center;'><a href='[HREF]' style='color: #f3a42a; text-decoration: none;'><span class='cross' style='color: #f3a42a; text-decoration: none;'>✞ </span>[TITLE]</a></div>"; //Convert list to html foreach (latestUpdates latestUpdate in lstLatestUpdates) { if (isFirst) { //Obtain date published datePublished = latestUpdate.datePublished; isFirst = false; } foreach (visionary visionary in latestUpdate.lstVisionaries) { if (lastVisionary != visionary.name) { sbHtmlList.AppendLine(strVisionary.Replace("[HREF]", visionary.url).Replace("[VISIONARY]", visionary.name)); lastVisionary = visionary.name; } foreach (message msg in visionary.lstMessages) { sbHtmlList.AppendLine(strMsg.Replace("[HREF]", msg.url).Replace("[TITLE]", msg.title)); } } } } catch (Exception ex) { //Save error message to umbraco StringBuilder sb = new StringBuilder(); sb.AppendLine(@"MembershipController.cs : SendUpdatesByEmail()"); sb.AppendLine("Error converting list to html:"); sb.AppendLine(Newtonsoft.Json.JsonConvert.SerializeObject(lstLatestUpdates)); Common.SaveErrorMessage(ex, sb, typeof(MembershipController)); errored = true; } } //Convert List to Text if (!errored) { try { //Instantiate variables Boolean isFirst = true; string lastVisionary = ""; //Convert list to html foreach (latestUpdates latestUpdate in lstLatestUpdates) { foreach (visionary visionary in latestUpdate.lstVisionaries) { if (lastVisionary != visionary.name) { sbTextList.AppendLine(" "); sbTextList.AppendLine(" "); sbTextList.AppendLine(visionary.name); lastVisionary = visionary.name; } foreach (message msg in visionary.lstMessages) { sbTextList.AppendLine(msg.title + " | " + msg.url); } } } } catch (Exception ex) { //Save error message to umbraco StringBuilder sb = new StringBuilder(); sb.AppendLine(@"MembershipController.cs : SendUpdatesByEmail()"); sb.AppendLine("Error converting list to text:"); sb.AppendLine(Newtonsoft.Json.JsonConvert.SerializeObject(lstLatestUpdates)); Common.SaveErrorMessage(ex, sb, typeof(MembershipController)); errored = true; } } //Create email files if (!errored) { try { //Obtain host url string hostUrl = System.Web.HttpContext.Current.Request.Url.Scheme + "://" + System.Web.HttpContext.Current.Request.Url.Host + "/"; //Extract templates from email files //string filePath_html = HostingEnvironment.MapPath("~/Emails/RecentUpdates/RecentUpdates-uncompressed.html"); string filePath_html = HostingEnvironment.MapPath("~/Emails/RecentUpdates/RecentUpdates.html"); string filePath_Text = HostingEnvironment.MapPath("~/Emails/RecentUpdates/RecentUpdates.txt"); emailBody_Html = System.IO.File.ReadAllText(filePath_html); emailBody_Text = System.IO.File.ReadAllText(filePath_Text); // Insert data into page emailBody_Html = emailBody_Html.Replace("[AFTERTHEWARNING_URL]", hostUrl); emailBody_Html = emailBody_Html.Replace("[INFO]", sbHtmlList.ToString()); emailBody_Html = emailBody_Html.Replace("[DATE]", datePublished.ToString("MMMM d, yyyy")); emailBody_Html = emailBody_Html.Replace("[YEAR]", DateTime.Today.Year.ToString()); emailBody_Text = emailBody_Text.Replace("[AFTERTHEWARNING_URL]", hostUrl); emailBody_Text = emailBody_Text.Replace("[INFO]", sbTextList.ToString()); emailBody_Text = emailBody_Text.Replace("[DATE]", datePublished.ToString("MMMM d, yyyy")); emailBody_Text = emailBody_Text.Replace("[YEAR]", DateTime.Today.Year.ToString()); } catch (Exception ex) { //Save error message to umbraco StringBuilder sb = new StringBuilder(); sb.AppendLine(@"MembershipController.cs : SendUpdatesByEmail()"); sb.AppendLine("Error creating email files"); Common.SaveErrorMessage(ex, sb, typeof(MembershipController)); errored = true; } } //Send email files to each member via email. if (!errored) { try { //Instantiate variables UmbracoHelper umbHelper = new UmbracoHelper(UmbracoContext.Current); IMemberService memberService = ApplicationContext.Current.Services.MemberService; IEnumerable <IMember> members = memberService.GetAllMembers(); SmtpClient smtp = new SmtpClient(); MailMessage Msg = new MailMessage(); ////CREATE TEST MEMBER LIST //IMember tempMember1 = memberService.GetByEmail("*****@*****.**"); //IMember tempMember2 = memberService.GetByEmail("*****@*****.**"); //List<IMember> members = new List<IMember>(); //members.Add(tempMember1); //members.Add(tempMember2); //Create email message Msg.BodyEncoding = Encoding.UTF8; Msg.SubjectEncoding = Encoding.UTF8; Msg.Subject = "Recent Updates | After the Warning"; Msg.IsBodyHtml = true; Msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(emailBody_Text, Encoding.UTF8, MediaTypeNames.Text.Plain)); Msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(emailBody_Html, Encoding.UTF8, MediaTypeNames.Text.Html)); //Loop through each member foreach (IMember member in members) { try { // if (member.GetValue <Boolean>(Common.NodeProperties.subscribed) == true) { //Clear email list and add new member email Msg.To.Clear(); Msg.To.Add(new MailAddress(member.Email)); // Send email smtp.Send(Msg); //Increment successful tally totalSuccessful++; } } catch (Exception ex) { //Save error message to umbraco StringBuilder sb = new StringBuilder(); sb.AppendLine(@"MembershipController.cs : SendUpdatesByEmail()"); sb.AppendLine(@"Error sending email to:" + member.Name); Common.SaveErrorMessage(ex, sb, typeof(MembershipController)); //Increment failed tally totalFailed++; } } //Close connection after emails have been sent. smtp.ServicePoint.CloseConnectionGroup(smtp.ServicePoint.ConnectionName); } catch (Exception ex) { //Save error message to umbraco StringBuilder sb = new StringBuilder(); sb.AppendLine(@"MembershipController.cs : SendUpdatesByEmail()"); sb.AppendLine(@"Error creating smtpClient and/or list of members."); Common.SaveErrorMessage(ex, sb, typeof(MembershipController)); } } //Return results dict.Add("successful", totalSuccessful); dict.Add("failed", totalFailed); return(dict); }
public static void EnviarCorreoLDI(string Sentido, string Periodo) { ICPruebaEntities db = new ICPruebaEntities(); string rutaArchivoIngreso = string.Empty; string rutaArchivoCostos = string.Empty; string rutaArchivoFluctuacion = string.Empty; string sHost = ConfigurationManager.AppSettings["HostCorreo"]; string sPort = ConfigurationManager.AppSettings["PuertoCorreo"]; //string filename = @"C:\Users\Paul\Documents\test.txt"; //Attachment data = new Attachment(filename, MediaTypeNames.Application.Octet); MailMessage email = new MailMessage(); StringBuilder sbBody = new StringBuilder(); string rutaArchivos = string.Empty; string ListaCorreos = string.Empty; string[] _aPeriodo = Periodo.Split('/'); string Mes = _aPeriodo[1]; string Ano = _aPeriodo[2]; string Subject = string.Empty; //string Nombre = "";//Session["NombrePoliza"].ToString(); //Obtenemos rutas configurables de base de datos string[] Rutas = GenerarPolizas.RutasArchivosConfigurables(); rutaArchivoIngreso = Rutas[0].ToString(); rutaArchivoCostos = Rutas[1].ToString(); rutaArchivoFluctuacion = Rutas[2].ToString(); //Obtenemos Lista de correos var correos = from datos in db.parametrosCargaDocumento where datos.idDocumento == "CORREO" select new { datos.pathURL }; foreach (var item in correos) { ListaCorreos = item.pathURL; } if (Sentido == "INGRESO") { string[] Archivos; //Creamos Body sbBody.Append("IC Infroma: Genero Polizas INGRESOS automatica para SAP del periodo " + Mes + " " + Ano + "Con los archivos adjuntos:"); sbBody.AppendFormat("<br/>"); //Obtenemos los archivos csv de la carpeta y los Adjuntamos Archivos = Directory.GetFiles(rutaArchivoIngreso, "*.csv"); //string NombreArchivo = Path.GetFileName(rutaArchivos); foreach (string archivo in Archivos) { email.Attachments.Add(new Attachment(archivo)); } foreach (string archivo in Archivos) { sbBody.AppendFormat("<br/>{0}", Path.GetFileName(archivo)); } //Creamos Subject Subject = "[External]IC Archivos Generados S1 INGRESOS ( " + DateTime.Now.ToString("dd / MMM / yyy hh:mm:ss") + " ) " + "Periodo " + Mes + " " + Ano; //foreach (string archivo in Archivos) //{ // sbBody.AppendFormat("<br/>{0}", Path.GetFileName(archivo)); //} } if (Sentido == "COSTO") { string[] Archivos; //Creamos Body sbBody.Append("IC Infroma: Genero Polizas COSTOS automatica para SAP del periodo " + Mes + " " + Ano + "Con los archivos adjuntos:"); sbBody.AppendFormat("<br/>"); //Obtenemos los archivos csv de la carpeta y los Adjuntamos Archivos = Directory.GetFiles(rutaArchivoCostos, "*.csv"); //string NombreArchivo = Path.GetFileName(rutaArchivos); foreach (string archivo in Archivos) { email.Attachments.Add(new Attachment(archivo)); } foreach (string archivo in Archivos) { sbBody.AppendFormat("<br/>{0}", Path.GetFileName(archivo)); } //Creamos Subject Subject = "[External]IC Archivos Generados S3 COSTOS(" + DateTime.Now.ToString("dd / MMM / yyy hh: mm:ss") + ") " + "Periodo " + Mes + " " + Ano; } if (Sentido == "FLUCTUACION") { string[] Archivos; //Creamos Body sbBody.Append("IC Infroma: Genero Polizas FLUCTUACION automatica para SAP del periodo " + Mes + " " + Ano + "Con los archivos adjuntos:"); sbBody.AppendFormat("<br/>"); //Obtenemos los archivos csv de la carpeta y los Adjuntamos Archivos = Directory.GetFiles(rutaArchivoFluctuacion, "*.csv"); //string NombreArchivo = Path.GetFileName(rutaArchivos); foreach (string archivo in Archivos) { email.Attachments.Add(new Attachment(archivo)); } foreach (string archivo in Archivos) { sbBody.AppendFormat("<br/>{0}", Path.GetFileName(archivo)); } //Creamos Subject Subject = "[External]IC Archivos Generados SA FLUCTUACION ( " + DateTime.Now.ToString("dd / MMM / yyy hh:mm:ss") + " ) " + "Periodo " + Mes + " " + Ano; } //De quen se envia email.From = new MailAddress("*****@*****.**"); //A quien se le envia correo //email.To.Add(new MailAddress("[email protected], [email protected], [email protected], [email protected]")); email.To.Add(new MailAddress(ListaCorreos)); email.Subject = Subject; email.Body = sbBody.ToString(); email.IsBodyHtml = true; email.Priority = MailPriority.High; SmtpClient smtp = new SmtpClient(); smtp.Host = sHost; smtp.Port = int.Parse(sPort); smtp.EnableSsl = false; smtp.UseDefaultCredentials = true; smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //Se envia Correo smtp.Send(email); email.Dispose(); }
public async Task Send(string subject, string content, MessagePriority priority) { if (Enabled) { using var client = new SmtpClient(); try { var options = SecureSocketOptions.None; if (_secure) { if (_secureMode.HasValue) { switch (_secureMode.Value) { case 1: options = SecureSocketOptions.Auto; break; case 2: options = SecureSocketOptions.SslOnConnect; break; case 3: options = SecureSocketOptions.StartTls; break; case 4: options = SecureSocketOptions.StartTlsWhenAvailable; break; } } else { options = SecureSocketOptions.StartTls; } } await client.ConnectAsync(_server, _port, options); if (!string.IsNullOrEmpty(_user)) { await client.AuthenticateAsync(new NetworkCredential(_user, _password)); } foreach (var receiverAddress in _receiverAddresses) { _log.Information("Sending e-mail with subject {subject} to {_receiverAddress}", subject, receiverAddress); var sender = new MailboxAddress(_senderName, _senderAddress); var receiver = new MailboxAddress(receiverAddress); var message = new MimeMessage() { Sender = sender, Priority = priority, Subject = subject }; message.Subject = $"{subject} ({_computerName})"; message.From.Add(sender); message.To.Add(receiver); var bodyBuilder = new BodyBuilder(); bodyBuilder.HtmlBody = content + $"<p>Sent by win-acme version {_version} from {_computerName}</p>"; message.Body = bodyBuilder.ToMessageBody(); await client.SendAsync(message); } await client.DisconnectAsync(true); } catch (Exception ex) { _log.Error(ex, "Problem sending e-mail"); } finally { } } }
public String SendEmailInviteStandBy([FromBody] EmailViewModel emailViewModel) { try { //Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath); //MailSettingsSectionGroup settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings"); SmtpClient sc = new SmtpClient("smtp.zoho.com"); System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); msg.From = new MailAddress("*****@*****.**"); msg.To.Add(new MailAddress("*****@*****.**", "Prakash Anban")); msg.To.Add(new MailAddress("*****@*****.**", "Yuvaraj Sathiyamoorthy")); msg.To.Add(new MailAddress("*****@*****.**", "Prakash Gmail")); msg.Subject = emailViewModel.Subject; msg.Body = emailViewModel.Body; StringBuilder str = new StringBuilder(); str.AppendLine("BEGIN:VCALENDAR"); str.AppendLine("PRODID:-//" + "*****@*****.**"); str.AppendLine("VERSION:2.0"); str.AppendLine("METHOD:REQUEST"); str.AppendLine("BEGIN:VEVENT"); str.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", emailViewModel.StartDate.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z"))); str.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}", (emailViewModel.EndDate - emailViewModel.StartDate).Minutes.ToString())); str.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", emailViewModel.EndDate.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z"))); //str.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", objApptEmail.StartDate.ToString())); //str.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}", DateTime.UtcNow)); //str.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", objApptEmail.EndDate.ToString())); str.AppendLine("LOCATION:" + emailViewModel.Location); str.AppendLine(string.Format("DESCRIPTION:{0}", emailViewModel.Body)); str.AppendLine(string.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", emailViewModel.Body)); str.AppendLine(string.Format("SUMMARY:{0}", emailViewModel.Subject)); str.AppendLine(string.Format("ORGANIZER:MAILTO:{0}", "*****@*****.**")); str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", msg.To[0].DisplayName, msg.To[0].Address)); str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", msg.To[1].DisplayName, msg.To[1].Address)); str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", msg.To[2].DisplayName, msg.To[2].Address)); str.AppendLine("BEGIN:VALARM"); str.AppendLine("TRIGGER:-PT15M"); str.AppendLine("ACTION:DISPLAY"); str.AppendLine("DESCRIPTION:Reminder"); str.AppendLine("END:VALARM"); str.AppendLine("END:VEVENT"); str.AppendLine("END:VCALENDAR"); System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType("text/calendar"); ct.Parameters.Add("method", "REQUEST"); AlternateView avCal = AlternateView.CreateAlternateViewFromString(str.ToString(), ct); msg.AlternateViews.Add(avCal); NetworkCredential nc = new NetworkCredential("*****@*****.**", "Temp#123"); sc.Port = 587; sc.EnableSsl = true; sc.Credentials = nc; try { sc.Send(msg); return("Success"); } catch (Exception ex) { return("Fail Reason +++++++++ " + ex); } } catch (Exception e) { return("" + e); } return(string.Empty); }
public void EnviarEmail(int cd_procedimento, string tipo) { db = new b2yweb_entities("oracle"); ProcedimentoAdm procedimento = db.ProcedimentoAdm.Find(cd_procedimento); int cd_departamento = 0; //string obsOriginal = procedimento.OBS; string obsOriginal = String.Concat(procedimento.Clientes.CD_CADASTRO.ToString(), "-", procedimento.Clientes.RAZAO);; string dtaUltimaInteracao = ""; string msgUltimaInteracao = ""; string userUltimaInteracao = ""; string usuarioAbertura = procedimento.Usuario.NOME; if (tipo == "Edit") { if (db.pa_troca_departamentos.Where(a => a.CD_PROCEDIMENTO == procedimento.CD_PROCEDIMENTO).Count() > 0) { dtaUltimaInteracao = (from a in db.pa_troca_departamentos.Where(a => a.CD_PROCEDIMENTO == procedimento.CD_PROCEDIMENTO).OrderByDescending(a => a.NUM_SEQ) select a.DTA_ENTRADA_DEP_NOVA).FirstOrDefault().ToString(); msgUltimaInteracao = (from a in db.pa_troca_departamentos.Where(a => a.CD_PROCEDIMENTO == procedimento.CD_PROCEDIMENTO).OrderByDescending(a => a.NUM_SEQ) select a.OBS).FirstOrDefault().ToString(); userUltimaInteracao = (from a in db.pa_troca_departamentos.Where(a => a.CD_PROCEDIMENTO == procedimento.CD_PROCEDIMENTO).OrderByDescending(a => a.NUM_SEQ) select a.Usuario.NOME).FirstOrDefault().ToString(); cd_departamento = (from a in db.pa_troca_departamentos.Where(a => a.CD_PROCEDIMENTO == procedimento.CD_PROCEDIMENTO).OrderByDescending(a => a.NUM_SEQ) select a.CD_DEPARTAMENTO_NOVA).FirstOrDefault(); } else { dtaUltimaInteracao = ""; userUltimaInteracao = ""; cd_departamento = 0; } } else { dtaUltimaInteracao = ""; userUltimaInteracao = ""; cd_departamento = 0; } if (cd_departamento == 0) { cd_departamento = procedimento.CD_DEPARTAMENTO; } if (cd_departamento == 0) { return; } string enviaemail = (from a in db.DEPARTAMENTOes.Where(a => a.CD_DEPARTAMENTO == cd_departamento) select a.ENVIA_EMAIL).FirstOrDefault(); var depUsu = db.DepartamentoUsuario.Where(a => a.CD_DEPARTAMENTO == cd_departamento).ToList(); if (enviaemail == "N") { return; } //var stateList = new List<int>() {2,3,4}; //if ((tipo == "Edit") && (!procedimento.Situacao.ToString().Contains(stateList.ToString()))) //{ // return; //} var msg = new MailMessage(); string Para = ""; string CC = ""; int aux = 1; foreach (var var in depUsu) { if (aux == 1) { msg.To.Add(new MailAddress(var.Usuario.EMAIL)); } else { msg.CC.Add(new MailAddress(var.Usuario.EMAIL)); } aux += 1; } string DepResponsavel = procedimento.DEPARTAMENTO.DESC_DEPARTAMENTO; string dta_abertura = procedimento.DTA_ABERTURA.ToString(); string nfFox = procedimento.NF_FOX.ToString(); string situacao = procedimento.Situacao.DESCRICAO; string DescTipo = (from a in db.TP_PROCEDIMENTO.Where(a => a.CD_TIPO == procedimento.CD_TIPO) select a.DES_TIPO).FirstOrDefault(); string subject = "[Chamado #" + cd_procedimento + "] " + DescTipo; string email = ConfigurationManager.AppSettings["MailFrom"].ToString(); string username = ConfigurationManager.AppSettings["MailUserName"].ToString(); string password = ConfigurationManager.AppSettings["MailPwd"].ToString(); var loginInfo = new NetworkCredential(username, password); var smtpClient = new SmtpClient(ConfigurationManager.AppSettings["SMTP"].ToString(), Int32.Parse(ConfigurationManager.AppSettings["Port"])); //string message = "<b> DADOS DO CHAMADO </b>"; //string path = System.Web.HttpContext.Current.Server.MapPath("~/Images/LogoEmail.png"); // my logo is placed in images folder //Path.GetFileName(Server.MapPath("~/Images"), "LogoEmail.png"); //get //LinkedResource logo = new LinkedResource(path); //logo.ContentId = "companylogo"; #region msgbody string message = " <div align='center'> "; message += " <table class='MsoNormalTable' border='0' cellspacing='0' cellpadding='0' width='600' style='width:450.0pt;mso-cellspacing:0cm;mso-yfti-tbllook:1184;mso-padding-alt: "; message += " 0cm 0cm 0cm 0cm'> "; message += " <tbody><tr style='mso-yfti-irow:0;mso-yfti-firstrow:yes'> "; message += " <td style='padding:0cm 0cm 0cm 0cm'> "; message += " <p class='MsoNormal'><span style='font-size:9.0pt;font-family:"Verdana","sans-serif"; "; message += " mso-fareast-font-family:"Times New Roman";color:#797979'><img id='_x0000_i1025' src='~/Images/LogoEmail.png'><o:p></o:p></span></p> "; message += " </td>"; message += " </tr> "; message += " <tr style='mso-yfti-irow:1;height:15.0pt'> "; message += " <td style='padding:0cm 0cm 0cm 0cm;height:15.0pt'></td> "; message += " </tr>"; message += " <tr style='mso-yfti-irow:2'>"; message += " <td style='padding:0cm 15.0pt 0cm 15.0pt'> "; message += " <h3 style='margin:0cm;margin-bottom:.0001pt'><span style='font-family:"Verdana","sans-serif"; "; if (tipo == "Edit") { message += " mso-fareast-font-family:"Times New Roman";color:#2A2A2A'>Nova interação no "; } if (tipo == "Create") { message += " mso-fareast-font-family:"Times New Roman";color:#2A2A2A'>Você recebeu uma solicitação para avaliar: "; } message += " procedimento : " + cd_procedimento + "<o:p></o:p></span></h3> "; message += " <p class='MsoNormal'><span style='font-size:9.0pt;font-family:"Verdana","sans-serif"; "; message += " mso-fareast-font-family:"Times New Roman";color:#797979'><o:p> </o:p></span></p> "; message += " <p style='margin:0cm;margin-bottom:.0001pt'><span style='font-size:10.5pt; "; message += " font-family:"Verdana","sans-serif";color:#797979'>Dados do procedimento<o:p></o:p></span></p> "; message += " </td>"; message += " </tr> "; message += " <tr style='mso-yfti-irow:3'>"; message += " <td style='padding:7.5pt 7.5pt 0cm 7.5pt'>"; message += " <div style='border:solid #D7D7D7 1.0pt;mso-border-alt:solid #D7D7D7 .75pt;"; message += " padding:8.0pt 8.0pt 8.0pt 8.0pt'>"; message += " <p style='margin:1.5pt;background:#F7F7F7'><span style='font-size:9.0pt;"; message += " font-family:"Verdana","sans-serif";color:#797979'>Data Abertura: <strong><span style='font-family:"Verdana","sans-serif"'>" + dta_abertura + "</span></strong><o:p></o:p></span></p>"; message += " <p style='margin:1.5pt;background:#F7F7F7'><span style='font-size:9.0pt;"; message += " font-family:"Verdana","sans-serif";color:#797979'>Usuário: <strong><span style='font-family:"Verdana","sans-serif"'>" + usuarioAbertura + "</span></strong><o:p></o:p></span></p>"; message += " <p style='margin:1.5pt;background:#F7F7F7'><span style='font-size:9.0pt;"; message += " font-family:"Verdana","sans-serif";color:#797979'>Cliente: <strong><span style='font-family:"Verdana","sans-serif"'>" + obsOriginal; message += " </span></strong><o:p></o:p></span></p>"; message += " <p style='margin:1.5pt;background:#F7F7F7'><span style='font-size:9.0pt;"; message += " font-family:"Verdana","sans-serif";color:#797979'>NF Foxlux: <strong><span style='font-family:"Verdana","sans-serif"'>" + nfFox; message += " </span></strong><o:p></o:p></span></p>"; message += " <p style='margin:1.5pt;background:#F7F7F7'><span style='font-size:9.0pt;"; message += " font-family:"Verdana","sans-serif";color:#797979'>Departamento: <strong><span style='font-family:"Verdana","sans-serif"'>" + DepResponsavel + "</span></strong><o:p></o:p></span></p>"; message += " <p style='margin:1.5pt;background:#F7F7F7'><span style='font-size:9.0pt;"; message += " font-family:"Verdana","sans-serif";color:#797979'>No. do procedimento: <strong><span style='font-family:"Verdana","sans-serif"'>" + cd_procedimento + "</span></strong><o:p></o:p></span></p>"; message += " </div>"; message += " </td>"; message += " </tr>"; message += " <tr style='mso-yfti-irow:4'>"; message += " <td style='padding:0cm 15.0pt 0cm 15.0pt'>"; message += " <p class='MsoNormal'><span style='font-size:9.0pt;font-family:"Verdana","sans-serif";"; message += " mso-fareast-font-family:"Times New Roman";color:#797979'><o:p> </o:p></span></p>"; //message += " <p style='margin:0cm;margin-bottom:.0001pt'><span style='font-size:10.5pt;" ; //if (tipo == "Edit") //{ // message += " font-family:"Verdana","sans-serif";color:#797979'>Última interação<o:p></o:p></span></p>"; //} //if (tipo == "Create") //{ // message += " font-family:"Verdana","sans-serif";color:#797979'>Dados do Chamado<o:p></o:p></span></p>"; //} //message += " <p class='MsoNormal'><span style='font-size:9.0pt;font-family:"Verdana","sans-serif";" ; //message += " mso-fareast-font-family:"Times New Roman";color:#797979'><o:p> </o:p></span></p>" ; message += " <p style='margin:1.5pt'><span style='font-size:9.0pt;font-family:"Verdana","sans-serif";"; //if (tipo == "Edit") //{ // message += " color:#797979'>Autor: <strong><span style='font-family:"Verdana","sans-serif"'>" + userUltimaInteracao; //} //if (tipo == "Create") //{ // message += " color:#797979'>Autor: <strong><span style='font-family:"Verdana","sans-serif"'>" + usuarioAbertura; //} //message += " </span></strong><o:p></o:p></span></p>" ; //message += " <p style='margin:1.5pt'><span style='font-size:9.0pt;font-family:"Verdana","sans-serif";" ; //if (tipo == "Edit") //{ // message += " color:#797979'>Data: <strong><span style='font-family:"Verdana","sans-serif"'>" + dtaUltimaInteracao; //} //if (tipo == "Create") //{ // message += " color:#797979'>Data: <strong><span style='font-family:"Verdana","sans-serif"'>" + dta_abertura; //} // message += " </span></strong><o:p></o:p></span></p>" ; // message += " <p class='MsoNormal'><span style='font-size:9.0pt;font-family:"Verdana","sans-serif";" ; // message += " mso-fareast-font-family:"Times New Roman";color:#797979'><br>" ; // message += " <br style='mso-special-character:line-break'>" ; // message += " <!--[if !supportLineBreakNewLine]--><br style='mso-special-character:line-break'>" ; // message += " <!--[endif]--><o:p></o:p></span></p>" ; //message += " <p style='margin:0cm;margin-bottom:.0001pt'><span style='font-size:9.0pt;" ; //message += " font-family:"Verdana","sans-serif";color:#797979'> Msg. <br>" ; //message += " <br>" ; //if (tipo == "Edit") //{ // message += " " + msgUltimaInteracao; //} //if (tipo == "Create") //{ // message += " " + obsOriginal; //} //message += " <br>" ; //message += " Atenciosamente,<br>" ; //message += " <br>" ; //message += " " + ((Usuario)HttpContext.Current.Session["oUsuario"]).NOME + " <o:p></o:p></span></p>"; message += " <p class='MsoNormal' style='margin-bottom:12.0pt'><span style='font-size:9.0pt;"; message += " font-family:"Verdana","sans-serif";mso-fareast-font-family:"Times New Roman";"; message += " color:#797979'><o:p> </o:p></span></p>"; // message += " <p style='margin:0cm;margin-bottom:.0001pt'><span style='font-size:9.0pt;" ; // message += " font-family:"Verdana","sans-serif";color:#797979'>Para visualizar esse" ; // message += " chamado, acesse o link: <br>" ; // message += " <a href='http://centraldocliente.locaweb.com.br/tickets/19702140'><span style='color:#990000'>http://centraldocliente.locaweb.com.br/tickets/19702140</span></a><o:p></o:p></span></p>" ; message += " </td>"; message += " </tr>"; message += " <tr style='mso-yfti-irow:5;height:30.0pt'>"; message += " <td style='padding:0cm 0cm 0cm 0cm;height:30.0pt'></td>"; message += " </tr>"; message += " <tr style='mso-yfti-irow:6;height:34.5pt'>"; message += " <td width='600' style='width:450.0pt;padding:0cm 0cm 0cm 0cm;height:34.5pt'>"; /*message += " <table class='MsoNormalTable' border='0' cellspacing='0' cellpadding='0' width='600' style='width:450.0pt;mso-cellspacing:0cm;background:#131313;mso-yfti-tbllook:" ; * message += " 1184;mso-padding-alt:0cm 7.5pt 0cm 7.5pt;border-radius: 3px 3px 3px 3px'>" ; * message += " <tbody><tr style='mso-yfti-irow:0;mso-yfti-firstrow:yes;mso-yfti-lastrow:yes'>" ; * message += " <td style='padding:0cm 7.5pt 0cm 7.5pt'>" ; * message += " <p class='MsoNormal'><span style='font-size:10.0pt;font-family:"Arial","sans-serif";" ; * message += " mso-fareast-font-family:"Times New Roman";color:white;text-transform:uppercase'>Suporte" ; * message += " e Ajuda <img border='0' id='_x0000_i1026' src='https://centraldocliente.locaweb.com.br/assets/border-menu-support-footer-e0a15b2f50f910340fcb9842e80ec48f.png' style='margin-bottom:0in;margin-left:5px;margin-right:5px;margin-top:0in;" ; * message += " vertical-align:middle'><o:p></o:p></span></p>" ; * message += " </td>" ; * message += " <td style='padding:0cm 7.5pt 0cm 7.5pt'>" ; * message += " <p class='MsoNormal'><span style='font-size:9.0pt;font-family:"Arial","sans-serif";" ; * message += " mso-fareast-font-family:"Times New Roman";color:white'><img border='0' id='_x0000_i1027' src='https://centraldocliente.locaweb.com.br/assets/arrow-right-red-menu-9b5b6e2b0f40f2f19e8e05d2dfd7c251.png' style='vertical-align:middle'><a href='https://centraldocliente.locaweb.com.br/treatment' target='_blank' title='Atendimento'><span style='color:white;text-decoration:none;text-underline:" ; * message += " none'>Atendimento </span></a><img border='0' id='_x0000_i1028' src='https://centraldocliente.locaweb.com.br/assets/border-menu-support-footer-e0a15b2f50f910340fcb9842e80ec48f.png' style='margin-bottom:0in;margin-left:5px;margin-right:5px;margin-top:0in;" ; * message += " vertical-align:middle'><o:p></o:p></span></p>" ; * message += " </td>" ; * message += " <td style='padding:0cm 7.5pt 0cm 7.5pt'>" ; * message += " <p class='MsoNormal'><span style='font-size:9.0pt;font-family:"Arial","sans-serif";" ; * message += " mso-fareast-font-family:"Times New Roman";color:white'><img border='0' id='_x0000_i1029' src='https://centraldocliente.locaweb.com.br/assets/arrow-right-red-menu-9b5b6e2b0f40f2f19e8e05d2dfd7c251.png' style='vertical-align:middle'><a href='https://centraldocliente.locaweb.com.br/tickets' target='_blank' title='Meus Chamados'><span style='color:white;text-decoration:none;" ; * message += " text-underline:none'>Meus Chamados </span></a><img border='0' id='_x0000_i1030' src='https://centraldocliente.locaweb.com.br/assets/border-menu-support-footer-e0a15b2f50f910340fcb9842e80ec48f.png' style='margin-bottom:0in;margin-left:5px;margin-right:5px;margin-top:0in;" ; * message += " vertical-align:middle'><o:p></o:p></span></p>" ; * message += " </td>" ; * message += " <td style='padding:0cm 7.5pt 0cm 7.5pt'>" ; * message += " <p class='MsoNormal'><span style='font-size:9.0pt;font-family:"Arial","sans-serif";" ; * message += " mso-fareast-font-family:"Times New Roman";color:white'><img border='0' id='_x0000_i1031' src='https://centraldocliente.locaweb.com.br/assets/arrow-right-red-menu-9b5b6e2b0f40f2f19e8e05d2dfd7c251.png' style='vertical-align:middle'><a href='http://wiki.locaweb.com.br' target='_blank' title='Central de Ajuda (wiki)'><span style='color:white;" ; * message += " text-decoration:none;text-underline:none'>Central de Ajuda (wiki) </span></a><img border='0' id='_x0000_i1032' src='https://centraldocliente.locaweb.com.br/assets/border-menu-support-footer-e0a15b2f50f910340fcb9842e80ec48f.png' style='margin-bottom:0in;margin-left:5px;margin-right:5px;margin-top:0in;" ; * message += " vertical-align:middle'><o:p></o:p></span></p>" ; * message += " </td>" ; * message += " <td style='padding:0cm 7.5pt 0cm 7.5pt'>" ; * message += " <p class='MsoNormal'><span style='font-size:9.0pt;font-family:"Arial","sans-serif";" ; * message += " mso-fareast-font-family:"Times New Roman";color:white'><img border='0' id='_x0000_i1033' src='https://centraldocliente.locaweb.com.br/assets/arrow-right-red-menu-9b5b6e2b0f40f2f19e8e05d2dfd7c251.png' style='vertical-align:middle'><a href='http://statusblog.locaweb.com.br/' target='_blank'><span style='color:white;text-decoration:none;text-underline:" ; * message += " none'>Status blog </span></a><o:p></o:p></span></p>" ; * message += " </td>" ; * message += " </tr>" ; * message += " </tbody></table>" ; */ message += " </td>"; message += " </tr>"; message += " <tr style='mso-yfti-irow:7;mso-yfti-lastrow:yes'>"; message += " <td style='padding:11.25pt 0cm 0cm 0cm'>"; message += " <p class='MsoNormal' align='center' style='text-align:center'><span style='font-size:8.5pt;font-family:"Verdana","sans-serif";mso-fareast-font-family:"; message += " "Times New Roman";color:#666666'>Se você possui filtro antispam habilitado em"; message += " sua caixa postal, autorize o e-mail<br>"; message += " <a href='" + email + "'><span style='color:#990000'>" + email + "</span></a>"; message += " para continuar recebendo nossas mensagens <o:p></o:p></span></p>"; message += " </td>"; message += " </tr>"; message += " </tbody></table>"; message += " </div>"; #endregion //message += "<img src='Images\\LogoEmail.png'> "; //AlternateView av1 = AlternateView.CreateAlternateViewFromString( //"<html><body><img src=cid:companylogo/>" + //"<br></body></html>" + message, //null, MediaTypeNames.Text.Html); //now add the AlternateView //av1.LinkedResources.Add(logo); //now append it to the body of the mail //msg.AlternateViews.Add(av1); msg.From = new MailAddress(email); //msg.To.Add(new MailAddress(Para)); msg.Subject = subject; msg.Body = message; msg.IsBodyHtml = true; smtpClient.EnableSsl = false; smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = loginInfo; smtpClient.Send(msg); }