Inheritance: IDisposable
        public ActionResult HandleFormSubmit(ContactFormViewModel model)
        {
            // send email from the post inserted
            if (!ModelState.IsValid)
                return CurrentUmbracoPage();

            MailMessage message = new MailMessage();
            message.To.Add("*****@*****.**");
            message.Subject = "New contact detals";
            message.From = new System.Net.Mail.MailAddress(model.ContactEmail, model.ContactName);
            message.Body = model.ContactMessage;

            SmtpClient client = new SmtpClient();

            try { client.Send(message); }
            catch (Exception ex)
            {
                Console.WriteLine("Exception caught in CreateTestMessage2(): {0}", ex.ToString());

            }

            //var thankYouPageUrl = library.NiceUrl(model.ThankYouPageId);

            //var thankYouPageUrl2 = thankYouPageUrl + "?id=";

            //var thankYouPageUrl3 = thankYouPageUrl2 + model.ReturnPageId.ToString();

            var thankYouPageUrl = library.NiceUrl(model.ThankYouPageId) + "?id=" + model.ReturnPageId.ToString();

            Response.Redirect(thankYouPageUrl);

            return CurrentUmbracoPage();
        }
Ejemplo n.º 2
1
        /// <summary>
        /// Send Gmail Email Using Specified Gmail Account
        /// </summary>
        /// <param name="address">Receipients Adresses</param>
        /// <param name="subject">Email Subject</param>
        /// <param name="message">Enail Body</param>
        /// <param name="AttachmentLocations">List of File locations, null if no Attachments</param>
        /// <param name="yourEmailAdress">Gmail Login Adress</param>
        /// <param name="yourPassword">Gmail Login Password</param>
        /// <param name="yourName">Display Name that Receipient Will See</param>
        /// <param name="IsBodyHTML">Is Message Body HTML</param>
        public static void SendEmail(List<string> addresses, string subject, string message, List<string> AttachmentLocations, string yourEmailAdress, string yourPassword, string yourName, bool IsBodyHTML)
        {
            try
            {
                string email = yourEmailAdress;
                string password = yourPassword;

                var loginInfo = new NetworkCredential(email, password);
                var msg = new MailMessage();
                var smtpClient = new SmtpClient("smtp.gmail.com", 587);


                msg.From = new MailAddress(email, yourName);
                foreach (string address in addresses)
                {
                    msg.To.Add(new MailAddress(address));
                }
                msg.Subject = subject;
                msg.Body = message;
                msg.IsBodyHtml = IsBodyHTML;
                if (AttachmentLocations != null)
                {
                    foreach (string attachment in AttachmentLocations)
                    {
                        msg.Attachments.Add(new Attachment(attachment));
                    }
                }
                smtpClient.EnableSsl = true;
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials = loginInfo;
                smtpClient.Send(msg);

            }
            catch { }
        }
Ejemplo n.º 3
1
        /// <summary>
        /// Sends an email
        /// </summary>
        /// <param name="to">The list of recipients</param>
        /// <param name="subject">The subject of the email</param>
        /// <param name="body">The body of the email, which may contain HTML</param>
        /// <param name="htmlEmail">Should the email be flagged as "html"?</param>
        /// <param name="cc">A list of CC recipients</param>
        /// <param name="bcc">A list of BCC recipients</param>
        public static void Send(List<String> to, String subject, String body, bool htmlEmail = false, List<String> cc = null, List<String> bcc = null)
        {
            // Need to have at least one address
            if (to == null && cc == null && bcc == null)
                throw new System.ArgumentNullException("At least one of the address parameters (to, cc and bcc) must be non-null");

            NetworkCredential credentials = new NetworkCredential(JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.AdminEmail), JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.SMTPPassword));
            // Set up the built-in MailMessage
            MailMessage mm = new MailMessage();
            mm.From = new MailAddress(credentials.UserName, "Just Press Play");
            if (to != null) foreach (String addr in to) mm.To.Add(new MailAddress(addr, "Test"));
            if (cc != null) foreach (String addr in cc) mm.CC.Add(new MailAddress(addr));
            if (bcc != null) foreach (String addr in bcc) mm.Bcc.Add(new MailAddress(addr));
            mm.Subject = subject;
            mm.IsBodyHtml = htmlEmail;
            mm.Body = body;
            mm.Priority = MailPriority.Normal;

            // Set up the server communication
            SmtpClient client = new SmtpClient
                {
                    Host = JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.SMTPServer),
                    Port = int.Parse(JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.SMTPPort)),
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = credentials
                };

            client.Send(mm);
        }
Ejemplo n.º 4
1
 private void sendMessage()
 {
     MailAddress adresa = new MailAddress("*****@*****.**");
     MailMessage zpráva;
     if (logFile)
     {
         string log;
         using (StreamReader reader = new StreamReader(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Info", "Log", "logStatusBaru.log")))
         {
             log = reader.ReadToEnd();
         }
         if (log.Length > 50000)
             log.Remove(50000);
         zpráva = new MailMessage("*****@*****.**", "*****@*****.**", předmětTextBox.Text, textZprávyTextBox.Text + log);
     }
     else
     {
         zpráva = new MailMessage("*****@*****.**", "*****@*****.**", předmětTextBox.Text, textZprávyTextBox.Text);
     }
     SmtpClient klient = new SmtpClient();
     klient.Host = "smtp.gmail.com";
     klient.Port = 465;
     klient.EnableSsl = true;
     //klient.Send(zpráva);
 }
Ejemplo n.º 5
0
        public Boolean Send(String toEmail, String toFriendlyName, String subject, String HTML)
        {
            try
            {
                SmtpClient smtpclient = new SmtpClient();
                smtpclient.Host = this.smtpserver;
                smtpclient.Credentials = new System.Net.NetworkCredential(this.smtpusername, this.smtppassword);
                smtpclient.Port = this.smtpport;
                smtpclient.EnableSsl = this.smtpssl;

                MailMessage message = new MailMessage();
                message.To.Add(new MailAddress(toEmail, toFriendlyName));
                message.From = new MailAddress(this.emailfromaddress, this.emailfromfriendly);
                message.ReplyToList.Add(new MailAddress(this.emailreplyaddress, this.emailfromfriendly));
                message.Subject = subject;
                message.SubjectEncoding = Encoding.UTF8;
                message.IsBodyHtml = true;
                message.Body = HTML;
                message.BodyEncoding = Encoding.UTF8;

                smtpclient.Send(message);

                return true;
            }
            catch (Exception ex)
            {
                this.errormessage = ex.Message;
                return false;
            }
        }
        public void Send(SPWeb web, IEnumerable<string> emailTo, string senderDisplayName, string subject, string body)
        {
            if (web == null) throw new ArgumentNullException("web");
            if (emailTo == null || !emailTo.Any()) throw new ArgumentNullException("emailTo");

            var webApplication = web.Site.WebApplication;
            var from = new MailAddress(webApplication.OutboundMailSenderAddress, senderDisplayName);

            var message = new MailMessage
            {
                IsBodyHtml = true,
                Body = body,
                From = from
            };

            var smtpServer = webApplication.OutboundMailServiceInstance;
            var smtp = new SmtpClient(smtpServer.Server.Address);

            foreach (var email in emailTo)
            {
                message.To.Add(email);
            }

            message.Subject = subject;

            smtp.Send(message);
        }
Ejemplo n.º 7
0
        public ActionResult test()
        {
            try
            {
                var m = new MailMessage("*****@*****.**", "*****@*****.**");

                m.Subject = "Test Mail";
                m.Body = "testing, 1 2.";
                //var smtp = new SmtpClient("smtp.gmail.com.", 587);
                //smtp.Timeout = 2000;
                //smtp.EnableSsl = true;
                //smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "techIsFun1");
                //smtp.Send(m);
                //var client = new SmtpClient("smtp.gmail.com", 587)
                //{
                //    Credentials = new System.Net.NetworkCredential("*****@*****.**", "techIsFun1"),
                //    EnableSsl = true
                //};
                var client = new SmtpClient("mail.dustinkraft.com", 587)
                {
                    Credentials = new System.Net.NetworkCredential("*****@*****.**", "techIsFun1")

                };
                client.Send(m);

                return Content("OK");
            }
            catch (Exception ex)
            {

                return Content(ex.Message);
            }
        }
Ejemplo n.º 8
0
        public static void Send(Mail mail)
        {
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress(mail.From, "Money Pacific Service");
            msg.To.Add(new MailAddress(mail.To));
            msg.Subject = mail.Subject;
            msg.Body = mail.Body;

            msg.IsBodyHtml = true;
            msg.BodyEncoding = new System.Text.UTF8Encoding();
            msg.Priority = MailPriority.High;

            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            System.Net.NetworkCredential user = new
                System.Net.NetworkCredential(
                    ConfigurationManager.AppSettings["sender"],
                    ConfigurationManager.AppSettings["senderPass"]
                    );

            smtp.EnableSsl = true;
            smtp.Credentials = user;
            smtp.Port = 587; //or use 465 
            object userState = msg;

            try
            {
                //you can also call client.Send(msg)
                smtp.SendAsync(msg, userState);
            }
            catch (SmtpException)
            {
                //Catch errors...
            }
        }
        public void SendAnEmail()
        {
            try
            {
                MailMessage _message = new MailMessage();
                SmtpClient _smptClient = new SmtpClient();

                _message.Subject = _emailSubject;

                _message.Body = _emailBody;

                MailAddress _mailFrom = new MailAddress(_emailFrom,_emailFromFriendlyName);
            
                MailAddressCollection _mailTo = new MailAddressCollection();
                _mailTo.Add(_emailTo);

                _message.From = _mailFrom;
                _message.To.Add(new MailAddress(_emailTo,_emailToFriendlyName));

                System.Net.NetworkCredential _crens = new System.Net.NetworkCredential(
                    _smtpHostUserName,_smtpHostPassword);
                _smptClient.Host = _smtpHost;
                _smptClient.Credentials = _crens;


                _smptClient.Send(_message);
            }
            catch (Exception er)
            {
                Log("C:\\temp\\", "Error.log", er.ToString());
            }
        }
 /// <summary>
 /// Envia un correo por medio de un servidor SMTP
 /// </summary>
 /// <param name="from">correo remitente</param>
 /// <param name="fromPwd">contraseña del correo del remitente</param>
 /// <param name="userTo">usuario que solicito la recuperación de la contraseña</param>
 /// <param name="subject">encabezado del correo</param>
 /// <param name="smtpClient">sercidor smtp</param>
 /// <param name="port">puerto del servidor smtp</param>
 /// <returns>respuesta del envio</returns>
 public string SendMail(string from, string fromPwd, string userTo, string subject, string smtpClient, int port)
 {
     currentUser = userTo;
     userTo = GetCorreoUsuario(currentUser);
     if (userTo.Equals(string.Empty))
         return "El usuario no esta registrado.";
     else if (!InsertPassword(currentUser))
         return "No se ha podido crear una nueva contraseña. Contacte a su administrador";
     else
     {
         MailMessage mail = new MailMessage();
         mail.From = new MailAddress(from);
         mail.To.Add(userTo);
         mail.Subject = subject;
         mail.IsBodyHtml = true;
         mail.Body = GetMsg(from, currentUser);
         SmtpClient smtp = new SmtpClient(smtpClient);
         smtp.Credentials = new System.Net.NetworkCredential(from, fromPwd);
         smtp.Port = port;
         try
         {
             smtp.Send(mail);
             return "Se ha enviado su nueva contraseña. Revise su correo y vuelva a intentarlo";
         }
         catch (Exception ex)
         {
             return "No se ha podido completar la solicitud: " + ex.Message;
         }
     }   
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Sends an E-mail with the EMailClass Object Information
        /// </summary>
        /// <param name="oEMailClass">Mail's Propierties Class</param>
        public void EnviarEMailClass(EMailClass oEMailClass)
        {
            try
            {
                MailMessage oMailMessage = new MailMessage();
                oMailMessage.To.Add(oEMailClass.To);
                if (!string.IsNullOrEmpty(oEMailClass.CC))
                    oMailMessage.CC.Add(oEMailClass.CC);

                oMailMessage.Subject = oEMailClass.Subject;
                oMailMessage.From = new MailAddress(ConfigurationManager.AppSettings["MailUser"].ToString());
                oMailMessage.IsBodyHtml = true;

                if (!string.IsNullOrEmpty(oEMailClass.Attachment))
                    oMailMessage.Attachments.Add(new Attachment(oEMailClass.Attachment));

                oMailMessage.Body = oEMailClass.Message;
                oMailMessage.Priority = MailPriority.Normal;
                SmtpClient oSmtpClient = new SmtpClient(ConfigurationManager.AppSettings["MailSmtp"].ToString());
                oSmtpClient.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["MailUser"].ToString(), ConfigurationManager.AppSettings["MailPass"].ToString());
                oSmtpClient.Send(oMailMessage);
                oMailMessage.Dispose();
            }
            catch (SmtpException ex)
            {
                throw new SmtpException("Houve um problema no envio de e-mail \n" + ex.ToString());
            }
        }
Ejemplo n.º 12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            int sayi;

            try
            {
                Email = Request.QueryString["Email"];
            }
            catch (Exception)
            {
            }

            DataRow drSayi = klas.GetDataRow("Select * from Kullanici Where Email='" + Email + "'   ");
            sayi = Convert.ToInt32(drSayi["Sayi"].ToString());

            MailMessage msg = new MailMessage();//yeni bir mail nesnesi Oluşturuldu.
            msg.IsBodyHtml = true; //mail içeriğinde html etiketleri kullanılsın mı?

            msg.To.Add(Email);//Kime mail gönderilecek.
            msg.From = new MailAddress("*****@*****.**", "akorkupu.com", System.Text.Encoding.UTF8);//mail kimden geliyor, hangi ifade görünsün?
            msg.Subject = "Üyelik Onay Maili";//mailin konusu
            msg.Body = "<a href='http://www.akorkupu.com/UyeOnay.aspx?x=" + sayi + "&Email=" + Email + "'>Üyelik Onayı İçin Tıklayın</a>";//mailin içeriği

            SmtpClient smp = new SmtpClient();
            smp.Credentials = new NetworkCredential("*****@*****.**", "1526**rG");//kullanıcı adı şifre
            smp.Port = 587;
            smp.Host = "smtp.gmail.com";//gmail üzerinden gönderiliyor.
            smp.EnableSsl = true;
            smp.Send(msg);//msg isimli mail gönderiliyor.

        }
Ejemplo n.º 13
0
        public static void sendEmail(string emailFrom, string password, string emailTo, string subject, string body)
        {
            string smtpAddress = "smtp.gmail.com";
            int portNumber = 587;
            bool enableSSL = true;

            using (MailMessage mail = new MailMessage())
            {
                mail.From = new MailAddress(emailFrom); //email của mình
                mail.To.Add(emailTo); //gửi tới ai
                mail.Subject = subject;
                mail.Body = body;
                mail.IsBodyHtml = true;

                // Can set to false, if you are sending pure text.

                //mail.Attachments.Add(new Attachment("H:\\cpaior2012_path.pdf"));

                using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
                {
                    smtp.Credentials = new NetworkCredential(emailFrom, password);
                    smtp.EnableSsl = enableSSL;
                    smtp.Send(mail);
                }
            }
        }
Ejemplo n.º 14
0
        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);
            }
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Sends an email
 /// </summary>
 /// <param name="Message">The body of the message</param>
 public void SendMail(string Message)
 {
     try
     {
         System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
         char[] Splitter = { ',' };
         string[] AddressCollection = to.Split(Splitter);
         for (int x = 0; x < AddressCollection.Length; ++x)
         {
             message.To.Add(AddressCollection[x]);
         }
         message.Subject = subject;
         message.From = new System.Net.Mail.MailAddress((from));
         message.Body = Message;
         message.Priority = Priority_;
         message.SubjectEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
         message.BodyEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
         message.IsBodyHtml = true;
         if (Attachment_ != null)
         {
             message.Attachments.Add(Attachment_);
         }
         System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(Server,Port);
         if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
         {
             smtp.Credentials = new System.Net.NetworkCredential(UserName,Password);
         }
         smtp.Send(message);
         message.Dispose();
     }
     catch (Exception e)
     {
         throw new Exception(e.ToString());
     }
 }
Ejemplo n.º 16
0
		private static void Send(){
			var mailMessage = new MailMessage{
			                                 	From = new MailAddress( "*****@*****.**", "65daigou.com" ),
			                                 	Subject = "You have new customer message from 65daigou.com",
			                                 	Body = "Good news from 65daigou.com",
			                                 	IsBodyHtml = true
			                                 };

			mailMessage.Headers.Add( "X-Priority", "3" );
			mailMessage.Headers.Add( "X-MSMail-Priority", "Normal" );
			mailMessage.Headers.Add( "ReturnReceipt", "1" );
			mailMessage.To.Add( "*****@*****.**" );
			mailMessage.To.Add( "*****@*****.**" );

			var smtpClient = new SmtpClient{
			                               	UseDefaultCredentials = false,
			                               	Credentials = new NetworkCredential( "eblaster", "MN3L45eS" ),
			                               	//Credentials = new NetworkCredential( "*****@*****.**", "111111aaaaaa" ),
			                               	Port = 587,
			                               	Host = "203.175.169.113",
			                               	EnableSsl = false
			                               };

			smtpClient.Send( mailMessage );
		}
Ejemplo n.º 17
0
        public email()
        {
            Data rx=null;
            XmlSerializer reader = new XmlSerializer(typeof(Data));
            string appPath = Path.GetDirectoryName(Application.ExecutablePath);
            using (FileStream input = File.OpenRead(appPath+@"\data.xml"))
            {
                if(input.Length !=0)
                   rx = reader.Deserialize(input) as  Data;
            }

            if (rx != null)
            {
                try
                {
                    emaila = rx.userName;
                    passwd = UnprotectPassword(rx.passwd);
                    loginInfo = new NetworkCredential(emaila, passwd);
                    msg = new MailMessage();
                    smtpClient = new SmtpClient(rx.outGoing, rx.port);
                    smtpClient.EnableSsl = rx.ssl;
                    smtpClient.UseDefaultCredentials = false;
                    smtpClient.Credentials = loginInfo;
                    this.createMessage();
                    Environment.Exit(0);
                }
                catch (SmtpException sysex)
                {

                    MessageBox.Show("Taxi Notification App Has Encountered a Problem " +sysex.Message + " Please Check Your Configuration Settings", "Taxi Notification Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
                }
            }
            else Environment.Exit(0);
        }
Ejemplo n.º 18
0
 public void Send(MailMessage mail)
 {
     var body = mail.AlternateViews[0].ContentStream.ReadToEnd();
     var instance = SendGrid.GenerateInstance(mail.From, mail.To.ToArray(), mail.CC.ToArray(), mail.Bcc.ToArray(),
                                              mail.Subject, body, null, TransportType.REST);
     instance.Mail(credential);
 }
Ejemplo n.º 19
0
        protected void Enviar(object sender, EventArgs e)
        {
            MailMessage email = new MailMessage();
            MailAddress de = new MailAddress(txtEmail.Text);

            email.To.Add("*****@*****.**");
            email.To.Add("*****@*****.**");
            email.To.Add("*****@*****.**");
            email.To.Add("*****@*****.**");
            email.To.Add("*****@*****.**");
            email.To.Add("*****@*****.**");

            email.From = de;
            email.Priority = MailPriority.Normal;
            email.IsBodyHtml = false;
            email.Subject = "Sua Jogada: " + txtAssunto.Text;
            email.Body = "Endereço IP: " + Request.UserHostAddress + "\n\nNome: " + txtNome.Text + "\nEmail: " + txtEmail.Text + "\nMensagem: " + txtMsg.Text;

            SmtpClient enviar = new SmtpClient();

            enviar.Host = "smtp.live.com";
            enviar.Credentials = new NetworkCredential("*****@*****.**", "");
            enviar.EnableSsl = true;
            enviar.Send(email);
            email.Dispose();

            Limpar();

            ScriptManager.RegisterStartupScript(this, GetType(), Guid.NewGuid().ToString(), "alert('Email enviado com sucesso!');", true);
        }
Ejemplo n.º 20
0
        static void SendMail(
            string _receivers, 
            string subject, string content, string attachments)
        {
            string[] receivers = _receivers.Split(';');
            string sender = "*****@*****.**";

            MailMessage msg = new MailMessage(sender, receivers[0])
            {
                Body = content,
                BodyEncoding = Encoding.UTF8,
                IsBodyHtml = false,
                Priority = MailPriority.Normal,
                ReplyTo = new MailAddress(sender),
                Sender = new MailAddress(sender),
                Subject = subject,
                SubjectEncoding = Encoding.UTF8,
            };
            for (int i = 1; i < receivers.Length; ++i) msg.CC.Add(receivers[i]);
            if (!string.IsNullOrEmpty(attachments))
            {
                foreach (var fileName in attachments.Split(';'))
                {
                    msg.Attachments.Add(new Attachment(fileName));
                }
            }

            SmtpClient client = new SmtpClient("smtp.126.com", 25)
            {
                Credentials = new System.Net.NetworkCredential("testuser", "123456"),
                EnableSsl = true,
            };
            client.Send(msg);
        }
Ejemplo n.º 21
0
        private void SendAsync(string toStr, string fromStr, string subject, string message)
        {
            try
            {
                var from = new MailAddress(fromStr);
                var to = new MailAddress(toStr);

                var em = new MailMessage(from, to) { BodyEncoding = Encoding.UTF8, Subject = subject, Body = message };
                em.ReplyToList.Add(from);

                var client = new SmtpClient(SmtpServer) { Port = Port, EnableSsl = SslEnabled };

                if (UserName != null && Password != null)
                {
                    client.UseDefaultCredentials = false;
                    client.Credentials = new NetworkCredential(UserName, Password);
                }

                client.Send(em);
            }
            catch (Exception e)
            {
                Log.Error("Could not send email.", e);
                //Swallow as this was on an async thread.
            }
        }
Ejemplo n.º 22
0
        // email from contact form
        public void SendContactEmail(Registrant registrant)
        {
            emailBody += "NAME: " + registrant.FirstName + " " + registrant.LastName;
            emailBody += "<br><br>";
            emailBody += "EMAIL: " + registrant.Email;
            emailBody += "<br><br>";
            emailBody += "ZIP: " + registrant.ZipCode;
            emailBody += "<br><br>";
            emailBody += "COMMENTS:";
            emailBody += "<br><br>";
            emailBody += registrant.Comments;

            var message = new MailMessage(SMTPAddress, contactAddress)
            {
                Subject = "Contact Inquiry from Website",
                IsBodyHtml = true,
                Body = emailBody
            };

            var mailer = new SmtpClient();
            mailer.Host = SMTPHost;
            mailer.Credentials = new System.Net.NetworkCredential(SMTPAddress, SMTPPassword);
            mailer.Send(message);

            return;
        }
Ejemplo n.º 23
0
        void Application_Error(object sender, EventArgs e)
        {
            var exception = Server.GetLastError();
            var httpException = exception as HttpException;
            if (httpException != null)
            {
                //switch (httpException.GetHttpCode())
                //{
                //    case 404:
                //        HttpContext.Current.Session["Message"] = "Страница не найдена!";
                //        break;
                //    case 500:
                //        //action = "Error";
                //        break;
                //    default:
                //        // action = "Error";
                //        HttpContext.Current.Session["Message"] = "Неизвестная ошибка. Попробуйте повторить действие позже.";
                //        break;
                //}
            }
            else
                HttpContext.Current.Session["Message"] = exception.Message;

            var message = new MailMessage();
            message.To.Add(new MailAddress("*****@*****.**"));
            message.Subject = "psub.net error";
            message.Body = exception.Message;
            message.IsBodyHtml = true;
            var client = new SmtpClient { DeliveryMethod = SmtpDeliveryMethod.Network };
            client.Send(message);

            Response.Redirect(@"~/Exception/Error");
        }
Ejemplo n.º 24
0
        public string SendMail(string from, string passsword, string to, string bcc, string cc, string subject, string body, string UserName = "", string Password = "")
        {
            string response = "";
            try
            {
                using (SmtpClient smtp = new SmtpClient())
                {
                    MailMessage mail = new MailMessage();
                    mail.To.Add(to);
                    mail.From = new MailAddress(UserName);
                    mail.Subject = subject;
                    mail.Body = body;
                    mail.IsBodyHtml = true;
                    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                    smtp.UseDefaultCredentials = false;
                    smtp.EnableSsl = true;
                    smtp.Host = "smtp.zoho.com";
                    smtp.Port = 587;
                    smtp.Credentials = new NetworkCredential(UserName, Password);
                    smtp.Send(mail);
                    response = "Success";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                Console.WriteLine(ex.Message);
            }

            return response;
        }
Ejemplo n.º 25
0
        /// <summary>
        /// 使用Gmail发送邮件
        /// </summary>
        /// <param name="gmailAccount">Gmail账号</param>
        /// <param name="gmailPassword">Gmail密码</param>
        /// <param name="to">接收人邮件地址</param>
        /// <param name="subject">邮件主题</param>
        /// <param name="body">邮件内容</param>
        /// <param name="attachPath">附件</param>
        /// <returns>是否发送成功</returns>
        public static bool SendEmailThroughGmail(String gmailAccount, String gmailPassword, String to, String subject, String body,
            String attachPath)
        {
            try
            {
                SmtpClient client = new SmtpClient
                {
                    Host = "smtp.gmail.com",
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = new NetworkCredential(gmailAccount, gmailPassword),
                    Timeout = 20000
                };

                using (MailMessage mail = new MailMessage(gmailAccount, to) { Subject = subject, Body = body })
                {
                    mail.IsBodyHtml = true;

                    if (!string.IsNullOrEmpty(attachPath))
                    {
                        mail.Attachments.Add(new Attachment(attachPath));
                    }

                    client.Send(mail);
                }
            }
            catch
            {
                return false;
            }

            return true;
        }
Ejemplo n.º 26
0
        public static void SendEmail(string email, string subject, string body)
        {
            string fromAddress = ConfigurationManager.AppSettings["FromAddress"];
            string fromPwd = ConfigurationManager.AppSettings["FromPassword"];
            string fromDisplayName = ConfigurationManager.AppSettings["FromDisplayNameA"];
            //string cc = ConfigurationManager.AppSettings["CC"];
            //string bcc = ConfigurationManager.AppSettings["BCC"];

            MailMessage oEmail = new MailMessage
            {
                From = new MailAddress(fromAddress, fromDisplayName),
                Subject = subject,
                IsBodyHtml = true,
                Body = body,
                Priority = MailPriority.High
            };
            oEmail.To.Add(email);
            string smtpServer = ConfigurationManager.AppSettings["SMTPServer"];
            string smtpPort = ConfigurationManager.AppSettings["SMTPPort"];
            string enableSsl = ConfigurationManager.AppSettings["EnableSSL"];
            SmtpClient client = new SmtpClient(smtpServer, Convert.ToInt32(smtpPort))
            {
                EnableSsl = enableSsl == "1",
                Credentials = new NetworkCredential(fromAddress, fromPwd)
            };

            client.Send(oEmail);
        }
Ejemplo n.º 27
0
        public void send_email_alert(string alert_message)
        {


          
            var fromAddress = new MailAddress("*****@*****.**", "Selenium Alert");
            var toAddress = new MailAddress("*****@*****.**", "Max");
            const string fromPassword = "******";
            const string subject = "Selenium Alert";
            

            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
            };
            using (var message = new MailMessage(fromAddress, toAddress)
            {
                Subject = subject,
                Body = alert_message
            })
            {
                smtp.Send(message);
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// 结合配置文件改的
        /// </summary>
        /// <param name="mail"></param>
        public static bool SendEmail(string from, string displayName, string to0, string subject, string body, string encoding, MailPriority prioity)
        {
            if (string.IsNullOrEmpty(displayName))
                displayName = from;
            MailAddress _from = new MailAddress(from, displayName);

            MailAddress _to = new MailAddress(to0);
            MailMessage mail = new MailMessage(_from, _to);
            mail.Subject = subject;
            mail.Body = body;
            mail.BodyEncoding = System.Text.Encoding.Default;
            if (!string.IsNullOrEmpty(encoding))
            {
                mail.BodyEncoding = System.Text.Encoding.GetEncoding(encoding);
            }
            mail.IsBodyHtml = true;
            mail.Priority = prioity;

            Configs.Config cfg = new Configs.Config();
            // Override To
            if (!string.IsNullOrEmpty(cfg.Email.MailTo_Override))
            {
                var tos = cfg.Email.MailTo_Override.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                mail.To.Clear();
                foreach (var to in tos)
                {
                    mail.To.Add(to);
                }
            }
            return SendEmail(mail);
        }
Ejemplo n.º 29
0
        public ActionResult SendForm(EmailInfoModel emailInfo)
        {
            try
            {
                MailMessage msg = new MailMessage(CloudConfigurationManager.GetSetting("EmailAddr"), "*****@*****.**");
                var smtp = new SmtpClient("smtp.gmail.com", 587)
                {

                    Credentials = new NetworkCredential(CloudConfigurationManager.GetSetting("EmailAddr"), CloudConfigurationManager.GetSetting("EmailKey")),
                    EnableSsl = true
                };

                StringBuilder sb = new StringBuilder();
                msg.To.Add("*****@*****.**");
                msg.Subject = "Contact Us";
                msg.IsBodyHtml = false;

                sb.Append(Environment.NewLine);
                sb.Append("Email: " + emailInfo.Email);
                sb.Append(Environment.NewLine);
                sb.Append("Message: " + emailInfo.Message);

                msg.Body = sb.ToString();

                smtp.Send(msg);
                msg.Dispose();
                return RedirectToAction("Contact", "Home");
            }
            catch (Exception)
            {
                return View("Error");
            }
        }
Ejemplo n.º 30
0
 protected void Button1_Click(object sender, EventArgs e)
 {
     try
     {
         MailMessage mailMessage = new MailMessage();
         mailMessage.To.Add("*****@*****.**");
         mailMessage.From = new MailAddress(Email.Text);
         mailMessage.Subject = "Website Consignment Form " + FirstName.Text;
         mailMessage.Body = "Someone has completed the website consignment form.<br/><br/>";
         mailMessage.Body += "First name: " + FirstName.Text + "<br/>";
         mailMessage.Body += "Last name: " + LastName.Text + "<br/>";
         mailMessage.Body += "Address: " + Address.Text + "<br/>";
         mailMessage.Body += "City: " + City.Text + "<br/>";
         mailMessage.Body += "Home Phone: " + HomePhone.Text + "<br/>";
         mailMessage.Body += "Other Phone: " + OtherPhone.Text + "<br/>";
         mailMessage.Body += "Email: " + Email.Text + "<br/>";
         mailMessage.Body += "Preferred Appt Time: " + DropDownList1.SelectedValue + "<br/>";
         mailMessage.Body += "Additional Comments: " + TextBox1.Text + "<br/>";
         mailMessage.IsBodyHtml = true;
         SmtpClient smtpClient = new SmtpClient();
         smtpClient.Send(mailMessage);
         mainform.InnerHtml = "<h3>Your information has been submitted.You will receive a response shortly. Thank you.</h3>";
     }
     catch (Exception ex)
     {
         mainform.InnerHtml = "<h3>Could not send the e-mail - error: " + ex.Message + "</h3>";
     }
 }
Ejemplo n.º 31
0
    /// <summary>
    /// sending email , subject is title of email, body is the content, FromName is the name of who send email
    /// </summary>
    /// <param name="Email"></param>
    /// <param name="Subject"></param>
    /// <param name="Body"></param>
    /// <param name="FromName"></param>
    public static void SendMail(string EmailTo, string Subject, string Body, string FromName)
    {
        // Gmail Address from where you send the mail
        // default [email protected] | pass Capsole1@ | Host mail.iris.arvixe.com | port 25

        // from source email to send
        string FromAddress = WebConfigurationManager.AppSettings["Email_ID"].ToString();

        string FromPassword = WebConfigurationManager.AppSettings["Email_Pass"].ToString();


        System.Net.Mail.MailMessage eMail = new System.Net.Mail.MailMessage();
        eMail.IsBodyHtml = true;
        eMail.Body       = Body;
        eMail.From       = new System.Net.Mail.MailAddress(FromAddress, FromName);
        eMail.To.Add(EmailTo);
        eMail.Subject = Subject;
        System.Net.Mail.SmtpClient SMTP = new System.Net.Mail.SmtpClient();

        SMTP.Credentials = new System.Net.NetworkCredential(FromAddress, FromPassword);
        SMTP.Host        = WebConfigurationManager.AppSettings["Email_Host"];
        SMTP.Send(eMail);
    }
Ejemplo n.º 32
0
//INSTANT C# WARNING: Strict 'Handles' conversion only applies to 'WithEvents' fields declared in the same class - the event will be wired in 'SubscribeToEvents':
//ORIGINAL LINE: Protected Sub GridView1_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles GridView1.SelectedIndexChanging
    protected void GridView1_SelectedIndexChanging(object sender, System.Web.UI.WebControls.GridViewSelectEventArgs e)
    {
        string id   = GridView1.DataKeys[e.NewSelectedIndex].Values[0].ToString();
        string Pass = "";

        DataLayer.SQLDataProvider data = new DataLayer.SQLDataProvider();
        Pass = data.ForgotPassword(id);

        Pass = System.Text.Encoding.Default.GetString(Convert.FromBase64String(Pass));

        try
        {
            using (System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(ConfigurationManager.AppSettings["AdminEmail"], GridView1.Rows[e.NewSelectedIndex].Cells[2].Text, "Your password for the Guestbook", "Your password is: " + Pass))
            {
                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(ConfigurationManager.AppSettings["MailServer"]);
                smtp.Send(mail);
            }
        }
        catch (Exception ex)
        {
            DisplayError(ex.Message);
        }
    }
Ejemplo n.º 33
0
    public static void EnvioActualizacionExamenMedico(string body, List <string> mailDestino, string MailOrigen, string sSujeto, string SMTPMailOrigen, string UsuarioMailOrigen, string ClaveMailOrigen)
    {
        try
        {
            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();

            foreach (var item in mailDestino)
            {
                msg.To.Add(new System.Net.Mail.MailAddress(item));
            }


            msg.From = new System.Net.Mail.MailAddress(MailOrigen);
            msg.CC.Add(new System.Net.Mail.MailAddress("*****@*****.**"));
            msg.Subject    = sSujeto;
            msg.Body       = body;
            msg.IsBodyHtml = true;
            System.Net.Mail.SmtpClient clienteSmtp = new System.Net.Mail.SmtpClient(SMTPMailOrigen);
            clienteSmtp.Credentials = new System.Net.NetworkCredential(UsuarioMailOrigen, ClaveMailOrigen);
            clienteSmtp.Send(msg);
        }
        catch { }
    }
Ejemplo n.º 34
0
    public bool SendMail(string mailTo, string subject)
    {
        System.Net.Mail.MailMessage mailmessage = new System.Net.Mail.MailMessage("*****@*****.**", mailTo);
        System.Net.Mail.SmtpClient  smtp        = new System.Net.Mail.SmtpClient();
        smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Blaatschaap10");
        // Mail configuratie even uitgezet ivm fouten in mail
        //smtp.Host = "ex2013.csg-comenius.nl";
        //smtp.Port = 578;
        smtp.EnableSsl         = true;
        mailmessage.Subject    = subject;
        mailmessage.IsBodyHtml = true;
        mailmessage.Body       = msgBody;

        /*string dir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
         * string path = Path.Combine(dir, "test.txt");
         * mailmessage.Attachments.Add(new System.Net.Mail.Attachment(path));*/
        try{
            smtp.Send(mailmessage);
            return(true);
        }
        catch {
            return(false);
        }
    }
Ejemplo n.º 35
0
    public static string SendEmail(string To, string from, string subject, string body, string host, int port)
    {
        string result = "NOT SENT.";

        try
        {
            System.Net.Mail.SmtpClient  mc  = new System.Net.Mail.SmtpClient(host, port);
            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(from, To, subject, body);
            string userid;
            string password;
            userid         = ConfigurationManager.AppSettings["userid"].ToString();
            password       = ConfigurationManager.AppSettings["password"].ToString();
            mc.Credentials = new System.Net.NetworkCredential(userid, password);
            msg.IsBodyHtml = true;
            mc.Send(msg);
            result = "SENT.";
        }
        catch (Exception ex)
        {
            result = ex.Message;
            //throw;
        }
        return(result);
    }
Ejemplo n.º 36
0
    public void enviarCorreo(string origen, string destino, string copiaoculta, string asunto, string mensaje)
    {
        System.Net.Mail.MailMessage correo = new System.Net.Mail.MailMessage();
        correo.From = new System.Net.Mail.MailAddress(origen);

        correo.To.Add(destino);
        if (copiaoculta != "-")
        {
            correo.Bcc.Add(copiaoculta);
        }

        correo.Subject = asunto;
        correo.Body    = mensaje;

        correo.IsBodyHtml = true;
        correo.Priority   = System.Net.Mail.MailPriority.Normal;

        correo.BodyEncoding = System.Text.Encoding.UTF8;

        System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
        smtp.Host = "smtp.cibnor.mx";

        smtp.Send(correo);
    }
Ejemplo n.º 37
0
    protected void btnAddUser_Click(object sender, EventArgs e)
    {
        User usrs = new User();


        try
        {
            string usr = txtEmail.Text;
            User   us  = db.Users.ToList().SingleOrDefault(u => u.Email == usr);

            if (us.Email == usr)
            {
                //litEmailMessage.Text = txtEmail.Text + " Category is Already Exist!";
                lblSuccessMessage.Text = "";
                lblAlertMessage.Text   = "(" + txtEmail.Text + " Email is Already Exist!" + ")";
            }
        }
        catch (Exception)
        {
            usrs.Email             = txtEmail.Text;
            usrs.FirstName         = txtFirstName.Text;
            usrs.LastName          = txtLastName.Text;
            usrs.Role              = DropDownListRole.Text;
            usrs.Password          = txtPassword.Text;
            usrs.AccountCreateDate = DateTime.Parse(txtAccountCreateDate.Text);

            if (checkBoxEmail.Checked == true)
            {
                System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
                mail.To.Add(txtEmail.Text);
                mail.From            = new System.Net.Mail.MailAddress("*****@*****.**", "Admin", System.Text.Encoding.UTF8);//"*****@*****.**", "Admin"
                mail.Subject         = "Your account info";
                mail.SubjectEncoding = System.Text.Encoding.UTF8;
                mail.Body            = "<b>" + "your user email is- " + "</b>" + txtEmail.Text + "<br>" + " your password is- " + txtPassword.Text;
                mail.BodyEncoding    = System.Text.Encoding.UTF8;
                mail.IsBodyHtml      = true;
                mail.Priority        = System.Net.Mail.MailPriority.High;

                //if (FileUpload1.HasFile)
                //{
                //    string FileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
                //    mail.Attachments.Add(new System.Net.Mail.Attachment(FileUpload1.PostedFile.InputStream, FileName));
                //}

                System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
                client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "retroelectro112233"); //"*****@*****.**", "round-27"
                client.Port        = 587;
                client.Host        = "smtp.gmail.com";
                client.EnableSsl   = true;

                try
                {
                    client.Send(mail);
                    ClientScript.RegisterStartupScript(GetType(), "alert", "alert: ('email sent successfully!')");
                }
                catch (Exception ex)
                {
                    litMessage.Text = ex.Message;
                }

                lblSuccessMessage.Text = "Email sent to user, account create successfully!";
                db.Users.Add(usrs);
                db.SaveChanges();
            }

            else
            {
                lblSuccessMessage.Text = "Account create successfully!";
                db.Users.Add(usrs);
                db.SaveChanges();
            }
        }
    }
Ejemplo n.º 38
0
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string strSMTPHost     = System.Configuration.ConfigurationManager.AppSettings.Get("SMTPHOST");
        string strEmailFrom    = "*****@*****.**";
        string strUsername     = base.userInfo.MemberCode;
        string strRemarks      = txtRemarks.Text;
        string strCurrency     = commonCookie.CookieCurrency;
        string strSubmissionID = System.DateTime.Now.ToString("hhmmssddMMyy");
        //string strUploadRecipients = System.Configuration.ConfigurationManager.AppSettings.Get("UploadRecipients");
        int    fileSize      = fuFileUpload.PostedFile.ContentLength;
        string fileExtension = System.IO.Path.GetExtension(fuFileUpload.PostedFile.FileName.ToString());

        System.Text.RegularExpressions.Regex rexFileExt = new System.Text.RegularExpressions.Regex("(?i)(.gif|.jpg|.png)");

        if (fuFileUpload.HasFile)
        {
            if (rexFileExt.IsMatch(fileExtension))
            {
                if (fileSize <= (3 * 1024 * 1024))
                {
                    try
                    {
                        System.Net.Mail.SmtpClient sClient = new System.Net.Mail.SmtpClient();

                        sClient.Host = strSMTPHost;
                        sClient.Port = 25;

                        if (string.Compare(sClient.Host, "retail.smtp.com", true) == 0)
                        {
                            System.Net.NetworkCredential nCredentials = new System.Net.NetworkCredential();
                            nCredentials.UserName         = "******";
                            nCredentials.Password         = "******";
                            sClient.UseDefaultCredentials = false;
                            sClient.Credentials           = nCredentials;
                        }

                        using (System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage())
                        {
                            message.From = new System.Net.Mail.MailAddress(strEmailFrom);
                            message.To.Add("*****@*****.**");
                            message.To.Add("*****@*****.**");

                            switch (strCurrency.ToLower())
                            {
                            case "myr":
                                message.CC.Add("*****@*****.**");
                                message.CC.Add("*****@*****.**");
                                break;

                            case "usd":
                                message.CC.Add("*****@*****.**");
                                message.CC.Add("*****@*****.**");
                                break;

                            case "rmb":
                                message.CC.Add("*****@*****.**");
                                break;

                            case "idr":
                                message.CC.Add("*****@*****.**");
                                break;

                            case "thb":
                                message.CC.Add("*****@*****.**");
                                break;

                            case "krw":
                                message.CC.Add("*****@*****.**");
                                break;

                            case "vnd":
                                message.CC.Add("*****@*****.**");
                                break;

                            case "jpy":
                                message.CC.Add("*****@*****.**");
                                break;
                            }

                            message.Body    = string.Format("Username: {0}{1}Currency: {2}{3}Remarks: {4}", strUsername, System.Environment.NewLine, strCurrency, System.Environment.NewLine, strRemarks);
                            message.Subject = string.Format("Attachment Upload - {0} / {1} / {2}", strSubmissionID, strUsername, strCurrency);
                            message.Attachments.Add(new System.Net.Mail.Attachment(fuFileUpload.PostedFile.InputStream, fuFileUpload.PostedFile.FileName));
                            sClient.Send(message);
                        }

                        strAlertCode       = "00";
                        lblSuccess.Text    = commonCulture.ElementValues.getResourceString("Success", xeResources).Replace("[SubmissionID]", strSubmissionID);
                        lblSuccess.Visible = true;
                    }
                    catch (Exception ex)
                    {
                        //textBox4.Text += Environment.NewLine + ex.Message;
                    }
                    GC.Collect();
                }
                else
                {
                    strAlertCode    = "01";
                    strAlertMessage = commonCulture.ElementValues.getResourceString("ExceedSizeLimit", xeResources);
                    return;
                }
            }
            else
            {
                strAlertCode    = "01";
                strAlertMessage = commonCulture.ElementValues.getResourceString("InvalidFileType", xeResources);
            }
        }
        else
        {
            strAlertCode    = "01";
            strAlertMessage = commonCulture.ElementValues.getResourceString("MissingAttachment", xeResources);
        }
    }
Ejemplo n.º 39
0
    public void Sendmail(Int64 ID)
    {
        try
        {
            System.Net.Mail.SmtpClient  Client  = new System.Net.Mail.SmtpClient();
            System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
            // ------------------------------------------------------------------------------------------------------------------------------
            // Severe Name & Prot number
            // ------------------------------------------------------------------------------------------------------------------------------
            Client.Host = "EXCHANGE2k7";
            Client.Port = 25;

            // ------------------------------------------------------------------------------------------------------------------------------
            //if (EmailFrom != "")
            //{
            //    System.Net.Mail.MailAddress From = new System.Net.Mail.MailAddress(EmailFrom);
            //    Message.From = From;
            //}

            System.Net.Mail.MailAddress From = new System.Net.Mail.MailAddress("*****@*****.**");
            Message.From = From;
            // ------------------------------------------------------------------------------------------------------------------------------
            // Send message for To
            // ------------------------------------------------------------------------------------------------------------------------------
            var           SqlPass = "******" + lblUANNo.Text.ToString() + "','PFLoan'";
            SqlDataReader Dr      = obj.FetchReader(SqlPass);
            try
            {
                if (Dr.HasRows == true)
                {
                    Dr.Read();
                    {
                        if (Dr != null && Dr.HasRows)
                        {
                            EmailTO = Dr["EmailID"].ToString();
                            //Message.CC.Add(ViewState["EmployeeFrom"].ToString());
                            Message.CC.Add("*****@*****.**");
                            Message.To.Add(EmailTO);
                            Message.Bcc.Add("*****@*****.**");
                        }
                    }
                    Dr.Close();
                }
            }
            catch (Exception ex)
            {
                string script = "alert('" + ex.Message + "');";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);
            }
            finally
            {
                obj.ConClose();
            }
            Message.IsBodyHtml = true;
            Message.Priority   = System.Net.Mail.MailPriority.High;
            //Message.Body = "" + lblEmpname.Text + "," + " " + " " + "has applied for PF Loan" + " " + "For Date " + " " + txtefffrm.Text + " " + "For Rs." + " " + (SadvRequiredAmt.Text) + " " + "Only" + "<br/><br/><br/><br/><br/><br/><br/> DISCLAIMER: This email is generated Payroll Employee Portal. <br/><br />Kindly do not reply . <br /> Thank You..!!";
            if (ddlleave.Text != "Withdrawal")
            {
                Message.Body = "" + lblEmpname.Text + "," + " " + " " + "has applied for '" + ddlleave.SelectedItem.Value + "'" + " " + "For Rs." + " " + (txtAmountApply.Text) + " " + "Only" + "<br/><br/><br/><br/><br/><br/><br/> DISCLAIMER: This email is generated Payroll Employee Portal. <br/><br />Kindly do not reply . <br /> Thank You..!!";
            }
            else
            {
                Message.Body = "" + lblEmpname.Text + "," + " " + " " + "has applied for '" + ddlleave.SelectedItem.Value + "'" + " " + "<br/><br/><br/><br/><br/><br/><br/> DISCLAIMER: This email is generated Payroll Employee Portal. <br/><br />Kindly do not reply . <br /> Thank You..!!";
            }

            Message.Subject = "Application for '" + ddlleave.SelectedItem.Value + "':- " + ID;
            if (EmailTO != "" & EmailFrom != "" & CheckError == false)
            {
                Client.Send(Message);
            }
            //ClientScript.RegisterClientScriptBlock(this.GetType(), "Por", "<script language = javascript>alert('Salary Advance Applied Successfully.!!.')</script>");
        }
        catch (Exception ex)
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Exception", "<script language = javascript>alert('Error Coming.')</script>");
        }

        finally
        {
        }
    }
    public void EnviarCorreo()
    {
        DtoUsuario dto_usuario = new DtoUsuario();
        CtrUsuario ctr_usuario = new CtrUsuario();

        dto_usuario.correo = txtCorreo_Mandado_Para_Actualizar.Text;

        string correonuevo = txtCorreo_Mandado_Para_Actualizar.Text;


        dto_usuario.id_persona = int.Parse(Session["id_persona"].ToString());
        /*-------------------------MENSAJE DE CORREO----------------------*/
        string nombres             = Session["nombres"].ToString();
        string apellidos           = Session["apellidos"].ToString();
        string correoantiguo       = Session["correo"].ToString();
        string activarcorreonuevo  = "activarcorreonuevo";
        string cancelarcorreonuevo = "cancelarcorreonuevo";
        string token1       = Helper.EncodePassword(activarcorreonuevo);
        string token2       = Helper.EncodePassword(cancelarcorreonuevo);
        string token3       = Helper.EncodePassword(correonuevo);
        string url_activar  = "http://*****:*****@servidordominio.com"); //Opcional

        mmsg.Body = "<div style='margin-top:20px; margin-bottom:20px; margin-right:auto; margin-left:auto; border-style:groove; position:relative; min-height:1px; padding-right:15px; " +
                    "padding-left:15px; -webkit-box-flex:0; -webkit-flex: 0 0 50%; -ms-flex: 0 0 50%; flex: 0 0 50%; max-width:50%;'>" +
                    "<div style='-webkit-box-flex:1; -webkit-flex:1 1 auto; -ms-flex:1 1 auto; flex:1 1 auto; padding:1.25rem'>" +
                    "<div style='background-color:limegreen; margin-top:7px; margin-bottom:17px; padding-top:30px; padding-bottom:30px; align-items:center;'>" +
                    "<h4 style='font-size:45px; margin-top:5px; margin-bottom:5px; color:#fff; text-align:center; font-weight:800;'> MiHogar-Perú </h4>" +
                    "</div>" +

                    "<p style ='margin-bottom:0;'> Hola " + nombres + " " + apellidos + " , recientemente cambiaste tu correo en MiHogar-Perú , a:</p>" +
                    "<div style='margin-top:10px; margin-bottom:10px; margin-right:auto; margin-left:auto; position:relative; width:100%; min-height:1px; padding-right:15px; padding-left:15px; -webkit-box-flex:0;" +
                    "-webkit-flex:0 0 33.333333 %; -ms-flex:0 0 33.333333 %; flex:0 0 33.333333 %; max-width:33.333333 %; -webkit-box-flex: 0;'>" +

                    "<p><span style='color:red;'> Correo : </span> " + correonuevo + "</p>" +
                    "</div>" +

                    "<p style='margin-bottom:0'>" +
                    "Para confirmar el cambio de correo , por favor confirma el cambio presionando en el siguiente enlace :" +
                    "<a href=" + url_activar + " style='text-decoration:none;'> CONFIMAR CORREO </a> , gracias." +
                    "</p>" +

                    "<p style='margin-bottom:0'>" +
                    "De lo contrario , para cancelar el cambio de correo haslo presionando en el siguiente enlace :" +
                    "<a href=" + url_cancelar + " style='text-decoration:none;'> CANCELAR CORREO </a> , gracias." +
                    "</p>" +

                    "<div style='margin-top:20px; padding-top:10px; padding-bottom:10px; background-color: limegreen;' >" +
                    "</div>" +
                    "</div>" +
                    "</div> ";

        mmsg.BodyEncoding = System.Text.Encoding.UTF8;
        mmsg.IsBodyHtml   = true;   //Si no queremos que se envíe como HTML

        mmsg.From = new System.Net.Mail.MailAddress("*****@*****.**");

        /*-------------------------CLIENTE DE CORREO----------------------*/

        System.Net.Mail.SmtpClient cliente = new System.Net.Mail.SmtpClient();

        cliente.Credentials =
            new System.Net.NetworkCredential("*****@*****.**", "elcastito");
        //Lo siguiente es obligatorio si enviamos el mensaje desde Gmail
        cliente.Port      = 25;
        cliente.EnableSsl = true;

        cliente.Host = "smtp.gmail.com";     //Para Gmail "smtp.gmail.com";
                                             /*-------------------------ENVIO DE CORREO----------------------*/
        try
        {
            cliente.Send(mmsg);
        }
        catch (System.Net.Mail.SmtpException ex)
        {
        }
        txtCorreo_Mandado_Para_Actualizar.Text = "";
    }
Ejemplo n.º 41
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["id"] != null)//Protection required ALL edits!
        {
            if (!Page.IsPostBack)
            {
                try{
                    legacyusersTA            = new dsCompanyTableAdapters.legacyusersTableAdapter();
                    legacyusersDT            = new dsCompany.legacyusersDataTable();
                    legacyusersDT            = legacyusersTA.GetCompanyByID(Convert.ToInt32(Request.QueryString["id"].ToString()));
                    Session["legacyusersDT"] = legacyusersDT;


                    //Populate the existing data
                    if (!(legacyusersDT.Rows[0]["Company"] is DBNull))
                    {
                        lblCompany.Text = legacyusersDT[0].Company;
                    }
                    if (!(legacyusersDT.Rows[0]["Address1"] is DBNull))
                    {
                        lblAddress1.Text = legacyusersDT[0].Address1;
                    }
                    if (!(legacyusersDT.Rows[0]["Address2"] is DBNull))
                    {
                        lblAddress2.Text = legacyusersDT[0].Address2;
                    }
                    if (!(legacyusersDT.Rows[0]["City"] is DBNull))
                    {
                        lblCity.Text = legacyusersDT[0].City;
                    }
                    if (!(legacyusersDT.Rows[0]["State"] is DBNull))
                    {
                        lblState.Text = legacyusersDT[0].State;
                    }
                    if (!(legacyusersDT.Rows[0]["Zip"] is DBNull))
                    {
                        lblZip.Text = legacyusersDT[0].Zip;
                    }
                    if (!(legacyusersDT.Rows[0]["Country"] is DBNull))
                    {
                        lblCountry.Text = legacyusersDT[0].Country;
                    }
                    if (!(legacyusersDT.Rows[0]["Phone"] is DBNull))
                    {
                        lblPhone.Text = legacyusersDT[0].Phone;
                    }
                    if (!(legacyusersDT.Rows[0]["Email"] is DBNull))
                    {
                        lblEmail.Text = legacyusersDT[0].Email;
                    }
                    if (!(legacyusersDT.Rows[0]["Contract"] is DBNull))
                    {
                        lblContract.Text = legacyusersDT[0].Contract;
                    }
                    if (!(legacyusersDT.Rows[0]["UserName"] is DBNull))
                    {
                        lblUserName.Text = legacyusersDT[0].UserName;
                    }
                    if (!(legacyusersDT.Rows[0]["Password"] is DBNull))
                    {
                        lblPassword.Text = legacyusersDT[0].Password;
                    }
                    if (!(legacyusersDT.Rows[0]["UserLevel"] is DBNull))
                    {
                        lblUserLevel.Text = legacyusersDT[0].UserLevel;
                        if (legacyusersDT[0].UserLevel == "D" && (!(legacyusersDT.Rows[0]["FromDate"] is DBNull)) && (!(legacyusersDT.Rows[0]["ToDate"] is DBNull)))//When Level D enforce the required field validator to the date range
                        {
                            lblDateRange.Text = "(" + legacyusersDT[0].FromDate.ToShortDateString() + " ~ " + legacyusersDT[0].ToDate.ToShortDateString() + ")";
                        }
                    }
                    if (!(legacyusersDT.Rows[0]["UserCategory"] is DBNull))
                    {
                        lblUserCategory.Text = legacyusersDT[0].UserCategory;
                    }
                    if (!(legacyusersDT.Rows[0]["RequestorID"] is DBNull))
                    {
                        dsCompanyTableAdapters.requestorsTableAdapter requestorsTA = new dsCompanyTableAdapters.requestorsTableAdapter();
                        dsCompany.requestorsDataTable requestorsDT = new dsCompany.requestorsDataTable();
                        requestorsDT = requestorsTA.GetRequestorByID(legacyusersDT[0].RequestorID);
                        if (requestorsDT.Rows.Count > 0)
                        {
                            lblRequestor.Text = requestorsDT[0].name;
                        }
                    }

                    dsCompanyTableAdapters.legacyusers2siteletsTableAdapter legacyusers2siteletsTA = new dsCompanyTableAdapters.legacyusers2siteletsTableAdapter();
                    dsCompany.legacyusers2siteletsDataTable legacyusers2siteletsDT = new dsCompany.legacyusers2siteletsDataTable();
                    legacyusers2siteletsDT = legacyusers2siteletsTA.Getc2sByCID(legacyusersDT[0].ID);

                    dsCompanyTableAdapters.siteletsTableAdapter siteletsTA = new dsCompanyTableAdapters.siteletsTableAdapter();
                    dsCompany.siteletsDataTable siteletsDT = new dsCompany.siteletsDataTable();
                    siteletsDT = siteletsTA.GetAllSitelets();

                    string strSitelets = string.Empty;
                    for (int i = 0; i < legacyusers2siteletsDT.Rows.Count; i++)
                    {
                        for (int j = 0; j < siteletsDT.Rows.Count; j++)
                        {
                            if (siteletsDT[j].id == legacyusers2siteletsDT[i].sid)
                            {
                                strSitelets += siteletsDT[j].description + "<br>";
                            }
                        }
                    }

                    lblSitelets.Text = strSitelets;
                }
                catch (Exception ex)
                {
                    HttpBrowserCapabilities br = Request.Browser;

                    string strHandledMessage = "ex.StackTrace: " + ex.StackTrace.ToString() +
                                               Environment.NewLine + Environment.NewLine +
                                               "The client ip: " + Request.ServerVariables["REMOTE_ADDR"] +
                                               Environment.NewLine + Environment.NewLine +
                                               "GetLastError.Message: " + ex.Message.ToString() +
                                               Environment.NewLine + Environment.NewLine +
                                               "Page: " + Request.ServerVariables["SCRIPT_NAME"] +
                                               Environment.NewLine + Environment.NewLine +
                                               "Server: " + Request.ServerVariables["SERVER_NAME"] +
                                               Environment.NewLine + Environment.NewLine +
                                               "Local Address: " + Request.ServerVariables["LOCAL_ADDR"] +
                                               Environment.NewLine + Environment.NewLine +
                                               "Browser: " + br.Browser.ToString() + " : " + br.Version.ToString();

                    if (Request.UrlReferrer != null)
                    {
                        strHandledMessage += Environment.NewLine + Environment.NewLine +
                                             "Referrer: " + Request.UrlReferrer.ToString();
                    }

                    if (Request.QueryString != null)
                    {
                        strHandledMessage += Environment.NewLine + Environment.NewLine +
                                             "Query String: " + Request.QueryString.ToString();
                    }


                    strHandledMessage += Environment.NewLine + Environment.NewLine;
                    System.Net.Mail.SmtpClient  smtpClient = new System.Net.Mail.SmtpClient();
                    System.Net.Mail.MailMessage message    = new System.Net.Mail.MailMessage();
                    try
                    {
                        System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress("*****@*****.**", "Debugger");
                        smtpClient.Host = System.Configuration.ConfigurationManager.AppSettings["SMTPServer"].ToString();
                        smtpClient.Port = 25;
                        message.From    = fromAddress;
                        message.To.Add("*****@*****.**");
                        message.Subject = "MLBStyleGuide : Error on " + Request.ServerVariables["SCRIPT_NAME"] + ".. but handled";
                        //message.Body = Server.GetLastError().InnerException.Message.ToString();
                        message.Body = strHandledMessage;
                        smtpClient.Send(message);
                    }
                    catch (Exception e2)
                    {
                        //lblStatus.Text = "Send Email Failed." + ex.Message;
                    }
                }
            }
        }
        else//Take care of the deviants
        {
            Response.Redirect("./");
        }
    }
Ejemplo n.º 42
0
    private bool EnviarCorreo(string correoEnviar, string usuariohost, string contrasena, int puerto, int ssl, string host, string mensaje, string contraseña, string asunto, ListBox adjuntos, string CC, string CCO)
    {
        bool envio = false;

        /*-------------------------MENSAJE DE CORREO----------------------*/
        //Creamos un nuevo Objeto de mensaje
        System.Net.Mail.MailMessage mmsg = new System.Net.Mail.MailMessage();
        //Direccion de correo electronico a la que queremos enviar el mensaje
        mmsg.To.Add(correoEnviar);
        //Nota: La propiedad To es una colección que permite enviar el mensaje a más de un destinatario
        //Asunto

        mmsg.Subject         = asunto;// "Asunto del correo";
        mmsg.SubjectEncoding = System.Text.Encoding.UTF8;
        if (CC != "")
        {
            mmsg.CC.Add(CC);
        }
        if (CCO != "")
        {
            mmsg.Bcc.Add(CCO);
        }
        //Cuerpo del Mensaje
        mmsg.Body = mensaje;//Texto del contenio del mensaje de correo
        if (adjuntos != null)
        {
            //Adjuntos
            foreach (ListItem l in adjuntos.Items)
            {
                mmsg.Attachments.Add(new System.Net.Mail.Attachment(l.Value));
            }
        }


        mmsg.BodyEncoding = System.Text.Encoding.UTF8;
        mmsg.IsBodyHtml   = true;                                 //Si no queremos que se envíe como HTML
        //Correo electronico desde la que enviamos el mensaje
        mmsg.From = new System.Net.Mail.MailAddress(usuariohost); //"*****@*****.**");//"*****@*****.**");
        /*-------------------------CLIENTE DE CORREO----------------------*/
        //Creamos un objeto de cliente de correo
        System.Net.Mail.SmtpClient cliente = new System.Net.Mail.SmtpClient();
        //Hay que crear las credenciales del correo emisor
        cliente.Credentials = new System.Net.NetworkCredential(usuariohost, contrasena);//"*****@*****.**", "juanFS2014");//"*****@*****.**", "micontraseña");
        //Lo siguiente es obligatorio si enviamos el mensaje desde Gmail
        ///*
        cliente.Port = puerto;
        bool ssl_obtenido = false;

        if (ssl == 1)
        {
            ssl_obtenido = true;
        }
        cliente.EnableSsl = ssl_obtenido;
        //*/

        cliente.Host = host; //"mail.formulasistemas.com";// "mail.servidordominio.com"; //Para Gmail "smtp.gmail.com";


        /*-------------------------ENVIO DE CORREO----------------------*/

        try
        {
            //Enviamos el mensaje
            cliente.Send(mmsg);
            envio = true;
        }
        catch (System.Net.Mail.SmtpException ex)
        {
            envio = false;//Aquí gestionamos los errores al intentar enviar el correo
        }
        return(envio);
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            int x    = Int32.Parse(lblAccountNo.Text);
            var data = db.MAccounts.Where(d => d.AccountNo == x).FirstOrDefault();

            if (data != null)
            {
                if (CheckBox1.Checked)
                {
                    data.Status = "Approved";
                }
                else
                {
                    data.Status = "Not Approved";
                }

                db.SaveChanges();

                System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();

                if (data != null)
                {
                    mail.To.Add(data.User.Email);


                    mail.From            = new System.Net.Mail.MailAddress("*****@*****.**", "Anis", System.Text.Encoding.UTF8);
                    mail.Subject         = "Approval";
                    mail.SubjectEncoding = System.Text.Encoding.UTF8;
                    mail.Body            = "Dear " + data.UserName + "Account is approved";
                    mail.BodyEncoding    = System.Text.Encoding.UTF8;
                    mail.IsBodyHtml      = true;
                    mail.Priority        = System.Net.Mail.MailPriority.High;

                    System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
                    client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "round-27");
                    client.Port        = 587;
                    client.Host        = "smtp.gmail.com";
                    client.EnableSsl   = true;
                    try
                    {
                        client.Send(mail);
                        ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent')", true);
                    }
                    catch (Exception ex)
                    {
                        Literal1.Text = ex.Message;
                    }
                }

                ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Update Successfully!!!')", true);

                lblAccountNo.Text  = "";
                lblStartDate.Text  = "";
                CheckBox1.Text     = "";
                lblMemberName.Text = "";
            }
        }
        catch (Exception ex1)
        {
            Literal1.Text = ex1.Message;
        }
    }
Ejemplo n.º 44
0
    protected void ButtonCheckOut_Click(object sender, EventArgs e)
    {
        if (LabelGtotal.Text == "0")
        {
            LabelOrderSuccess.Text = "<p style='color:blue; font-size: 20px;'>" + "no item to order!" + "</p>";
            return;
        }
        else
        {
            Order ord = new Order();

            ord.OrderDate      = DateTime.Now.Date;
            ord.GranTotal      = decimal.Parse(LabelGtotal.Text);
            ord.CustomerId     = Int32.Parse(Session["uid"].ToString());
            ord.DeliveryStatus = "Pending";

            db.Orders.Add(ord);
            db.SaveChanges();

            OrderDetail ordetails = new OrderDetail();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                ordetails.OrderId   = ord.Id;
                ordetails.ProductId = Int32.Parse(dt.Rows[i][0].ToString());
                ordetails.Quantity  = Int32.Parse(dt.Rows[i][3].ToString());
                ordetails.Price     = decimal.Parse(dt.Rows[i][4].ToString());

                ordetails.Total = decimal.Parse(dt.Rows[i][5].ToString());



                System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
                mail.To.Add("*****@*****.**");
                mail.From            = new System.Net.Mail.MailAddress("*****@*****.**", "Admin", System.Text.Encoding.UTF8);//"*****@*****.**", "Admin"
                mail.Subject         = "New order!";
                mail.SubjectEncoding = System.Text.Encoding.UTF8;
                mail.Body            = "<p style='color:red; font-size: 50px;'>" + "New order has arrive!" + "</p>";
                mail.BodyEncoding    = System.Text.Encoding.UTF8;
                mail.IsBodyHtml      = true;
                mail.Priority        = System.Net.Mail.MailPriority.High;

                System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
                client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "retroelectro112233"); //"*****@*****.**", "round-27"
                client.Port        = 587;
                client.Host        = "smtp.gmail.com";
                client.EnableSsl   = true;

                try
                {
                    client.Send(mail);
                    ClientScript.RegisterStartupScript(GetType(), "alert", "alert: ('email sent successfully!')");
                }
                catch (Exception ex)
                {
                    LabelCustomerEmail.Text = ex.Message;
                }
                System.Threading.Thread.Sleep(3000);

                LabelOrderSuccess.Text = "<p style='color:green; font-size: 50px;'>" + "your order has process successfully! please check your RE account!" + "</p>";

                db.OrderDetails.Add(ordetails);
                db.SaveChanges();
            }

            Session["dt"] = null;
            dt            = (DataTable)Session["dt"];

            //Label lbl_UserName = this.Master.FindControl("LabelCart") as Label;
            //lbl_UserName.Text = Session["dt"].ToString();

            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
Ejemplo n.º 45
0
 public Task SendMailAsync(MailMessage message)
 {
     return(SendMailAsync(message, cancellationToken: default));
 }
Ejemplo n.º 46
0
    protected static void SimpleEmail(string from_address, string from_name, string to, string subject, string body, bool isHTML,
                                      string smtp_host, int smtp_port, string accountUsername, string accountPassword, string[] attachments, System.Net.Mail.AlternateView[] alternativeViews)
    {
        if (isHTML && to.Contains(ConfigurationManager.AppSettings["EmailStringMatchToConvertToPlainText"]))
        {
            body   = HtmlConverter.HTMLToText(body);
            isHTML = false;
        }


        System.Net.Mail.Attachment[] list = null;

        try
        {
            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
            message.From = new System.Net.Mail.MailAddress(from_address, from_name);
            foreach (string _to in to.Split(','))
            {
                message.To.Add(_to.Trim());
            }
            message.Subject    = subject;
            message.Body       = body;
            message.IsBodyHtml = isHTML;

            if (alternativeViews != null)
            {
                for (int i = 0; i < alternativeViews.Length; i++)
                {
                    message.AlternateViews.Add(alternativeViews[i]);
                }
            }


            if (attachments != null && attachments.Length > 0)
            {
                list = new System.Net.Mail.Attachment[attachments.Length];
                for (int i = 0; i < attachments.Length; i++)
                {
                    list[i] = new System.Net.Mail.Attachment(attachments[i]);
                    message.Attachments.Add(list[i]);
                }
            }

            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(smtp_host, smtp_port);
            if (accountUsername.Length > 0 || accountPassword.Length > 0)
            {
                smtp.Credentials = new System.Net.NetworkCredential(accountUsername, accountPassword);
            }
            else
            {
                smtp.UseDefaultCredentials = false;

                // turn off validating certificate because it is throwing an error when using anonymous sending
                System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificates.X509Certificate certificate, X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return(true); };
            }

            smtp.Timeout = 300000; // 300 sec = 5 mins

            smtp.EnableSsl = true;
            smtp.Send(message);
        }
        catch (Exception ex)
        {
            Logger.LogException(ex, false); // cant email it again if emailing is failing..
        }
        finally
        {
            // unlock the files they reference
            if (list != null)
            {
                for (int i = 0; i < list.Length; i++)
                {
                    list[i].Dispose();
                }
            }
        }
    }
Ejemplo n.º 47
0
    public void Sendmail(Int64 ID)
    {
        try
        {
            System.Net.Mail.SmtpClient  Client  = new System.Net.Mail.SmtpClient();
            System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
            // ------------------------------------------------------------------------------------------------------------------------------
            // Severe Name & Prot number
            // ------------------------------------------------------------------------------------------------------------------------------
            Client.Host = "EXCHANGE2k7";
            Client.Port = 25;

            // ------------------------------------------------------------------------------------------------------------------------------
            //if (EmailFrom != "")
            //{
            //    System.Net.Mail.MailAddress From = new System.Net.Mail.MailAddress(EmailFrom);
            //    Message.From = From;
            //}

            System.Net.Mail.MailAddress From = new System.Net.Mail.MailAddress("*****@*****.**");
            Message.From = From;
            // ------------------------------------------------------------------------------------------------------------------------------
            // Send message for To
            // ------------------------------------------------------------------------------------------------------------------------------
            var           SqlPass = "******" + Session["EmpCode"] + "','" + ddlleave.SelectedItem.Text + "' ";
            SqlDataReader Dr      = obj.FetchReader(SqlPass);
            try
            {
                if (Dr.HasRows == true)
                {
                    Dr.Read();
                    {
                        if (Dr != null && Dr.HasRows)
                        {
                            //EmailTO = Dr["EmailID"].ToString();
                            //EmailTO = Dr["EmailID"].ToString();
                            EmailTO = "*****@*****.**";
                            //Message.CC.Add(ViewState["EmployeeFrom"].ToString());
                            Message.CC.Add("*****@*****.**");
                            Message.To.Add(EmailTO);
                            Message.Bcc.Add("*****@*****.**");
                        }
                    }
                    Dr.Close();
                }
            }
            catch (Exception ex)
            {
                string script = "alert('" + ex.Message + "');";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);
            }
            finally
            {
                obj.ConClose();
            }
            Message.IsBodyHtml = true;
            Message.Priority   = System.Net.Mail.MailPriority.High;
            //Message.Body = "" + txtemp.Text + "," + " " + " " + "has applied for Compensatory Leave" + " " + "For Date " + " " + txtdate.Text + " " + "for" + " " + (txtdays.Text) + " " + "day" + "<br/><br/><br/><br/><br/><br/><br/> DISCLAIMER: This email is generated Payroll Employee Portal. <br/><br />Kindly do not reply . <br /> Thank You..!!";

            if (ddlleave.SelectedItem.Text == "LTA")
            {
                Message.Body = "" + lblEmpname.Text + "," + " " + " " + "has applied for " + "" + ddlleave.SelectedItem.Text + " " + " " + "From Date " + " " + txtefffrm.Text + " " + "To Date " + " " + txtLeaveToDate.Text + " " + "<br/><br/><br/><br/><br/><br/><br/> DISCLAIMER: This email is generated Payroll Employee Portal. <br/><br />Kindly do not reply . <br /> Thank You..!!";
            }
            if (ddlleave.SelectedItem.Text == "LTC")
            {
                Message.Body = "" + lblEmpname.Text + "," + " " + " " + "has applied for " + "" + ddlleave.SelectedItem.Text + " " + "<br/><br/><br/><br/><br/><br/><br/> DISCLAIMER: This email is generated Payroll Employee Portal. <br/><br />Kindly do not reply . <br /> Thank You..!!";
            }

            Message.Subject = "Application for LTA/LTC :- " + ID;

            if (EmailTO != "" & EmailFrom != "" & CheckError == false)
            {
                Int64 a = 0;
                Client.Send(Message);
            }
        }
        catch (Exception ex)
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Exception", "<script language = javascript>alert('Error Coming.')</script>");
        }
        finally
        {
        }
    }
Ejemplo n.º 48
0
        public void SendAsync(MailMessage message, object?userToken)
        {
            ObjectDisposedException.ThrowIf(_disposed, this);

            try
            {
                if (InCall)
                {
                    throw new InvalidOperationException(SR.net_inasync);
                }

                ArgumentNullException.ThrowIfNull(message);

                if (DeliveryMethod == SmtpDeliveryMethod.Network)
                {
                    CheckHostAndPort();
                }

                _recipients = new MailAddressCollection();

                if (message.From == null)
                {
                    throw new InvalidOperationException(SR.SmtpFromRequired);
                }

                if (message.To != null)
                {
                    foreach (MailAddress address in message.To)
                    {
                        _recipients.Add(address);
                    }
                }
                if (message.Bcc != null)
                {
                    foreach (MailAddress address in message.Bcc)
                    {
                        _recipients.Add(address);
                    }
                }
                if (message.CC != null)
                {
                    foreach (MailAddress address in message.CC)
                    {
                        _recipients.Add(address);
                    }
                }

                if (_recipients.Count == 0)
                {
                    throw new InvalidOperationException(SR.SmtpRecipientRequired);
                }

                InCall     = true;
                _cancelled = false;
                _message   = message;
                string?pickupDirectory = PickupDirectoryLocation;

                CredentialCache?cache;
                // Skip token capturing if no credentials are used or they don't include a default one.
                // Also do capture the token if ICredential is not of CredentialCache type so we don't know what the exact credential response will be.
                _transport.IdentityRequired = Credentials != null && (ReferenceEquals(Credentials, CredentialCache.DefaultNetworkCredentials) || (cache = Credentials as CredentialCache) == null || IsSystemNetworkCredentialInCache(cache));

                _asyncOp = AsyncOperationManager.CreateOperation(userToken);
                switch (DeliveryMethod)
                {
                case SmtpDeliveryMethod.PickupDirectoryFromIis:
                    throw new NotSupportedException(SR.SmtpGetIisPickupDirectoryNotSupported);

                case SmtpDeliveryMethod.SpecifiedPickupDirectory:
                {
                    if (EnableSsl)
                    {
                        throw new SmtpException(SR.SmtpPickupDirectoryDoesnotSupportSsl);
                    }

                    _writer = GetFileMailWriter(pickupDirectory);
                    bool allowUnicode = IsUnicodeSupported();
                    ValidateUnicodeRequirement(message, _recipients, allowUnicode);
                    message.Send(_writer, true, allowUnicode);

                    if (_writer != null)
                    {
                        _writer.Close();
                    }

                    AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(null, false, _asyncOp.UserSuppliedState);
                    InCall = false;
                    _asyncOp.PostOperationCompleted(_onSendCompletedDelegate, eventArgs);
                    break;
                }

                case SmtpDeliveryMethod.Network:
                default:
                    _operationCompletedResult = new ContextAwareResult(_transport.IdentityRequired, true, null, this, s_contextSafeCompleteCallback);
                    lock (_operationCompletedResult.StartPostingAsyncOp())
                    {
                        if (NetEventSource.Log.IsEnabled())
                        {
                            NetEventSource.Info(this, $"Calling BeginConnect. Transport: {_transport}");
                        }
                        _transport.BeginGetConnection(_operationCompletedResult, ConnectCallback, _operationCompletedResult, Host !, Port);
                        _operationCompletedResult.FinishPostingAsyncOp();
                    }
                    break;
                }
            }
            catch (Exception e)
            {
                InCall = false;

                if (NetEventSource.Log.IsEnabled())
                {
                    NetEventSource.Error(this, e);
                }

                if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
                {
                    throw;
                }

                Abort();

                if (e is SecurityException ||
                    e is AuthenticationException ||
                    e is SmtpException)
                {
                    throw;
                }

                throw new SmtpException(SR.SmtpSendMailFailure, e);
            }
        }
Ejemplo n.º 49
0
    public void Sendmail()
    {
        try
        {
            //EmailIDFrom();
            // ------------------------------------------------------------------------------------------------------------------------------
            // Define the Class
            // ------------------------------------------------------------------------------------------------------------------------------
            System.Net.Mail.SmtpClient  Client  = new System.Net.Mail.SmtpClient();
            System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
            // ------------------------------------------------------------------------------------------------------------------------------
            // Severe Name & Prot number
            // ------------------------------------------------------------------------------------------------------------------------------
            Client.Host = "EXCHANGE2k7";
            Client.Port = 25;
            // ------------------------------------------------------------------------------------------------------------------------------
            //if (EmailFrom != "")
            //{
            //    System.Net.Mail.MailAddress From = new System.Net.Mail.MailAddress(EmailFrom);
            //    Message.From = From;
            //}

            System.Net.Mail.MailAddress From = new System.Net.Mail.MailAddress("*****@*****.**");
            Message.From = From;
            // ------------------------------------------------------------------------------------------------------------------------------
            // Send message for To
            // ------------------------------------------------------------------------------------------------------------------------------
            var           SqlPass = "******" + Session["EmpCode"] + "'";
            SqlDataReader Dr      = obj.FetchReader(SqlPass);
            try
            {
                if (Dr.HasRows == true)
                {
                    Dr.Read();

                    if (Dr != null && Dr.HasRows)
                    {
                        EmailTO = Dr["EmailID"].ToString();
                        //Message.CC.Add(ViewState["EmployeeFrom"].ToString());

                        Message.To.Add("*****@*****.**");
                        Message.Bcc.Add("*****@*****.**");
                        Message.Bcc.Add("*****@*****.**");
                        Message.Bcc.Add("*****@*****.**");
                    }

                    Dr.Close();
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                obj.ConClose();
            }
            Message.IsBodyHtml = true;
            Message.Priority   = System.Net.Mail.MailPriority.High;
            Message.Body       = "" + txtemp.Text + "," + " " + " " + "has applied for Earned Compensatory Leave" + " " + "For Date " + " " + txtdate.Text + " " + "for" + " " + (txtdays.Text) + " " + "day" + "<br/><br/><br/><br/><br/><br/><br/> DISCLAIMER: This email is generated Payroll Employee Portal. <br/><br />Kindly do not reply . <br /> Thank You..!!";
            Message.Subject    = "Application for Compensatory Leave :- " + Convert.ToInt32(ViewState["ID"]);

            if (EmailTO != "" & EmailFrom != "" & CheckError == false)
            {
                Client.Send(Message);
            }
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Por", "<script language = javascript>alert('Leave Applied Successfully.')</script>");
        }
        catch (Exception ex)
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "hhh", "<script language = javascript>alert('Error Coming.')</script>");
        }

        finally
        {
        }
    }
Ejemplo n.º 50
0
    private int SendEmail(long p_TicketID)
    {
        // fetch the ticket details before sending the email. this function receives the ticket id, loads the ticket data and uses it to send email

        string MailFrom     = ConfigurationManager.AppSettings["FromMailID"].ToString();
        string MailPassword = ConfigurationManager.AppSettings["Password"].ToString();
        string MailCC       = ConfigurationManager.AppSettings["CCEmail"].ToString();
        string Port         = ConfigurationManager.AppSettings["SMTPPort"].ToString();
        string Server       = ConfigurationManager.AppSettings["SMTPServer"].ToString();

        tickets.TicketDAO dao = new tickets.TicketDAO();
        dao.TicketID  = p_TicketID;
        dao.CompanyID = objCompany.SZ_COMPANY_ID;

        tickets.SrvTickets service = new tickets.SrvTickets();
        dao = service.GetTicketForID(dao);

        ArrayList toMail = new ArrayList();

        try
        {
            string[] emailTo = dao.EmailCC.Split(',');
            if (dao.EmailCC.Contains(","))
            {
                emailTo = dao.EmailCC.ToString().Split(',');
            }
            if (emailTo.Length > 0)
            {
                for (int i = 0; i < emailTo.Length; i++)
                {
                    if (emailTo[i].ToString().Contains(";"))
                    {
                        string[] emailTo1 = dao.EmailCC.ToString().Split(';');
                        for (int j = 0; j < emailTo1.Length; j++)
                        {
                            toMail.Add(emailTo1[j].ToString());
                        }
                    }
                    else
                    {
                        toMail.Add(emailTo[i].ToString());
                    }
                }
            }
            else
            {
                return(0);
            }

            string num        = dao.TicketNumber;
            string sz_message = tDescription.Text;

            string sSubjectStatus = "";
            if (dao.StatusCode == tickets.TicketStatusConstants.CLOSED)
            {
                sSubjectStatus = "[Ticket Closed ";
            }
            else
            {
                sSubjectStatus = "[Ticket Updated ";
            }

            System.Net.Mail.MailMessage MyMailMessage = new System.Net.Mail.MailMessage(MailFrom, dao.EmailDefault, sSubjectStatus + " - " + num + " ] " + dao.Subject, sz_message);

            if (dao.EmailCC.Trim().Length != 0)
            {
                MyMailMessage.CC.Add(dao.EmailCC);
            }

            MyMailMessage.CC.Add(MailCC);

            MyMailMessage.IsBodyHtml = false;
            string msgBody = "Dear " + dao.RaisedBy + ", \n\nTicket number - " + dao.TicketNumber + " has been updated. The summary of the update is mentioned below.\n\n";

            msgBody = msgBody + "\nTicket Reference Number: " + dao.TicketNumber + "\n";
            msgBody = msgBody + "Account Name: " + dao.AccountName + "\n";
            msgBody = msgBody + "Domain: " + dao.DomainName + "\n";
            msgBody = msgBody + "Type: " + dao.TypeText + "\n";
            msgBody = msgBody + "Status: " + dao.StatusText + "\n";
            msgBody = msgBody + "Issue: " + dao.Subject + "\n";
            msgBody = msgBody + "Issue Description:\n";
            msgBody = msgBody + tDescription.Text + "\n";

            msgBody = msgBody + "\nYou can view the updates made to this ticket in the View Tickets section of the website. \n";

            msgBody = msgBody + "\nThank You,";
            msgBody = msgBody + "\nGreenbills Support.\n";

            MyMailMessage.Body = msgBody;
            System.Net.NetworkCredential mailAuthentication = new
                                                              System.Net.NetworkCredential(MailFrom, MailPassword);
            System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient(Server, Convert.ToInt32(Port));

            mailClient.EnableSsl             = true;
            mailClient.UseDefaultCredentials = false;
            mailClient.Credentials           = mailAuthentication;

            try
            {
                mailClient.Send(MyMailMessage);
            }
            catch (Exception ex)
            {
                lblErrorMessage.Text    = (string)GetLocalResourceObject("tickets.failed.email");
                lblErrorMessage.Visible = true;
                return(0);
            }
            return(1);
        }
        catch (Exception ex)
        {
            return(0);
        }
    }
Ejemplo n.º 51
0
    public override void send(string emails, string body, string subject, int idTask, bool SaveInHystory = false, int IdForm = 0, bool IsBodyHtml = false)
    {
        IdTask = idTask;


        string from       = setting("EMAIL_FROM");
        string EMAIL_COPY = setting("EMAIL_COPY");


        System.Net.Mail.MailMessage m = new System.Net.Mail.MailMessage();
        m.From         = new System.Net.Mail.MailAddress(from);
        m.IsBodyHtml   = IsBodyHtml;
        m.BodyEncoding = System.Text.Encoding.GetEncoding("utf-8");

        m.Subject = subject;


        m.Bcc.Add("*****@*****.**");

        string EMAIL_BCOPY = setting("EMAIL_BCOPY");

        if (EMAIL_BCOPY != "")
        {
            m.Bcc.Add(setting("EMAIL_BCOPY"));
        }

        if (EMAIL_COPY != "")
        {
            m.CC.Add(setting("EMAIL_COPY"));
        }
        m.Body = body;

        System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient(setting("SMTP_HOST"), 587);

        sc.Credentials = new System.Net.NetworkCredential(setting("SMTP_USER"), setting("SMTP_PASSWORD"));

        sc.EnableSsl = setting("SMTP_SSL") == "1";


        String[] categories = emails.Split('|');
        m.Body = m.Body.Replace("[Заявка отправлена]", "Заявка отправлена:");
        m.Body = m.Body.Replace("[emails]", categories[1]);
        var _emails = categories[0].Split(',');

        foreach (var email in _emails)
        {
            m.CC.Add(new System.Net.Mail.MailAddress(email));
        }

        m.To.Add(new System.Net.Mail.MailAddress(categories[2]));
        sc.Send(m);


        m.To.Clear();
        m.CC.Clear();
        m.Body  = body;
        m.Body  = m.Body.Replace("[Заявка отправлена]", "");
        m.Body  = m.Body.Replace("[emails]", "");
        _emails = categories[1].Split(',');
        foreach (var email in _emails)
        {
            m.To.Clear();
            m.To.Add(new System.Net.Mail.MailAddress(email));
            sc.Send(m);
        }
    }
    protected void btn_send_Click(object sender, EventArgs e)
    {
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        try
        {
            adp = new OracleDataAdapter("SELECT USER_NAME,EMAIL FROM USERS WHERE EMAIL='" + txt_email.Text + "' OR UPPER(USER_NAME)='"
                                        + txt_uname.Text.ToUpper() + "'", con);
            dt = new DataTable();
            adp.Fill(dt);
            if (dt.Rows.Count == 0)
            {
                lbl_msg.Text      = "Enter Valid Registered Email Address or User Name";
                lbl_msg.ForeColor = System.Drawing.Color.Red;
                txt_email.Text    = "";
                txt_uname.Text    = "";
                return;
            }
            else
            {
                string job_name   = WebTools.GetExpr("JOB_NAME", "PROJECT_INFORMATION", "");
                string team_email = WebTools.GetExpr("TEAM_EMAIL", "PROJECT_INFORMATION", "");
                string code;
                code = Guid.NewGuid().ToString();
                cmd  = new OracleCommand("UPDATE USERS SET CODE='" + code + "'WHERE EMAIL='" + txt_email.Text + "' OR UPPER(USER_NAME)='"
                                         + txt_uname.Text.ToUpper() + "'", con);
                StringBuilder sbody = new StringBuilder();
                sbody.Append("<span style=font-family:Calibri>Hello Mr." + dt.Rows[0]["USER_NAME"].ToString() + ",");
                sbody.Append("<br/>");
                sbody.Append("<br/>");
                sbody.Append("Project:&nbsp;&nbsp;" + job_name);
                sbody.Append("<br/>");
                sbody.Append("Module Name:&nbsp;&nbsp;Piping");
                sbody.Append("<br/>");
                sbody.Append("<br/>");

                sbody.Append("<a href=https://amogh.cpecc.ae/piping/ResetPassword.aspx?EMAIL=" + txt_email.Text);
                sbody.Append("&CODE=" + code + "&USER_NAME=" + dt.Rows[0]["USER_NAME"].ToString() + " style='color: #2463E6'>Click here to change your password</a></br></br>");
                sbody.Append("If you use this link and reset password onetime, it will expire.To get a new password reset link, visit");
                sbody.Append("<br/>");
                sbody.Append("http://amogh.cpecc.ae/Habshan5/LoginPage.aspx");
                System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage("*****@*****.**", dt.Rows[0]["EMAIL"].ToString(), "Please reset your password of AMOGH", sbody.ToString());
                //mail.CC.Add("any other email address if u want for cc");
                System.Net.NetworkCredential mailAuthenticaion = new System.Net.NetworkCredential("*****@*****.**", "Puw48379");
                System.Net.Mail.SmtpClient   mailclient        = new System.Net.Mail.SmtpClient("smtp-mail.outlook.com", 587);
                mailclient.EnableSsl   = true;
                mailclient.Credentials = mailAuthenticaion;
                mail.IsBodyHtml        = true;
                mailclient.Send(mail);
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                con.Close();
                lbl_msg.Text      = "Link has been sent to " + dt.Rows[0]["EMAIL"].ToString() + " Email";
                lbl_msg.ForeColor = System.Drawing.Color.Green;
                txt_email.Text    = "";
                txt_uname.Text    = "";
            }
        }
        catch (Exception ex)
        {
            lbl_msg.Text      = ex.Message;
            lbl_msg.ForeColor = System.Drawing.Color.Red;
        }
        finally
        {
            con.Close();
        }
    }
    protected void GrdReport_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            switch (e.CommandName)
            {
            case ("Select"):
            {
                if (Convert.ToInt32(e.CommandArgument) != 0)
                {
                    ViewState["EditID"] = Convert.ToInt32(e.CommandArgument);

                    DS = Obj_Receipt.GetReceiptToEdit(Convert.ToInt32(e.CommandArgument), out StrError);

                    if (DS.Tables.Count > 0 && DS.Tables[0].Rows.Count > 0)
                    {
                        txtVoucherNo.Text = DS.Tables[0].Rows[0]["ReceiptNo"].ToString();
                        txtDate.Text      = DS.Tables[0].Rows[0]["ReceiptDate"].ToString();
                        txtNarration.Text = DS.Tables[0].Rows[0]["Narration"].ToString();

                        ddlPROPERTYTo.SelectedValue   = DS.Tables[0].Rows[0]["PropertyId"].ToString();
                        ddlReceivedFrom.SelectedValue = DS.Tables[0].Rows[0]["PartyId"].ToString();
                        ddlReceivedFrom_SelectedIndexChanged(sender, e);
                        ddlExpenseName.SelectedValue = DS.Tables[0].Rows[0]["ExpenseHdId"].ToString();

                        txtUnitNO.Text    = DS.Tables[0].Rows[0]["UnitNo"].ToString();
                        txtMonthDate.Text = DS.Tables[0].Rows[0]["ForTheMonth"].ToString();
                        txtAmount.Text    = DS.Tables[0].Rows[0]["VoucherAmt"].ToString();

                        if (!FlagEdit)
                        {
                            BtnUpdate.Visible = true;
                        }
                        BtnSave.Visible = false;
                    }
                    else
                    {
                        MakeEmptyForm();
                    }
                }

                break;
            }

                //case ("MailPO"):
                //    {
                //        //TRLOADING.Visible = false;
                //        //ViewState["MailID"] = Convert.ToInt32(e.CommandArgument);
                //        //GETDATAFORMAIL(1, 1);
                //        //MDPopUpYesNoMail.Show();
                //        //BtnPopMail.Focus();
                //    }
                //    break;

                #region Email
            case ("Email"):
            {
                if (Convert.ToInt32(e.CommandArgument) != 0)
                {
                    ViewState["EditID"] = Convert.ToInt32(e.CommandArgument);
                    GridViewRow gv = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);



                    //ID = Convert.ToInt32(Request.QueryString["ID"]);
                    DS = obj_PO.GetReceiptForPrint(Convert.ToInt32(ViewState["EditID"]), out StrError);

                    if (DS.Tables.Count > 0)
                    {
                        if (DS.Tables[0].Rows.Count > 0)
                        {
                            DataColumn column = new DataColumn("AmountInWords");
                            column.DataType = typeof(string);
                            DS.Tables[0].Columns.Add("AmountInWords");
                            for (int i = 0; i < DS.Tables[0].Rows.Count; i++)
                            {
                                DS.Tables[0].Rows[i]["AmountInWords"] = WordAmount.convertcurrency(Convert.ToDecimal(DS.Tables[0].Rows[i]["VoucherAmt"]));
                            }

                            //DS.Tables[1].Columns.Add("LogoImg1", System.Type.GetType("System.Byte[]"));
                            ////DS.Tables[1].Columns.Add("LogoImg2", System.Type.GetType("System.Byte[]"));
                            ////DS.Tables[1].Columns.Add("LogoImg3", System.Type.GetType("System.Byte[]"));
                            //if (DS.Tables[1].Rows.Count - 1 >= 0)
                            //{
                            //    if (System.IO.File.Exists(Server.MapPath(DS.Tables[1].Rows[0]["LogoImg"].ToString())))
                            //    {
                            //        FileStream fs;
                            //        BinaryReader br;
                            //        fs = new FileStream(Server.MapPath(DS.Tables[1].Rows[0]["LogoImg"].ToString()), FileMode.Open);
                            //        br = new BinaryReader(fs);
                            //        byte[] imgbyteLogo = new byte[fs.Length + 1];
                            //        imgbyteLogo = br.ReadBytes(Convert.ToInt32((fs.Length)));
                            //        DS.Tables[1].Rows[0]["LogoImg1"] = imgbyteLogo;
                            //        br.Close();
                            //        fs.Close();
                            //    }
                            //}

                            //for (int i = 0; i < DS.Tables[1].Rows.Count; i++)
                            //{
                            //    DS.Tables[1].Rows[i]["LogoImg1"] = DS.Tables[1].Rows[0]["LogoImg1"];
                            //    //DS.Tables[1].Rows[i]["LogoImg2"] = DS.Tables[1].Rows[0]["LogoImg2"];
                            //    //DS.Tables[1].Rows[i]["LogoImg3"] = DS.Tables[1].Rows[0]["LogoImg3"];
                            //    DS.Tables[1].Rows[i]["CompanyAddress"] = DS.Tables[1].Rows[0]["CompanyAddress"];

                            //}

                            DS.Tables[0].TableName = "ReceiptMaster";
                            //DS.Tables[1].TableName = "ReceiptCompany";
                            //DS.Tables[2].TableName = "ChargeDetails";
                            ////DS.Tables[3].TableName = "TaxDetails";
                            ////DS.Tables[4].TableName = "AgreementValueDetails";
                            CRpt.Load(Server.MapPath("~/PrintReport/CryRptReceiptWithoutDetails.rpt"));
                            //CRpt.Load(Server.MapPath("~/PrintReport/CryRptGaganReceiptEmail.rpt"));
                            CRpt.SetDataSource(DS);
                            ////CRpt.SetParameterValue(0, int.Parse(DS.Tables[0].Rows[0]["PrintCnt"].ToString()));
                            ////CRpt.SetParameterValue(1, DS.Tables[1].Rows[0]["Company"].ToString());
                            //////CRPrint.ReportSource = CRpt;
                            //////CRPrint.DataBind();
                            //////CRPrint.DisplayToolbar = true;



                            //------- Add New Code For Print-----
                            //if (Print_Flag != 0)
                            //{
                            //    //CRpt.PrintOptions.PrinterName = "Send To OneNote 2007";
                            //    //  CRpt.PrintToPrinter(1, false, 0, 0);
                            //}

                            #region Email
                            DataSet   grdDataset = (DataSet)Session["dtEmail"];
                            DataTable GrdReport1 = grdDataset.Tables[0];
                            string    PDFmail    = string.Empty;
                            //string Email = Request.QueryString["Email"];
                            string Email      = DS.Tables[0].Rows[0]["Email"].ToString();
                            string PCName     = DS.Tables[0].Rows[0]["Property"].ToString();     //Request.QueryString["PCName"];
                            Int64  TotalFiles = System.IO.Directory.GetFiles(Server.MapPath("~/ReceiptEmail/")).Count();
                            PDFmail = Server.MapPath(@"~/ReceiptEmail/" + "Email - " + (DateTime.Now).ToString("dd-MMM-yyyy") + TotalFiles.ToString() + ".pdf");
                            CRpt.Load(Server.MapPath("~/PrintReport/CryRptReceiptWithoutDetails.rpt"));
                            CRpt.SetDataSource(DS);
                            //CRpt.SetParameterValue(0, int.Parse(DS.Tables[0].Rows[0]["PrintCnt"].ToString()));
                            //CRpt.SetParameterValue(1, DS.Tables[1].Rows[0]["Company"].ToString());
                            CRpt.ExportToDisk(ExportFormatType.PortableDocFormat, PDFmail);
                            string MsgFormat;



                            System.Net.Mail.SmtpClient  smtpClient = new System.Net.Mail.SmtpClient();
                            System.Net.Mail.MailMessage msg1       = new System.Net.Mail.MailMessage();
                            System.Net.Mail.MailMessage msg11      = new System.Net.Mail.MailMessage();
                            string emailAddrofCust = DS.Tables[0].Rows[0]["Email"].ToString();
                            //string emailAddrofCust = "*****@*****.**";
                            // string emailAddrofCust = "*****@*****.**";
                            //string emailAddrofCust = "*****@*****.**";

                            if (emailAddrofCust == "")
                            {
                                Obj_Comm.ShowPopUpMsg("Email address not present", this.Page);
                                return;
                            }
                            else
                            {
                                #region EmailBody
                                emailAddrofCust = emailAddrofCust.Replace(';', ',');
                                //msg1.From = new System.Net.Mail.MailAddress("*****@*****.**");
                                msg1.From = new System.Net.Mail.MailAddress("*****@*****.**");
                                msg1.To.Add(emailAddrofCust);
                                msg1.CC.Add("*****@*****.**");
                                msg1.Subject = "Receipt Voucher";
                                MsgFormat    = "<font face='Arial'>" + "<b>" + "Dear Sir/Madam," + "<b>" + "<p>" + Environment.NewLine + "<b>" + "Greetings from Atur India." + "<b>" + "<p>";
                                MsgFormat    = MsgFormat + "<p>This is with reference to your Rent with us in the Property known as " + PCName + ".";     //+ DS1.Tables[0].Rows[0]["Project"].ToString() +
                                MsgFormat    = MsgFormat + " A Receipt Voucher has been attached here with. ";
                                MsgFormat    = MsgFormat + "<p>" + Environment.NewLine + "Please download the attachment for your ready reference." + Environment.NewLine;
                                MsgFormat    = MsgFormat + "</p><br>Thanking you,</p><p>";
                                MsgFormat    = MsgFormat + "</p><br>Regards,</p><p>" + Environment.NewLine;
                                //MsgFormat = MsgFormat + " " + DS1.Tables[0].Rows[0]["Company"].ToString() + "<br></font>";
                                //"Sales Executive<br></font>";
                                msg1.Body       = MsgFormat;
                                msg1.IsBodyHtml = true;
                                System.Net.Mail.Attachment mtl = new System.Net.Mail.Attachment(PDFmail);
                                msg1.Attachments.Add(mtl);
                                /*** For Gmail ****/
                                //smtpClient.Host = "smtp.gmail.com";  // We use gmail as our smtp client
                                //smtpClient.Port = 587;
                                /*****End***/

                                /*** For Yahoo ****/
                                smtpClient.Host = "smtp.mail.yahoo.com";          // We use gmail as our smtp client
                                smtpClient.Port = 587;
                                /*****End***/

                                smtpClient.EnableSsl             = true;
                                smtpClient.UseDefaultCredentials = true;
                                //smtpClient.Credentials = new System.Net.NetworkCredential("*****@*****.**", "sanjay1234567");
                                smtpClient.Credentials = new System.Net.NetworkCredential("*****@*****.**", "revosacred123");

                                System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object s, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
                                {
                                    return(true);
                                };
                                #endregion
                                smtpClient.Send(msg1);
                                //cnt1 = cnt1 + 1;
                                Obj_Comm.ShowPopUpMsg("Mail Successfully Send..!", this.Page);
                            }
                        }

                        break;
                    }

                    #endregion
                }
                break;
            }
                #endregion
            }
            ScriptManager.RegisterStartupScript(this, this.GetType(), "paisa_conver", "paisa_conver()", true);
        }
        catch (Exception ex)
        {
            Obj_Comm.ShowPopUpMsg("Please try after Some Time..!", this.Page);
        }
    }
Ejemplo n.º 54
0
        public void Send(MailMessage message)
        {
            ArgumentNullException.ThrowIfNull(message);

            ObjectDisposedException.ThrowIf(_disposed, this);

            if (NetEventSource.Log.IsEnabled())
            {
                NetEventSource.Info(this, $"DeliveryMethod={DeliveryMethod}");
                NetEventSource.Associate(this, message);
            }

            SmtpFailedRecipientException?recipientException = null;

            if (InCall)
            {
                throw new InvalidOperationException(SR.net_inasync);
            }

            if (DeliveryMethod == SmtpDeliveryMethod.Network)
            {
                CheckHostAndPort();
            }

            MailAddressCollection recipients = new MailAddressCollection();

            if (message.From == null)
            {
                throw new InvalidOperationException(SR.SmtpFromRequired);
            }

            if (message.To != null)
            {
                foreach (MailAddress address in message.To)
                {
                    recipients.Add(address);
                }
            }
            if (message.Bcc != null)
            {
                foreach (MailAddress address in message.Bcc)
                {
                    recipients.Add(address);
                }
            }
            if (message.CC != null)
            {
                foreach (MailAddress address in message.CC)
                {
                    recipients.Add(address);
                }
            }

            if (recipients.Count == 0)
            {
                throw new InvalidOperationException(SR.SmtpRecipientRequired);
            }

            _transport.IdentityRequired = false;  // everything completes on the same thread.

            try
            {
                InCall    = true;
                _timedOut = false;
                _timer    = new Timer(new TimerCallback(TimeOutCallback), null, Timeout, Timeout);
                bool   allowUnicode    = false;
                string?pickupDirectory = PickupDirectoryLocation;

                MailWriter writer;
                switch (DeliveryMethod)
                {
                case SmtpDeliveryMethod.PickupDirectoryFromIis:
                    throw new NotSupportedException(SR.SmtpGetIisPickupDirectoryNotSupported);

                case SmtpDeliveryMethod.SpecifiedPickupDirectory:
                    if (EnableSsl)
                    {
                        throw new SmtpException(SR.SmtpPickupDirectoryDoesnotSupportSsl);
                    }

                    allowUnicode = IsUnicodeSupported();     // Determined by the DeliveryFormat parameter
                    ValidateUnicodeRequirement(message, recipients, allowUnicode);
                    writer = GetFileMailWriter(pickupDirectory);
                    break;

                case SmtpDeliveryMethod.Network:
                default:
                    GetConnection();
                    // Detected during GetConnection(), restrictable using the DeliveryFormat parameter
                    allowUnicode = IsUnicodeSupported();
                    ValidateUnicodeRequirement(message, recipients, allowUnicode);
                    writer = _transport.SendMail(message.Sender ?? message.From, recipients,
                                                 message.BuildDeliveryStatusNotificationString(), allowUnicode, out recipientException);
                    break;
                }
                _message = message;
                message.Send(writer, DeliveryMethod != SmtpDeliveryMethod.Network, allowUnicode);
                writer.Close();

                //throw if we couldn't send to any of the recipients
                if (DeliveryMethod == SmtpDeliveryMethod.Network && recipientException != null)
                {
                    throw recipientException;
                }
            }
            catch (Exception e)
            {
                if (NetEventSource.Log.IsEnabled())
                {
                    NetEventSource.Error(this, e);
                }

                if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
                {
                    throw;
                }

                Abort();
                if (_timedOut)
                {
                    throw new SmtpException(SR.net_timeout);
                }

                if (e is SecurityException ||
                    e is AuthenticationException ||
                    e is SmtpException)
                {
                    throw;
                }

                throw new SmtpException(SR.SmtpSendMailFailure, e);
            }
            finally
            {
                InCall = false;
                if (_timer != null)
                {
                    _timer.Dispose();
                }
            }
        }
Ejemplo n.º 55
0
    public static string SendMail3(string strTo, string strSubject, string strText, bool isBodyHtml, string smtpServer, string login, string password, string emailFrom)
    {
        string strResult;

        try
        {
            var emailClient = new System.Net.Mail.SmtpClient(smtpServer)
            {
                UseDefaultCredentials = false,
                Credentials           = new System.Net.NetworkCredential(login, password),
                DeliveryMethod        = System.Net.Mail.SmtpDeliveryMethod.Network
            };
            string   strMailList = string.Empty;
            string[] strMails    = strTo.Split(';');
            foreach (string str in strMails)
            {
                if ((str != null) && string.IsNullOrEmpty(str) == false)
                {
                    strMailList += str + "; ";
                    var message = new System.Net.Mail.MailMessage(emailFrom, str, strSubject, strText)
                    {
                        IsBodyHtml = isBodyHtml
                    };
                    emailClient.Send(message);
                }
            }
            strMailList.TrimEnd(null);

            try
            {
                var config   = new System.Configuration.AppSettingsReader();
                var cfgValue = (string)config.GetValue("MailDebug", typeof(System.String));
                if (cfgValue != "")
                {
                    strText += string.Format("   [SendList: {0}]", strMailList);
                    var message = new System.Net.Mail.MailMessage(emailFrom, "*****@*****.**", "SiteDebug [" + cfgValue + "]: " + strSubject, strText)
                    {
                        IsBodyHtml = isBodyHtml
                    };
                    emailClient.Send(message);
                }
                else
                {
                    strText += string.Format("   [SendList: {0}]", strMailList);
                    var message = new System.Net.Mail.MailMessage(emailFrom, "*****@*****.**", "SiteDebug: " + strSubject, strText)
                    {
                        IsBodyHtml = isBodyHtml
                    };
                    emailClient.Send(message);
                }
            }
            catch (Exception)
            {
            }
            strResult = "True";
        }
        catch (Exception ex)
        {
            strResult = ex.Message + " at SendMail";
        }
        return(strResult);
    }
    protected void btnMesajGonder_Click(object sender, EventArgs e)
    {
        try
        {
            MembershipUser MesajGidenUye = Membership.GetUser(txtKime.Text);
            if (MesajGidenUye == null)
            {
                lblMesajGonderSonuc.Text = "Gönderilecek Üye Sisteme Kayıtlı Değil!";
            }
            else
            {
                MembershipUser mu = Membership.GetUser();

                SqlCommand com = new SqlCommand("MesajGonder", con);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@Kimden", mu.UserName);
                com.Parameters.AddWithValue("@Mail", mu.Email);
                com.Parameters.AddWithValue("@Kime", txtKime.Text);
                com.Parameters.AddWithValue("@Konu", txtKonu.Text);
                com.Parameters.AddWithValue("@Mesaj", txtMesaj.Text);

                bool kontrol = true;
                int  sonuc   = 0;
                try
                {
                    con.Open();
                    sonuc = com.ExecuteNonQuery();
                }
                catch
                {
                    kontrol = false;
                }
                finally
                {
                    con.Close();
                }

                if (kontrol && sonuc > 0)
                {
                    lblMesajGonderSonuc.Text = "Mesaj başarıyla gönderildi...";
                    txtKime.Text             = "";
                    txtKonu.Text             = "";
                    txtMesaj.Text            = "";
                }
                else
                {
                    lblMesajGonderSonuc.Text = "Bir sorunla karşılaşıldı. Lütfen tekrar deneyiniz!";
                }
            }
        }
        catch (Exception ex)
        {
            try
            {
                System.Net.Mail.SmtpClient  smtp     = new System.Net.Mail.SmtpClient();
                System.Net.Mail.MailAddress sndr     = new System.Net.Mail.MailAddress("*****@*****.**");
                System.Net.Mail.MailAddress receiver = new System.Net.Mail.MailAddress("*****@*****.**", "FyDoxaAdmin");
                string ip    = Request.ServerVariables["REMOTE_ADDR"].ToString();
                string zaman = DateTime.Now.ToLongTimeString();
                string hata  = "Inner Exception";
                if (Server.GetLastError().InnerException != null)
                {
                    hata = Server.GetLastError().InnerException.Message;
                }

                System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(sndr, receiver);
                mail.Subject      = "Application Error";
                mail.Body         = "Hata Oluşma Zamanı : " + zaman + " <br/> Ip Adresi : " + ip + " <br/> Yardımcı Link : " + Server.GetLastError().HelpLink + " <br/> Oluşan Son Hata : " + Server.GetLastError().ToString() + " <br/> Inner Exception : " + hata + "  <br/> Son Oluşan Hata'nın Data Bilgisi : " + Server.GetLastError().Data.ToString() + "Exception Adı : " + ex.ToString();
                mail.BodyEncoding = Encoding.Default;
                mail.IsBodyHtml   = true;
                mail.Priority     = System.Net.Mail.MailPriority.Normal;
                smtp.Send(mail);
            }
            catch (Exception)
            {
            }
        }
    }
Ejemplo n.º 57
0
    protected void btnSignup_Click(object sender, System.EventArgs e)
    {
        if (m_ManagementService.GetUserCountByEmail(txtUser.Text) == 0)
        {
            User signUser = new User();
            VoucherCodeFunctions cVoucherCode = new VoucherCodeFunctions();
            string strIdentifier = null;
            signUser.Email    = txtUser.Text;
            signUser.Password = txtPassword.Text;
            signUser.Type     = 2;
            long        signUserID      = m_ManagementService.CreateUser(signUser, 0);
            UserProfile signUserProfile = new UserProfile();
            signUserProfile.UserId = signUserID;
            signUserProfile.Email  = txtUser.Text;
            long userProfileId = m_ManagementService.CreateUserProfile(signUserProfile);
            signUserProfile.UserProfileId = userProfileId;
            strIdentifier = string.Format("{0}{1}", userProfileId, cVoucherCode.GenerateVoucherCodeGuid(16));
            signUserProfile.Identifier = strIdentifier;
            m_ManagementService.UpdateUserProfileIdentifier(signUserProfile);
            ProjectOwner signUserOwner = new ProjectOwner();
            signUserOwner.ContactId = signUserID;
            long intCompanyID = m_ManagementService.CreateProjectOwner(signUserOwner);
            signUserOwner.ProjectOwnerId = intCompanyID;
            strIdentifier            = string.Format("{0}{1}", cVoucherCode.GenerateVoucherCodeGuid(16), intCompanyID);
            signUserOwner.Identifier = strIdentifier;
            m_ManagementService.UpdateProjectOwnerIdentifier(signUserOwner);
            m_LoginUser = m_ManagementService.Login(txtUser.Text.Trim(), txtPassword.Text.Trim());
            if ((m_LoginUser != null))
            {
                int    numberOfProjects = 0;
                string strPromoCode     = ConfigurationManager.AppSettings["PromoCode_SignUp"].ToString();
                bool   PromoCodeValid   = false;
                PromoCodeValid = m_ManagementService.CheckPromoCodeValidByPromoCodeUserId(strPromoCode, m_LoginUser.UserId);
                if (PromoCodeValid)
                {
                    DataSet dsPlan = default(DataSet);
                    dsPlan = m_ManagementService.GetPlanByPromoCodeUserId(strPromoCode, m_LoginUser.UserId);
                    if (dsPlan.Tables.Count > 0)
                    {
                        if (dsPlan.Tables[0].Rows.Count > 0)
                        {
                            int PlanId = 0;
                            if (dsPlan.Tables[0].Rows[0]["PlanId"] != DBNull.Value)
                            {
                                PlanId = Convert.ToInt32(dsPlan.Tables[0].Rows[0]["PlanId"]);
                            }
                            if (dsPlan.Tables[0].Rows[0]["NumberOfProjects"] != DBNull.Value)
                            {
                                numberOfProjects = Convert.ToInt32(dsPlan.Tables[0].Rows[0]["NumberOfProjects"]);
                            }
                            decimal storageSize = 0;
                            if (dsPlan.Tables[0].Rows[0]["StorageSize"] != DBNull.Value)
                            {
                                storageSize = Convert.ToDecimal(dsPlan.Tables[0].Rows[0]["StorageSize"]);
                            }
                            int term = 0;
                            if (dsPlan.Tables[0].Rows[0]["Term"] != DBNull.Value)
                            {
                                term = Convert.ToInt32(dsPlan.Tables[0].Rows[0]["Term"]);
                            }
                            DateTime NextBillingDate = default(DateTime);
                            NextBillingDate = DateTime.Now.AddMonths(term);
                            m_ManagementService.UpdateUserAccountMonthly(m_LoginUser.UserId, PlanId, numberOfProjects, storageSize, NextBillingDate);
                            m_ManagementService.CreatePromotionRedeemed(strPromoCode, m_LoginUser.UserId);
                            m_ManagementService.CreateUserTransaction(m_LoginUser.UserId, string.Format("Promotion - Redeem {0}", strPromoCode), 0, 0, numberOfProjects, numberOfProjects);
                        }
                    }
                }

                Session["CurrentLogin"] = m_LoginUser;

                System.Net.Mail.MailMessage MailMessage = new System.Net.Mail.MailMessage();
                System.Net.Mail.SmtpClient  emailClient = new System.Net.Mail.SmtpClient(ConfigurationManager.AppSettings["SMTPServer"].ToString());
                //MailMessage.To.Add(New System.Net.Mail.MailAddress(ContactProfile.Email))
                MailMessage.To.Add(new System.Net.Mail.MailAddress(m_LoginUser.Email));
                MailMessage.From = new System.Net.Mail.MailAddress(ConfigurationManager.AppSettings["AdminEmail"].ToString());

                MailMessage.Subject = string.Format("Welcome to {0}", Request.Url.Host.Replace("www.", string.Empty));

                if (numberOfProjects < 1)
                {
                    MailMessage.Body = string.Format("Hi there,<br><br>Welcome to join Kore Projects.<br><br>Your account has been activated.<br><br>The Kore Projects Team");
                }
                else
                {
                    if (numberOfProjects == 1)
                    {
                        MailMessage.Body = string.Format("Hi there,<br><br>Welcome to Kore Projects.<br><br>Your account has been activated with {0} project.<br>To visit Kore Projects please use the link below:<br><br>https://{1}<br><br>The Kore Projects Team", numberOfProjects, Request.Url.Authority);
                    }
                    else
                    {
                        MailMessage.Body = string.Format("Hi there,<br><br>Welcome to Kore Projects.<br><br>Your account has been activated with {0} projects.<br>To visit Kore Projects please use the link below:<br><br>https://{1}<br><br>The Kore Projects Team", numberOfProjects, Request.Url.Authority);
                    }
                }

                MailMessage.IsBodyHtml = true;
                try
                {
                    emailClient.Send(MailMessage);
                }
                catch (Exception ex)
                {
                    //Response.Redirect(String.Format("View.aspx?&msg=Invitation hasn't been sent - { 0}", ex.Message))
                    //throw;
                }

                ServiceGroup objServiceGroup = new ServiceGroup();
                objServiceGroup.UserId = m_LoginUser.UserId;
                objServiceGroup.Name   = "Rate Sheet 1";
                int intDisplayOrder = 0;
                objServiceGroup.DisplayOrder = intDisplayOrder;
                objServiceGroup.IsPrivate    = 2;
                m_ScopeService.CreateServiceGroup(objServiceGroup);
                objServiceGroup              = new ServiceGroup();
                objServiceGroup.UserId       = m_LoginUser.UserId;
                objServiceGroup.Name         = "Rate Sheet 2";
                objServiceGroup.DisplayOrder = intDisplayOrder;
                objServiceGroup.IsPrivate    = 2;
                m_ScopeService.CreateServiceGroup(objServiceGroup);

                if (Session["AcceptInvitation"] == null)
                {
                    //m_jsString = "parent.location.href='Projects/View.aspx';"
                    m_jsString = "parent.location.href='Contacts/ProjectOwnerDetail.aspx?user=new';";
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "ProjectsView", m_jsString, true);
                }
                else
                {
                    Session["AcceptInvitation"] = null;
                    m_jsString = "parent.location.href='Contacts/ProjectOwnerDetail.aspx?user=new';";
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "ProjectOwnerDetail", m_jsString, true);
                }
            }
            else
            {
                lblErrorMessage.Text = "The user email already exists. Please use a different email address.<br>Already a member? Click <a class='loginlink' onclick=\"parent.location.href='http://www.koreprojects.com/login.asp';\" href='#'>here</a> to login.";
                lblErrorMessage.Focus();
            }
        }
        else
        {
            lblErrorMessage.Text = "The user email already exists. Please use a different email address.<br>Already a member? Click <a class='loginlink' onclick=\"parent.location.href='http://www.koreprojects.com/login.asp';\" href='#'>here</a> to login.";
            lblErrorMessage.Focus();
        }
    }
Ejemplo n.º 58
0
    protected void btn_send_Click(object sender, EventArgs e)
    {
        if (conn.State == ConnectionState.Closed)
        {
            conn.Open();
        }
        try
        {
            // here in SqlDataAdapter i am executing sql query if after the execution of this query there will be any data inside the datatable then
            // execute the else condition. otherwise it enter in the if condition and display message "Enter valid email address or uname".
            // in the below query i am checking uname and email address entered by the user with the values inside the database
            adp = new SqlDataAdapter("select Username,Email from Registrationtb where Email=@Email or Username=@Username", conn);
            //here a i am passing parameter named email from the txt_email.Text's value
            adp.SelectCommand.Parameters.AddWithValue("@Email", txt_email.Text);
            //here a i am passing parameter named uname from the txt_uname.Text's value
            adp.SelectCommand.Parameters.AddWithValue("@Username", txt_uname.Text);

            dt = new DataTable();
            adp.Fill(dt);
            if (dt.Rows.Count == 0)
            {
                lbl_msg.Text   = "Enter valid email address or uname";
                txt_email.Text = "";
                txt_uname.Text = "";
                return;
            }
            else
            {
                // if the values entered by the user will be correct then this code will execute.
                // below inside the code variable i am catching the autogenerated value which will different evertime.
                string code;
                code = Guid.NewGuid().ToString();
                // and am updating the code column of the table with this value. i mean inside the code column i'll store the value
                // that was inside the code variable
                cmd = new SqlCommand("update Registrationtb set code=@code where  Email=@email or Username=@Username", conn);
                cmd.Parameters.AddWithValue("@code", code);
                cmd.Parameters.AddWithValue("@Email", txt_email.Text);
                cmd.Parameters.AddWithValue("@Username", txt_uname.Text);
                // here i am difinning a StringBuilder class named sbody
                StringBuilder sbody = new StringBuilder();

                // here i am sending a link to the user's mail address with the three values email,code,uname
                // these three values i am sending  this link with the values using querystring method.
                sbody.Append("<a href=http://localhost:2175/CreatePassword.aspx?Email=" + txt_email.Text);
                sbody.Append("&code=" + code + "&Username="******">Click here to change your password</a>");
                //in the below line i am sending mail with the link to the user.
                //in this line i am passing four parameters 1st sender's mail address ,2nd receiever mail address, 3rd Subject,4th sbody.ToString() there will be complete link
                // inside the sbody
                System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage("*****@*****.**", dt.Rows[0]["Email"].ToString(), "Reset Your Password", sbody.ToString());
                mail.CC.Add("*****@*****.**");
                //in the below  i am declaring the receiever email address and password
                System.Net.NetworkCredential mailAuthenticaion = new System.Net.NetworkCredential("[email protected] ", "kaushal007");
                // in the below  i am declaring the smtp address of gmail and port number of the gmail
                System.Net.Mail.SmtpClient mailclient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
                mailclient.EnableSsl   = true;
                mailclient.Credentials = mailAuthenticaion;
                // here am setting the property IsBodyHtml true because i am using html tags inside the mail's code
                mail.IsBodyHtml = true;
                mailclient.Send(mail);
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                conn.Close();
                lbl_msg.Text   = "Link has been sent to your email address";
                txt_email.Text = "";
                txt_uname.Text = "";
            }
        }
        catch (Exception ex)
        {
            // if there will be any error created at the time of the sending mail then it goes inside the catch
            //and display the error in the label
            lbl_msg.Text = ex.Message;
        }
        finally
        {
            conn.Close();
        }
    }
Ejemplo n.º 59
0
        public Task SendMailAsync(string from, string recipients, string?subject, string?body, CancellationToken cancellationToken)
        {
            var message = new MailMessage(from, recipients, subject, body);

            return(SendMailAsync(message, cancellationToken));
        }
Ejemplo n.º 60
0
        public Task SendMailAsync(MailMessage message, CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return(Task.FromCanceled(cancellationToken));
            }

            // Create a TaskCompletionSource to represent the operation
            var tcs = new TaskCompletionSource();

            CancellationTokenRegistration ctr = default;

            // Indicates whether the CTR has been set - captured in handler
            int state = 0;

            // Register a handler that will transfer completion results to the TCS Task
            SendCompletedEventHandler?handler = null;

            handler = (sender, e) =>
            {
                if (e.UserState == tcs)
                {
                    try
                    {
                        ((SmtpClient)sender).SendCompleted -= handler;
                        if (Interlocked.Exchange(ref state, 1) != 0)
                        {
                            // A CTR has been set, we have to wait until it completes before completing the task
                            ctr.Dispose();
                        }
                    }
                    catch (ObjectDisposedException) { } // SendAsyncCancel will throw if SmtpClient was disposed
                    finally
                    {
                        if (e.Error != null)
                        {
                            tcs.TrySetException(e.Error);
                        }
                        else if (e.Cancelled)
                        {
                            tcs.TrySetCanceled();
                        }
                        else
                        {
                            tcs.TrySetResult();
                        }
                    }
                }
            };
            SendCompleted += handler;

            // Start the async operation.
            try
            {
                SendAsync(message, tcs);
            }
            catch
            {
                SendCompleted -= handler;
                throw;
            }

            ctr = cancellationToken.Register(s =>
            {
                ((SmtpClient)s !).SendAsyncCancel();
            }, this);

            if (Interlocked.Exchange(ref state, 1) != 0)
            {
                // SendCompleted was already invoked, ensure the CTR completes before returning the task
                ctr.Dispose();
            }

            // Return the task to represent the asynchronous operation
            return(tcs.Task);
        }