public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            string displayName = string.Empty;
            string address = string.Empty;
            while (reader.Read())
            {
                var tokenType = reader.TokenType;
                if (reader.TokenType == JsonToken.PropertyName)
                {
                    var val = (reader.Value as string )?? string.Empty;
                    if (val == "DisplayName")
                    {
                        displayName = reader.ReadAsString();
                    }
                    if (val == "Address")
                    {
                        address = reader.ReadAsString();
                    }
                }

                if (reader.TokenType == JsonToken.EndObject)
                {
                    break;
                }
            }

            var mailAddress = new MailAddress(address, displayName);
            return mailAddress;
        }
Пример #2
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);
 }
Пример #3
0
        public static void SendMail(string subject, string body, ICollection<string> recipients)
        {
            var fromAddress = new MailAddress("*****@*****.**", "Bearchop");

            const string fromPassword = "******";

            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
            };

            var message = new MailMessage();

            message.From = fromAddress;
            message.Subject = subject;
            message.Body = body;

            var toList = string.Join(",", recipients);

            message.To.Add(toList);

            smtp.Send(message);
        }
        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());
            }
        }
Пример #5
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);
        }
Пример #6
0
        public static void SendForgotPasswordMail(string email, string callbackUrl)
        {
            try
            {
                using (SmtpClient mailClient = new SmtpClient("smtp.office365.com", 587))
                {
                    //Your SmtpClient gets set to the SMTP Settings you found in the "POP, IMAP, and SMTP access" section from Web Outlook
                    //Your Port gets set to what you found in the "POP, IMAP, and SMTP access" section from Web Outlook
                    mailClient.Port = 587;
                    //Set EnableSsl to true so you can connect via TLS
                    mailClient.EnableSsl = true;
                    //Your network credentials are going to be the Office 365 email address and the password
                    mailClient.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Admin2016");
                    var from = new MailAddress("*****@*****.**", "Administracion Cent11", System.Text.Encoding.UTF8);
                    var to = new MailAddress(email);

                    MailMessage message = new MailMessage(from, to);

                    message.Subject = "Restablecer contraseña";
                    message.IsBodyHtml = true;
                    message.Body = "Para restablecer la contraseña, haga clic <a href=\"" + callbackUrl + "\">aquí</a>";
                    mailClient.Send(message);
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
Пример #7
0
        public static void Send(float ram, float cpu, List<DriveInfo> diskSummary, string subject, List<EventLogEntry> lastLogs)
        {
            MailAddress to = new MailAddress(Properties.Settings.Default.MailTo);
            MailAddress from = new MailAddress(Properties.Settings.Default.MailFrom);
            MailMessage mail = new MailMessage(Properties.Settings.Default.MailFrom, Properties.Settings.Default.MailTo);

            mail.Subject = subject;
            StringBuilder builder = new StringBuilder();
            builder.Append("Your CPU Usage: " +cpu+ "\n\nYour RAM Usage: " +ram+ "\n\n");

            foreach (DriveInfo disksToWrite in diskSummary)
            {
                builder.AppendLine(string.Format("{0} {1} GB Free Space of {2} GB Total Size;\n", disksToWrite.Name, ByteConverter.GetGigaBytesFromBytes(disksToWrite.TotalFreeSpace), ByteConverter.GetGigaBytesFromBytes(disksToWrite.TotalSize)));
            }

            foreach (EventLogEntry logsToWrite in lastLogs)
            {
                builder.AppendLine(string.Format("{0}; Event ID: {1}; {2}; {3};", logsToWrite.TimeGenerated, logsToWrite.InstanceId, logsToWrite.EntryType,
                                             logsToWrite.Message));
            }
            builder.AppendLine("\n\n" + subject);
            mail.Body = builder.ToString();
            SmtpClient smtp = new SmtpClient();
            smtp.Host = Properties.Settings.Default.MailSmtpServer;
            smtp.Port = Properties.Settings.Default.MailSmtpPort;

            smtp.Credentials = new NetworkCredential(
                Properties.Settings.Default.MailFrom, Properties.Settings.Default.MailPassword);
            smtp.EnableSsl = true;
            smtp.Send(mail);
        }
Пример #8
0
        public ApiRequest ParseRequestInfo(string address)
        {
            try
            {
                var mailAddress = new MailAddress(address);

                var match = RouteRegex.Match(mailAddress.User);

                if (!match.Success)
                    return null;

                var tenant = CoreContext.TenantManager.GetTenant(mailAddress.Host);

                if (tenant == null)
                    return null;

                var groups = RouteRegex.GetGroupNames().ToDictionary(groupName => groupName, groupName => match.Groups[groupName].Value);
                var requestInfo = ParseRequestInfo(groups, tenant);

                requestInfo.Method = "POST";
                requestInfo.Tenant = tenant;

                if (!string.IsNullOrEmpty(requestInfo.Url))
                    requestInfo.Url = string.Format("api/2.0/{0}.json", requestInfo.Url);

                return requestInfo;
            }
            catch
            {
                return null;
            }
        }
Пример #9
0
        private void Send_Click(object sender, EventArgs e)
        {
            try
            {
                Output.Text = string.Empty;
                FileInfo file = new FileInfo(_file);
                StreamReader rdr = file.OpenText();
                string messageBody = rdr.ReadToEnd();
                rdr.Dispose();

                SmtpClient client = new SmtpClient("some.mail.server.example.com");
                client.Credentials = new NetworkCredential("someuser", "somepassword");
                MailAddress from = new MailAddress("*****@*****.**");
                MailAddress to = new MailAddress("*****@*****.**");
                MailMessage msg = new MailMessage(from, to);
                msg.Body = messageBody;
                msg.Subject = "Test message";
                //client.Send(msg);

                Output.Text = "Sent email with body: " + Environment.NewLine + messageBody;
            }
            catch (Exception ex)
            {
                Output.Text = ex.ToString();
            }
        }
Пример #10
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);
            }
        }
Пример #11
0
		static QueueProcessor()
		{
			int bt;
			if (!int.TryParse(ConfigurationManager.AppSettings["MailBufferTimeout"], out bt))
				bt = 30;
			BufferTimeout = TimeSpan.FromSeconds(bt);
			if (!int.TryParse(ConfigurationManager.AppSettings["MailBufferCount"], out BufferCount))
				BufferCount = 10;
			else if (BufferCount < 1)
				BufferCount = 1;
			var toEmail = ConfigurationManager.AppSettings["Mailer.Admin"];
			var fromEmail = ConfigurationManager.AppSettings["Mailer.From"] ?? "no-reply@" + Environment.MachineName;
			try
			{
				ToAdminEmail = new MailAddress(toEmail);
				FromEmail = new MailAddress(fromEmail);
			}
			catch { }
			if (ToAdminEmail == null || FromEmail == null)
				throw new ConfigurationErrorsException(@"Please define valid admin email settings: Mailer.Admin and Mailer.From. Example:
<appSettings>
	<add key=""Mailer.Admin"" value=""*****@*****.**"" />
	<add key=""Mailer.From"" value=""*****@*****.**"" />
</appSettings>");
		}
Пример #12
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);
        }
        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);
        }
        protected string isValid()
        {
            string errors = "";
            if (ProviderName.Text == "")
            {
                errors += "Provider Name is required. ";
            }

            if (ProviderEmail.Text != "")
            {
                try
                {
                    MailAddress m = new MailAddress(ProviderEmail.Text);
                }
                catch (FormatException)
                {
                    errors += "Invalid Email. ";
                }
            }

            if (ProviderPhone.Text != "")
            {
                if (ProviderPhone.Text.Replace("-", "").Length != 10)
                {
                    errors += "Phone Number must be exactly 10 digits. ";
                }
                else if (!isDigit(ProviderPhone.Text.Replace("-", "")))
                {
                    errors += "Invalid Phone Number. ";
                }
            }

            return errors;
        }
Пример #15
0
        public ViewResult Contact(Contact contact)
        {
            if (ModelState.IsValid)
            {
                using (var client = new SmtpClient())
                {
                    var adminEmail = ConfigurationManager.AppSettings["AdminEmail"];
                    var from = new MailAddress(adminEmail, "MatlabBlog Messenger");
                    var to = new MailAddress(adminEmail, "MatlabBlog Admin");

                    using (var message = new MailMessage(from, to))
                    {
                        message.Body = contact.Body;
                        message.IsBodyHtml = true;
                        message.BodyEncoding = Encoding.UTF8;

                        message.Subject = contact.Subject;
                        message.SubjectEncoding = Encoding.UTF8;

                        message.ReplyTo = new MailAddress(contact.Email);

                        client.Send(message);
                    }
                }

                return View("Thanks");
            }

            return View();
        }
Пример #16
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.
            }
        }
Пример #17
0
 public static void sendMail(String host, String user, String pwd, String fromMail, String toMail, String subject, String strbody)
 {
     // Command line argument must the the SMTP host.
     SmtpClient client = new SmtpClient(host, 25);
     client.Credentials = new System.Net.NetworkCredential(user, pwd);
     // Specify the e-mail sender.
     // Create a mailing address that includes a UTF8 character
     // in the display name.
     MailAddress from = new MailAddress(fromMail, "Tradestation",
     System.Text.Encoding.UTF8);
     // Set destinations for the e-mail message.
     MailAddress to = new MailAddress(toMail);
     // Specify the message content.
     MailMessage message = new MailMessage(from, to);
     message.Body = strbody;
     // Include some non-ASCII characters in body and subject.
     string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' });
     message.Body += Environment.NewLine + someArrows;
     message.BodyEncoding = System.Text.Encoding.UTF8;
     message.Subject = subject + someArrows;
     message.SubjectEncoding = System.Text.Encoding.UTF8;
     // Set the method that is called back when the send operation ends.
     client.SendCompleted += new
     SendCompletedEventHandler(SendCompletedCallback);
     // The userState can be any object that allows your callback
     // method to identify this send operation.
     // For this example, the userToken is a string constant.
     string userState = "test message1";
     client.Send(message);
     // Clean up.
     message.Dispose();
     Console.WriteLine("Goodbye.");
 }
Пример #18
0
        public static void send(string _body, string toEmail)
        {
            var fromAddress = new MailAddress("*****@*****.**", "Selenium");
            var toAddress = new MailAddress(toEmail, "H&C");
            const string fromPassword = "******";
            const string subject = "Selenium Log";
            string body = _body;

            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 = body
                })
            {
                smtp.Send(message);
            }
        }
Пример #19
0
 /// <summary>
 ///  Use to send messages via e-mail to specific account.
 /// </summary>
 /// <param name="acc">Account , to which e-mail will be sended.</param>
 /// <param name="text">Sended text</param>
 /// <param name="sub">Subject of letter</param>
 public static void SendMail(Account acc, string text,string sub)
 {
     MailAddress fromAddress = new MailAddress("*****@*****.**", "SolarAnalys");
     var toAddress = new MailAddress(acc.Email);
     string fromPassword = "******";
     //AccountSecurityToken token = new AccountSecurityToken(acc);
     string subject=sub??"", body= text??"";
     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 = body
     })
     {
         message.IsBodyHtml = true;
         smtp.Send(message);
     }
 }
Пример #20
0
        private void okButton_Click(object sender, EventArgs e)
        {
            MailAddress userMailAddress;

            try
            {
                if (string.IsNullOrEmpty(emailTextBox.Text))
                {
                    throw new FormatException();
                }

                userMailAddress = new MailAddress(emailTextBox.Text);
            }
            catch (FormatException)
            {
                MessageBox.Show("Неверный формат электронной почты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            User newUser = new User(DataManager.lastUserID++, nameTextBox.Text, userMailAddress, newUserType);

            DataManager.Users.Add(newUser);

            mainForm.MainTreeView.SelectedNode.Nodes.Add(newUser.Name);

            DialogResult = DialogResult.OK;
        }
        public ActionResult Index(string name, string email, string phone, string message)
        {
            try
            {
                //Create the msg object to be sent
                MailMessage msg = new MailMessage();
                //Add your email address to the recipients
                msg.To.Add("*****@*****.**");
                //Configure the address we are sending the mail from
                MailAddress address = new MailAddress("*****@*****.**");
                msg.From = address;
                msg.Subject = "Website Feedback";
                string body = "From: " + name + "\n";
                body += "Email: " + email + "\n";
                body += "phone: " + phone + "\n\n";
                body += message + "\n";
                msg.Body = body;

                SmtpClient client = new SmtpClient();
                client.Host = "relay-hosting.secureserver.net";
                client.Port = 25;
                //Send the msg
                client.Send(msg);

                ViewBag.msg = "Mail Sent. Thank You For Contacting Us.";
                return View();
            }
            catch(Exception)
            {
                ViewBag.msg = "Something Is Wrong. Try Again.";
                return View();
            }
        }
Пример #22
0
        public static bool SendEmail(string EmailToAddress, string emailCCAddresses, string messageBody, string mailSubject)
        {
            SmtpClient client = new SmtpClient();

            try
            {
                MailAddress maFrom = new MailAddress("*****@*****.**", "website", Encoding.UTF8);
                MailAddress maTo = new MailAddress(EmailToAddress, EmailToAddress, Encoding.UTF8);
                MailMessage mmsg = new MailMessage(maFrom.Address, maTo.Address);

                mmsg.Body = messageBody;
                mmsg.BodyEncoding = Encoding.UTF8;
                mmsg.IsBodyHtml = true;
                mmsg.Subject = mailSubject;
                mmsg.SubjectEncoding = Encoding.UTF8;

                if (!string.IsNullOrEmpty(emailCCAddresses))
                {
                    mmsg.CC.Add(emailCCAddresses);
                }

                client.Send(mmsg);

                return true;
            }

            catch (Exception ex)
            {
                ExceptionHelper.SendExceptionEmail(ex);

                return false;
            }
            return true;
        }
        public bool RequestNotification(string notificationUid, string address, string value)
        {
            _Trace.TraceEvent(TraceEventType.Verbose, (int)Events.SendRequest, string.Format("RequestNotification( {0}, {1}, {2} )", notificationUid, address, value));

            MailAddress to = new MailAddress(address);
            MailMessage message = new MailMessage(_Emailer.From, to);
            message.Subject = _Subject;
            message.Body = value;
            try
            {
                _Emailer.Client.Send(message);
            }
            catch (System.Net.Mail.SmtpFailedRecipientException ex)
            {
                _Trace.TraceEvent(TraceEventType.Error, (int)Events.SendError, string.Format("{0}\r\n{1}", notificationUid, ex.ToString()));
                return false;
            }
            catch (System.Net.Mail.SmtpException ex)
            {
                _Trace.TraceEvent(TraceEventType.Error, (int)Events.SendError, string.Format("{0}\r\n{1}", notificationUid, ex.ToString()));
                return false;
            }
            _Trace.TraceEvent(TraceEventType.Verbose, (int)Events.SendSuccess, notificationUid);
            return true;
        }
Пример #24
0
        public MailMessage GetMessage(Guid queueId)
        {
            using (var db = new EmailQueueConnections())
            {

                var queue = db.QueueMasters.Join(db.Messages, q => q.MessageId, m => m.Id,
                    (q, m) => new { q.Id, q.MessageId, m.Emails, q.Message }).Where(m => m.Id == queueId).ToList();

                var messageId = queue.First().MessageId;
                var attachments = db.Attachments.Where(a => a.MessageId == messageId).ToList();
                var emailFromAddress = db.Emails.Where(e => e.MessageId == messageId && e.IsSender == true).Select(y => y.EmailAddress).First();
                var emailToAddress = db.Emails.Where(e => e.MessageId == messageId && e.IsSender == false).Select(y => y.EmailAddress).First();
                var subject = queue.First().Message.Subject;
                var body = queue.First().Message.Body;

                MailAddress emailAddressFrom = new MailAddress(emailFromAddress);
                MailAddress emailAddressTo = new MailAddress(emailToAddress);
                MailMessage mailMessage = new MailMessage(emailAddressFrom, emailAddressTo);

                mailMessage.Headers.Add(Constant.QueueId, queueId.ToString());
                mailMessage.Subject = subject;
                mailMessage.Body = body;

                return mailMessage;
            }
        }
Пример #25
0
        public void Send(EmailContents emailContents)
        {
            SmtpClient client = new SmtpClient(SMTPServerName);
            client.UseDefaultCredentials = true;
            MailAddress from = new MailAddress(emailContents.FromEmailAddress, emailContents.FromName);
            MailAddress to = new MailAddress(ToAddress);
            MailAddress bcc = new MailAddress(emailContents.Bcc);
            MailAddress cc = new MailAddress(emailContents.Cc);
            MailMessage message = new MailMessage(from, to);

            message.Bcc.Add(bcc);
            message.CC.Add(cc);
            message.Subject = emailContents.Subject;
            message.Body = Utilities.FormatText(emailContents.Body, true);
            message.IsBodyHtml = true;

            try
            {
                client.Send(message);
                IsSent = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #26
0
        public static bool SendInscripcion(string email, string url, string html)
        {
            try
            {
                using (SmtpClient mailClient = new SmtpClient("smtp.office365.com", 587))
                {
                    //Your SmtpClient gets set to the SMTP Settings you found in the "POP, IMAP, and SMTP access" section from Web Outlook
                    //SmtpClient mailClient = new SmtpClient("smtp.office365.com");
                    //Your Port gets set to what you found in the "POP, IMAP, and SMTP access" section from Web Outlook
                    mailClient.EnableSsl = true;
                    mailClient.UseDefaultCredentials = false;
                    //Set EnableSsl to true so you can connect via TLS
                    //Your network credentials are going to be the Office 365 email address and the password
                    mailClient.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Admin2016");

                    var from = new MailAddress("*****@*****.**", "Administracion Cent11",System.Text.Encoding.UTF8);
                    var to = new MailAddress(email);

                    MailMessage message = new MailMessage(from, to);
                    message.Subject = "Formulario de Inscripcion";
                    message.IsBodyHtml = true;
                    message.Body = html;

                    mailClient.Send(message);
                    return true;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
Пример #27
0
        public async Task<Autodiscover> Start(string domainOrUsername)
        {
            var domain = domainOrUsername;

            try
            {
                domain = new MailAddress(domainOrUsername).Host;
            }
            catch (FormatException)
            {
            }

            var response = await DiscoverSection(true, domain);
            if (response == null || (response != null && response.Data == null))
            {
                response = await DiscoverSection(false, domain);
            }

            if (response != null && response.Data != null)
            {
                return await FollowRedirects(response.Data.FromBytes<Autodiscover>());
            }
            else
            {
                throw new DiscoveryException(string.Format("Discovery was unable to find resource for domain: {0}", domain));
            }
        }
Пример #28
0
		public virtual void SendEmail(EmailServerSettings settings, string subject, string body, IEnumerable<MailAddress> toAddressList, MailAddress fromAddress, params EmailAttachmentData[] attachments)
		{
			using (var smtpClient = GetSmtpClient(settings))
			{
				var message = new MailMessage();
				message.From = fromAddress;
				message.Body = body;
				message.Subject = subject;
				message.IsBodyHtml = true;
				foreach (var toAddress in toAddressList)
				{
					message.To.Add(toAddress);
				}

				if (attachments != null)
				{
					foreach (var item in attachments)
					{
						var stream = StreamHelper.CreateMemoryStream(item.AttachmentData);
						stream.Position = 0;

						var attachment = new Attachment(stream, item.FileName);

						message.Attachments.Add(attachment);
					}
				}

				smtpClient.Send(message);
			}
		}
Пример #29
0
        public void SendSingle()
        {
            try
            {
                SmtpClient smtpClient = new SmtpClient();

                // Check which env. we are dev, prod?!
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;

                MailAddress mailFrom = new MailAddress("*****@*****.**", "Pasted.Net");
                MailAddress mailTo = new MailAddress("*****@*****.**" ,"Hello You");

                MailMessage mailToSend = new MailMessage(mailTo, mailFrom);
                mailToSend.Subject = "Pasted expires in x days";
                mailToSend.SubjectEncoding = System.Text.Encoding.UTF8;

                mailToSend.Body = "Your pasted xya will expire...";
                mailToSend.BodyEncoding = System.Text.Encoding.UTF8;
                mailToSend.IsBodyHtml = false;

                smtpClient.Send(mailToSend);
            }
            catch (SmtpException e)
            {
                throw new SmtpException(e.Message);
            }
        }
Пример #30
0
        public static string Send(string from, string name, string msg)
        {
            try
            {
                From = new MailAddress(from);
                To = new MailAddress("*****@*****.**");
                mail = new MailMessage(From, To);
                smtp = new SmtpClient();

                mail.Subject = string.Format("You have message from {0}", name);
                mail.Body = msg;

                smtp.Host = "mail.epaila.com";
                smtp.Port = 8889;

                smtp.Credentials = new NetworkCredential("*****@*****.**", "*****@*****.**");
                //smtp.EnableSsl = true;

                smtp.Send(mail);
            }
            catch(Exception ex)
            {
                return "Fail";
            }
            return "Sent";
        }
Пример #31
0
        public static bool isEmail(String s)
        {
            //try
            //{
            //    int num = s.IndexOf('@');
            //    int num2 = s.IndexOf('.');

            //    if (!string.IsNullOrEmpty(s) && (s[0] != ' ' || s[0] != '\t' || s[0] != '.'))
            //    {
            //        if (s.EndsWith(".com") || s.EndsWith(".lk"))
            //        {
            //            if (num < num2 && (num + 1) != num2)
            //            {
            //                return true;
            //            }
            //            else
            //            {
            //               MessageBox.Show(null, "invalid email id", "error");
            //                return false;
            //            }
            //        }
            //        else
            //        {
            //            MessageBox.Show(null, "enter a valid email id", "error");
            //            return false;
            //        }
            //    }
            //    else
            //    {
            //        MessageBox.Show(null, "enter a valid email id", "error");
            //        return false;
            //    }

            //}
            //catch
            //{
            //    return false;
            //}

            try
            {
                var addr = new System.Net.Mail.MailAddress(s);
                return(addr.Address == s);
            }
            catch
            {
                return(false);
            }
        }
Пример #32
0
        public static bool ValidateEmail(String email)
        {
            bool b = false;

            try
            {
                var addr = new System.Net.Mail.MailAddress(email);
                b = addr.Address == email;
            }
            catch
            {
                b = false;
            }
            return(b);
        }
 /*
  * FUNCTION : IsValidEmail
  *
  * DESCRIPTION : Validates email
  *
  * PARAMETERS : string email - email to be validated.
  *
  * RETURNS : bool - success or fail.
  */
 bool IsValidEmail(string email)
 {
     try
     {
         var addr = new System.Net.Mail.MailAddress(email);
         UserName.ForeColor = System.Drawing.Color.Black;
         return(addr.Address == email);
     }
     catch
     {
         UserName.Text      = "*invalid username";
         UserName.ForeColor = System.Drawing.Color.Red;
         return(false);
     }
 }
        public void SendEmail()
        {
            SmtpClient  client = default(SmtpClient);
            MailMessage oEmail = new MailMessage();

            System.Net.Mail.MailAddress addressObj = default(System.Net.Mail.MailAddress);
            try
            {
                client = new SmtpClient(m_EmailSMTP, this.m_EmailPort);

                //verify user/password
                if (((m_EmailUser != null)) & ((m_EmailPassword != null)))
                {
                    if (!string.IsNullOrWhiteSpace(m_EmailUser) && !string.IsNullOrWhiteSpace(m_EmailPassword))
                    {
                        client.Credentials = new System.Net.NetworkCredential(m_EmailUser, m_EmailPassword);
                    }
                }

                //set mail attributes
                var _with1 = oEmail;
                _with1.From       = new MailAddress(m_EmailForm, m_EmailFormName);
                _with1.IsBodyHtml = true;
                _with1.Subject    = m_EmailSubject;
                _with1.Body       = m_EmailBody;
                _with1.Priority   = MailPriority.Normal;

                //list email TO list
                if ((m_EmailTo != null))
                {
                    for (int iIndex = 0; iIndex < m_EmailTo.Count; iIndex++)
                    {
                        addressObj = new System.Net.Mail.MailAddress(m_EmailTo[iIndex].ToString());
                        if ((addressObj != null))
                        {
                            _with1.To.Add(addressObj);
                        }
                    }
                }

                //send mail
                client.Send(oEmail);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #35
0
 public static bool IsValidEmailFormat([NotNull] this string str)
 {
     if (string.IsNullOrEmpty(str) || !str.Contains("@"))
     {
         return(false);
     }
     try
     {
         System.Net.Mail.MailAddress addr = new System.Net.Mail.MailAddress(str);
         return(str.Equals(addr.Address));
     }
     catch
     {
         return(false);
     }
 }
Пример #36
0
 // https://stackoverflow.com/a/1374644/1449056
 private static bool IsValidEmail(string email)
 {
     if (string.IsNullOrEmpty(email) || !email.Contains("@"))
     {
         return(false);
     }
     try
     {
         System.Net.Mail.MailAddress addr = new System.Net.Mail.MailAddress(email);
         return(email.Equals(addr.Address));
     }
     catch
     {
         return(false);
     }
 }
Пример #37
0
        public static bool IsMailAddress(string mailAddress)
        {
            bool bln;

            try
            {
                System.Net.Mail.MailAddress mail = new System.Net.Mail.MailAddress(mailAddress);
                bln = false;
            }
            catch
            {
                bln = true;
            }

            return(bln);
        }
Пример #38
0
 bool IsValidEmail(string email)
 {
     try
     {
         var addr = new System.Net.Mail.MailAddress(email);
         if (addr.Address == email)
         {
             return(true);
         }
         return(false);
     }
     catch
     {
         return(false);
     }
 }
Пример #39
0
 private bool IsValidEmail(string EMail)
 {
     //tests to see if an email is in a valid format
     try
     {
         //try to assign the eail to an instance of System.Net.Mail.MailAddress
         System.Net.Mail.MailAddress addr = new System.Net.Mail.MailAddress(EMail);
         //if all ok return true
         return(true);
     }
     catch
     {
         //else return false
         return(false);
     }
 }
Пример #40
0
 private void tbEmail_Leave(object sender, EventArgs e)
 {
     if (tbEmail.Text.Count() > 0)
     {
         try
         {
             var eMailValidator = new System.Net.Mail.MailAddress(tbEmail.Text);
         }
         catch (FormatException ex)
         {
             // wrong e-mail address
             tbEmail.ForeColor = Color.Red;
             validemail        = false;
         }
     }
 }
Пример #41
0
        public static bool IsValidMail(string emailaddress, out string ErrorMessage)
        {
            Boolean _result = true;

            try
            {
                System.Net.Mail.MailAddress m = new System.Net.Mail.MailAddress(emailaddress);
                ErrorMessage = string.Empty;
            }
            catch (FormatException ex)
            {
                ErrorMessage = ex.Message;
                _result      = false;
            }
            return(_result);
        }
Пример #42
0
        /** Insert Fuentes**/
        public static void insertFuente(string fuente, int uidsitio)
        {
            System.Net.Mail.MailAddress address = new System.Net.Mail.MailAddress(fuente);
            string hostmail = address.Host; // Get domain mail

            //Console.WriteLine("only domain: " + hostmail);

            using (var connection = new SqlCommand())
            {
                connection.Connection  = myConnection.GetConnection();
                connection.CommandText = "INSERT INTO [Procesarmails].[dbo].[tbl_mp_fuentes] (uid_sitio, nombre) VALUES( " + uidsitio + ", '" + hostmail + "')";
                connection.ExecuteNonQuery();
                connection.Connection.Close();
                //VerificaFuente(fuente, uidsitio);
            }
        }
Пример #43
0
 public static bool IsValidEmail(string email)
 {
     try
     {
         if (email == "N/A")
         {
             return(true);
         }
         System.Net.Mail.MailAddress addr = new System.Net.Mail.MailAddress(email);
         return(addr.Address == email);
     }
     catch
     {
         return(false);
     }
 }
Пример #44
0
    protected void btnUyeAktifEt_Click(object sender, EventArgs e)
    {
        try
        {
            MembershipUser mu = Membership.GetUser(txtKullaniciAd.Text);
            ProfileCommon  pf = Profile.GetProfile(txtKullaniciAd.Text);

            if (mu != null && pf.uyeINFO.OnayKodu == txtOnayKodu.Text)
            {
                Roles.AddUserToRole(mu.UserName, "User");
                lblOnaySonuc.Text    = "Üyeliğiniz aktifleştirilmiştir...";
                btnGiriseGit.Visible = true;
            }
            else
            {
                lblOnaySonuc.Text = "Onay işlemi gerçekleşmedi..Tekrar deneyiniz veya Admin ile iletişime geçiniz...";
            }
        }
        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      = "UserOnay aspx Hatası";
                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)
            {
            }
        }
    }
Пример #45
0
    private static bool IsValidEmail(string email)
    {
        if (email.StartsWith("mailto:", StringComparison.OrdinalIgnoreCase))
        {
            email = email.Substring(7);
        }

        try
        {
            var address = new System.Net.Mail.MailAddress(email);
            return(address != null);
        }
        catch
        {
            return(false);
        }
    }
Пример #46
0
        public bool sendEmail(EmailSend emlSndngList)
        {
            bool validEmail = IsValidEmail(emlSndngList.ToEmailId);

            if (!string.IsNullOrEmpty(emlSndngList.ToEmailId) && !string.IsNullOrEmpty(emlSndngList.FrmEmailId) && validEmail)
            {
                var         BCC         = ConfigurationManager.AppSettings["PABCC"];
                var         SMTPServer  = ConfigurationManager.AppSettings["SMTPServer"];
                MailMessage mailMessage = new MailMessage(emlSndngList.FrmEmailId, emlSndngList.ToEmailId);
                SmtpClient  client      = new SmtpClient();
                if (!string.IsNullOrEmpty(emlSndngList.Subject))
                {
                    mailMessage.Subject = emlSndngList.Subject;
                }
                if (!string.IsNullOrEmpty(emlSndngList.CC))
                {
                    mailMessage.CC.Add(emlSndngList.CC);
                }
                if (!string.IsNullOrEmpty(BCC))
                {
                    mailMessage.Bcc.Add(BCC);
                }
                mailMessage.Body         = emlSndngList.Body;
                mailMessage.IsBodyHtml   = true;
                mailMessage.BodyEncoding = Encoding.UTF8;
                SmtpClient mailClient = new SmtpClient(SMTPServer, 25);
                //SmtpClient mailClient = new SmtpClient("10.29.15.9", 25);
                //mailClient.EnableSsl = true;
                mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                mailClient.Send(mailMessage);
            }
            return(true);

            bool IsValidEmail(string email)
            {
                try
                {
                    var addr = new System.Net.Mail.MailAddress(email);
                    return(addr.Address == email);
                }
                catch
                {
                    return(false);
                }
            }
        }
Пример #47
0
    public static bool IsValidEmail(string email)
    {
        if (email.Trim() == "")
        {
            return(false);
        }

        try
        {
            var addr = new System.Net.Mail.MailAddress(email);
            return(addr.Address == email);
        }
        catch
        {
            return(false);
        }
    }
Пример #48
0
        private int sendEmail(Security.UserBase toUser, string subject, string message, SiteConfigBase sConfig)
        {
            int successAnswer = 0;
            // Dim smtpC As New Net.Mail.SmtpClient
            // smtpC.Host = server
            // smtpC.Port = 25
            string toaddress = toUser.Email;

            if (SiteConfigBase.VersionClass == SiteConfigBase.verClass.dev)
            {
                toaddress = sConfig.AdministratorEmailAddress;
            }
            System.Net.Mail.MailAddress myToAddress   = new System.Net.Mail.MailAddress(toUser.Email, toUser.OfficialName);
            System.Net.Mail.MailAddress myFromAddress = new System.Net.Mail.MailAddress(sConfig.AdministratorEmailAddress, sConfig.Title + " Administrator");
            System.Net.Mail.MailMessage myMessage     = new System.Net.Mail.MailMessage();
            myMessage.To.Add(myToAddress);
            myMessage.From = myFromAddress;
            // myMessage.IsBodyHtml = True
            myMessage.Subject = subject;
            myMessage.Body    = message + Constants.vbCrLf
                                + Constants.vbCrLf
                                + adminSig(sConfig);

            try {
                if (Security.SiteConfigBase.TestingSite)
                {
                    throw new Exception("The site is being tested.");
                }
                System.Net.NetworkCredential netCredentials = new System.Net.NetworkCredential("", "6Ab=?revap$2QE!"); // eEncryptor.Decrypt(sConfig.EmailServerPassword))

                // smtpC.UseDefaultCredentials = False
                // smtpC.Credentials = CType(netCredentials.GetCredential(sConfig.EmailServerAddress, sConfig.EmailServerSMTPPort, "NTLM"), System.Net.ICredentialsByHost)
                System.Net.Mail.SmtpClient mynewsmtp = new System.Net.Mail.SmtpClient(sConfig.Email_ServerAddress);
                mynewsmtp.UseDefaultCredentials = false;
                mynewsmtp.Port        = 25;
                mynewsmtp.Credentials = new System.Net.NetworkCredential("", "6Ab=?revap$2QE!");
                // mynewsmtp.Credentials = CType(netCredentials.GetCredential(sConfig.EmailServerAddress, sConfig.EmailServerSMTPPort, "Basic"), System.Net.ICredentialsByHost)
                mynewsmtp.Send(myMessage);
                // smtpC.Send(myMessage)

                successAnswer = 1;
            } catch (Exception e) {
                successAnswer = -1;
            }
            return(successAnswer);
        }
Пример #49
0
        public async Task <Models.KickBoxResponse> VerifyEmail(System.Net.Mail.MailAddress mailAddress, int?timeout = null)
        {
            using var httpClient   = new HttpClient();
            using var httpResponse = await httpClient.GetAsync($"{this._apiUrl}/verify?apikey={this._apiKey}&email={mailAddress.Address}&timeout={timeout}")
                                     .ConfigureAwait(true);

            try
            {
                return(JsonConvert.DeserializeObject <Models.KickBoxResponse>(
                           await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(true)));
            }
            catch (Exception e)
            {
                // TODO: Add logging
                throw;
            }
        }
Пример #50
0
    public void sendEmail(String from, String fromPwd, String to, String Subject, String Body)
    {
        String  str   = "";
        Boolean state = false;

        str   = "smtp.mail.yahoo.com";
        state = false;
        System.Net.Mail.MailAddress From    = new System.Net.Mail.MailAddress(from);
        System.Net.Mail.MailAddress To      = new System.Net.Mail.MailAddress(to);
        System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage(From, To);
        Message.Subject = Subject;
        Message.Body    = Body;
        System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(str);
        client.EnableSsl   = Convert.ToBoolean(state);
        client.Credentials = new System.Net.NetworkCredential(from, fromPwd);
        client.Send(Message);
    }
Пример #51
0
    //بدنه ایونت کلیک روی دکه
    #region ClickforContact
    // ایونت کلیک دکمه
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            try
            {
                //بادی را این کدینگ میکنیم
                //Assign Email Template
                string strPathName = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/LocalizedEmailTemplates/Contact.htm");
                string strBody     = Tools.File.Read(strPathName);

                //Replace User's data in Email body
                strBody = strBody
                          .Replace("[NAME]", txtName.Text)
                          .Replace("[MAIL]", txtMail.Text)
                          .Replace("[COMMENT]", txtComment.Text);

                //ایجاد شی از میل آدرس
                System.Net.Mail.MailAddress oMailAddress =
                    new System.Net.Mail.MailAddress(txtMail.Text, txtName.Text, System.Text.Encoding.UTF8);

                //################################
                //کدهای مربوط به ارسال ایمیل
                //################################

                string strInformationMessage =
                    "پیام شما با موفقیت ارسال شد و در صورت نیاز به آن پاسخ خواهیم داد";
                divPageMessage.Visible = true;
                litPageMessage.Text    = strInformationMessage;
            }
            catch (ApplicationException ex0)
            {
                //متغیر ای ایکس را لاگ کنید
                throw (new ApplicationException(Resources.Messages.ErrorMessage020));
            }

            catch (Exception ex)
            {
                //متغیر ای ایکس را لاگ کنید
                string strErrorMessage = string.Format(Resources.Messages.ErrorMessage020);
                DisplayErrorMessage(strErrorMessage);
                return;
            }
        }
    }
Пример #52
0
        private static bool SendMail(GridProteinFoldingEntities ctx, Guid guid, string message, aspnet_Users user)
        {
            //Sent e-mail
            Middle.Helpers.NetworkHelpers.SmtpClient smtpClient = new Middle.Helpers.NetworkHelpers.SmtpClient();
            Process process = ctx.Process.FirstOrDefault(p => p.guid == guid);


            if (!(process.emailNotification == Convert.ToByte(BasicEnums.EmailNotification.Enviar)))
            {
                try
                {
                    System.Net.Mail.MailAddress to = new System.Net.Mail.MailAddress(user.aspnet_Membership.LoweredEmail, user.UserName);
                    string subject = "eFolding - Simulation";
                    string body    = "Simulation " + process.guid.ToString() + message;
                    body += "Direct access: efolding.fcfrp.usp.br/Pages/GCPS.aspx?guid= " + process.guid.ToString();

                    if (smtpClient.Send(to, subject, body))
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                catch (SmtpException ex)
                {
                    new GridProteinFolding.Middle.Helpers.LoggingHelpers.Log().SmtpException(ex, Types.ErrorLevel.Warning);
                    return(false);
                }
                catch (Exception ex)
                {
                    GICO.WriteLine(ex);
                    throw;
                }
                finally
                {
                    smtpClient = null;
                }
            }
            else
            {
                return(true);
            }
        }
Пример #53
0
 /// <summary>
 /// send the mail
 /// </summary>
 /// <param name="maintainEmail"></param>
 private void SendMail(string maintainEmail)
 {
     try
     {
         System.Net.Mail.SmtpClient     client   = new System.Net.Mail.SmtpClient(System.Configuration.ConfigurationManager.AppSettings["mail-server"]);
         System.Net.Mail.MailAddress    fromAddr = new System.Net.Mail.MailAddress(txtEmail.Text);                                                      //new System.Net.Mail.MailAddress(System.Configuration.ConfigurationManager.AppSettings["mail-company"]);
         System.Net.Mail.SmtpPermission sett     = new System.Net.Mail.SmtpPermission(System.Security.Permissions.PermissionState.Unrestricted);
         System.Net.Mail.MailAddress    toAddr   = new System.Net.Mail.MailAddress(System.Configuration.ConfigurationManager.AppSettings["mail-from"]); //new System.Net.Mail.MailAddress(user.Email.ToString());
         System.Net.Mail.MailMessage    message  = new System.Net.Mail.MailMessage(fromAddr, toAddr);
         ////MailAddress copy = new MailAddress(System.Configuration.ConfigurationManager.AppSettings["mail-company"]);
         ////message.CC.Add(copy);
         message.Subject    = subject;
         message.Body       = maintainEmail;
         message.IsBodyHtml = true;
         client.Send(message);
     }
     catch (Exception ex) { throw new Exception("SMTP Server Error: " + ex.Message); }
 }
Пример #54
0
    public bool IsValidEmail(string email)
    {
        string Email = email.Trim();

        if (Email.Length == 0)
        {
            return(false);
        }
        try
        {
            var addr = new System.Net.Mail.MailAddress(Email);
            return(addr.Address == Email);
        }
        catch
        {
            return(false);
        }
    }
Пример #55
0
        public static Task SendAsync(string FromUser, string ToUser, string subject, string body)
        {
            var result    = Task.FromResult(0);
            var toAddress = new System.Net.Mail.MailAddress(ToUser, ToUser);


            try
            {
                System.Net.Mail.MailMessage emessage = new System.Net.Mail.MailMessage();

                string Username   = "******";
                string Password   = "******";
                string port       = "25";
                string SmptServer = "mail.wr-itc.com";


                emessage.To.Add(toAddress);
                emessage.Subject    = subject;
                emessage.From       = new System.Net.Mail.MailAddress(FromUser);
                emessage.Body       = body;
                emessage.IsBodyHtml = true;
                System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();
                var netCredential             = new System.Net.NetworkCredential(Username, Password);
                sc.Host           = SmptServer;
                sc.DeliveryMethod = SmtpDeliveryMethod.Network;

                sc.Credentials = netCredential;
                sc.Port        = Convert.ToInt32(port);

                sc.Send(emessage);



                result = Task.FromResult(1);
            }
            catch (Exception e)
            {
                var x = e;
                result = Task.FromResult(0);
            }


            return(result);
        }
Пример #56
0
        public ActionResult Form(string receiverEmail, string subject, string message)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var senderEmail   = new System.Net.Mail.MailAddress("*****@*****.**", "Demo text");
                    var receiveremail = new System.Net.Mail.MailAddress(receiverEmail, "Receiver");
                    var password      = "******";
                    var sub           = "subject";
                    var body          = message;
                    var smtp          = new SmtpClient
                    {
                        Host                  = "smtp.gmail.com",
                        Port                  = 587,
                        EnableSsl             = true,
                        DeliveryMethod        = SmtpDeliveryMethod.Network,
                        UseDefaultCredentials = false,
                        Credentials           = new NetworkCredential(senderEmail.Address, password)
                    };

                    using (var mess = new MailMessage(senderEmail, receiveremail)
                    {
                        Subject = subject,
                        Body = body
                    }

                           )
                    {
                        smtp.Send(mess);
                    }


                    return(View());
                }
            }

            catch (Exception)
            {
                ViewBag.Error = "there are same problem in sending mail";
            }

            return(View());
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (ClientName.Text == "" || ClientEmail.Text == "" || ClientContactNo.Text == "" || ClientComment.Text == "")
            {
                MailStatus.Text = "Please fill all details.";
                ClientName.Text = ClientEmail.Text = ClientContactNo.Text = ClientComment.Text = "";
            }

            else
            {
                MailAddress add;
                try
                {
                    add = new System.Net.Mail.MailAddress(ClientEmail.Text);
                    try
                    {
                        MailMessage msg = new MailMessage();
                        msg.From = new MailAddress(ClientEmail.Text);
                        msg.To.Add("*****@*****.**");
                        msg.Subject = "Inquiry";
                        msg.Body    = "A Contact Request Form has been sent from .  <br/><br/>" + "Name: " + ClientName.Text + "<br/>Contact No: " + ClientContactNo.Text + "<br />Reply Back Email: " + ClientEmail.Text + "<br/><br />" + ClientComment.Text;

                        msg.IsBodyHtml = true;
                        SmtpClient client = new SmtpClient();
                        client.Host        = "smtp.gmail.com";
                        client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "yamunaart");
                        client.EnableSsl   = true;
                        client.Port        = 587;
                        client.Send(msg);
                        client.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
                        MailStatus.Text       = "Thank You";
                        ClientName.Text       = ClientEmail.Text = ClientComment.Text = ClientContactNo.Text = "";
                    }
                    catch (Exception exx)
                    {
                        MailStatus.Text = "Error Sending Message Please Try Later";
                    }
                }
                catch (Exception ex)
                {
                    MailStatus.Text = "Invalid Email Address";
                }
            }
        }
Пример #58
0
        public Task SendMailToEmployee(string userName, Incident incident, string toUser = null)
        {
            return(Task.Factory.StartNew(() =>
            {
                var fromAddress = new MailAddress("*****@*****.**", userName);
                System.Net.Mail.MailAddress toAddress = null;
                string body = "";
                //send to employee
                if (toUser == null)
                {
                    body = incident.Title;
                    toAddress = new MailAddress("*****@*****.**");
                }
                //send to client
                else
                {
                    toAddress = new MailAddress(toUser);
                    body = "Your incident - " + incident.Title + " was approved. Time for liquidation: " + incident.Estimate + " hours";
                }

                const string fromPassword = "******";
                const string subject = "New incident";



                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 = body
                })
                {
                    smtp.Send(message);
                }
            }));
        }
Пример #59
0
 protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
 {
     try
     {
         var     addr    = new System.Net.Mail.MailAddress(txtEmail.Text);
         Account account = db.Accounts.SingleOrDefault(acc => acc.UserName.Equals(txtEmail.Text));
         if (account != null)
         {
             args.IsValid = true;
         }
         else
         {
             args.IsValid = false;
         }
     }
     catch
     {
     }
 }
Пример #60
0
        /// <summary>
        /// 指定された文字列がメールアドレスとして正しい形式か検証する
        /// </summary>
        /// <param name="address">検証する文字列</param>
        /// <returns>正しい時はTrue。正しくない時はFalse。</returns>
        public static bool IsValidMailAddress(string address)
        {
            if (string.IsNullOrEmpty(address))
            {
                return(false);
            }

            try
            {
                System.Net.Mail.MailAddress a =
                    new System.Net.Mail.MailAddress(address);
            }
            catch (FormatException)
            {
                return(false);
            }

            return(true);
        }