Exemple #1
0
        private void btnSendReminder_Click(object sender, EventArgs e)
        {
            ContactDataSet.PersonDataTable addresses = personTableAdapter.GetEmailAddresses();
            //String[] emails = new string[addresses.Rows.Count];
            string addr = "*****@*****.**";

            for (int i = 0; i < addresses.Rows.Count; i++)
            {
                //emails[i] = addresses[i].Email;
                addr += ", " + addresses[i].Email;
            }

            try
            {
                string body = "You are being cordially invited to The Open Door Church " + lblServiceTitle.Text + " service  which is on " + dtpServiceDate.Value.ToLongDateString() + " starting at 10:00 A.M.";
                MailAddress fr = new MailAddress("*****@*****.**", "Romone Mcfarlane from Open Door Church");

                SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                client.EnableSsl = true;
                client.Timeout = 10000;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Credentials = new NetworkCredential("*****@*****.**", "mcfarlane1");

                MailMessage msg = new MailMessage(fr.ToString(), addr, lblServiceTitle.Text, body);
                client.Send(msg);
                MessageBox.Show("Reminder Sent Successfully.");
            }
            catch (Exception)
            {
                throw;
            }
        }
		public void Build_ReplyToSpecified_AddsReplyToPart()
		{
			var replyTo = new MailAddress("*****@*****.**", "Test Passed");
			var message = BuildMessage(x => { x.ReplyToList.Clear(); x.ReplyToList.Add(replyTo); });
			var result = FormPartsBuilder.Build(message);
			result.AssertContains("h:Reply-To", replyTo.ToString());
		}
 public void Build_FromSpecified_AddsFromPart()
 {
     var from = new MailAddress("*****@*****.**", "Test Passed");
     var message = BuildMessage(x => x.From = from);
     var result = FormPartsBuilder.Build(message);
     result.AssertContains("from", from.ToString());
 }
 public void Build_CCSpecified_AddsCCPart()
 {
     var cc = new MailAddress("*****@*****.**", "Test Passed");
     var message = BuildMessage(x => { x.CC.Clear(); x.CC.Add(cc); });
     var result = FormPartsBuilder.Build(message);
     result.AssertContains("cc", cc.ToString());
 }
Exemple #5
0
        public async Task <ActionResult> ResendEmailConfirmation(ForgotPasswordViewModel model)
        {
            var user = await UserManager.FindByNameAsync(model.Email);

            if (user != null)
            {
                string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                var callbackUrl = Url.Action("ConfirmEmail", "Account", new {
                    userId = user.Id,
                    code   = code
                }, protocol: Request.Url.Scheme);

                try {
                    var from     = new System.Net.Mail.MailAddress(WebConfigurationManager.AppSettings["emailsvcusr"], WebConfigurationManager.AppSettings["emailsvcdisplay"]);
                    var emailMsg = new MailMessage(from.ToString(), user.Email)
                    {
                        Subject = $"Monies: Confirm your account, {user.GetFullName()}!",
                        Body    = "<p>Here is a new copy of a confirmation email for your account.</p>" +
                                  $"<p>Please <a href=\"{callbackUrl}\">click here</a>! After confirming your email, you will be able to login.</p>",
                        IsBodyHtml = true
                    };

                    var emailSvc = new EmailService();
                    await emailSvc.SendAsync(emailMsg);

                    ViewBag.EmailSentTo = user.Email;
                } catch (Exception ex) {
                    //print error to IIS log
                    Debug.WriteLine(ex.ToString());
                }
            }

            return(View("ConfirmationSent"));
        }
		public void Build_ToSpecified_AddsToPart()
		{
			var to = new MailAddress("*****@*****.**", "Test Passed");
			var message = BuildMessage(x => { x.To.Clear(); x.To.Add(to); });
			var result = FormPartsBuilder.Build(message);
			result.AssertContains("to", to.ToString());
		}
        private static void SendEmailTemplate(string EmailAddress, string FirstName, string LastName, string CompanyName, string IntialName,
                                              string UserFirstName, string UserLastName, string TemplateURL, string attachmentFilename,
                                              ref bool IsSend, ref string ErrorCode, ref string ErrorMessage)
        {
            IsSend = false;
            //Attachment attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet);
            try
            {
                var userName     = System.Configuration.ConfigurationManager.AppSettings["GmailUserName"].ToString();
                var userPassword = System.Configuration.ConfigurationManager.AppSettings["GmailPassword"].ToString();

                if (IntialName.Length <= 0)
                {
                    IntialName = "IMENSO";
                }
                var    fromMail = new System.Net.Mail.MailAddress(userName, IntialName);
                var    toMail   = new MailAddress(EmailAddress);
                string subject  = "---Subject----";
                string body     = CreateEmailBody(FirstName, LastName, CompanyName, UserFirstName, UserLastName, TemplateURL);
                using (MailMessage mail = new MailMessage(fromMail, toMail))
                {
                    mail.Subject = subject;
                    mail.Body    = body;
                    string path = HttpContext.Current.Server.MapPath(attachmentFilename);
                    mail.Attachments.Add(new Attachment(path));
                    mail.Priority   = System.Net.Mail.MailPriority.High;
                    mail.IsBodyHtml = true;
                    mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
                    mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                    mail.Headers.Add("Disposition-Notification-To", fromMail.ToString());

                    var smtp = new SmtpClient
                    {
                        Host                  = "smtp.gmail.com",
                        Port                  = 587,
                        EnableSsl             = true,
                        DeliveryMethod        = SmtpDeliveryMethod.Network,
                        UseDefaultCredentials = false,
                        Credentials           = new NetworkCredential(userName, userPassword),
                    };
                    smtp.Send(mail);
                };


                //CreateEmailBody(FirstName, LastName, CompanyName, UserFirstName, UserLastName, TemplateURL);


                IsSend       = true;
                ErrorCode    = "Success";
                ErrorMessage = "Email Sent Successfully.";
            }

            catch (Exception ex)
            {
                IsSend       = false;
                ErrorCode    = "Error";
                ErrorMessage = ex.Message.ToString();
            }
        }
Exemple #8
0
 public User(uint id, string name, MailAddress email, UserType userType)
 {
     ID = id;
     Name = name;
     Email = email;
     StringMailAddress = email.ToString();
     UserType = userType;
 }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName  = model.Email,
                    Email     = model.Email,
                    FirstName = model.FirstName,
                    LastName  = model.LastName
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    //this is commented out to prevent the user from being signed in until email is confirmed.
                    //await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                    //create confirmation code and callback URL to trigger email confirmation.
                    string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                    //begin attempt to send email
                    try {
                        //fetch 'from' from configuration
                        var from     = new System.Net.Mail.MailAddress(WebConfigurationManager.AppSettings["emailsvcusr"], WebConfigurationManager.AppSettings["emailsvcdisplay"]);
                        var emailMsg = new MailMessage(from.ToString(), user.Email)
                        {
                            Subject = $"Simplicita: Confirm your account,{user.FullNameStandard}!",
                            Body    = "<p>Thank you for registering! We're glad to have you.</p>" +
                                      $"<p>To activate your account, please <a href=\"{callbackUrl}\">click here</a>! After confirming your email, you will be able to login.</p>",
                            IsBodyHtml = true
                        };

                        var emailSvc = new EmailService();
                        await emailSvc.SendAsync(emailMsg);

                        //redirect to confirmation sent, since login never occured (notify user of requirement to confirm).
                        ViewBag.EmailSentTo = user.Email;
                        return(View("ConfirmationSent"));
                    } catch (Exception ex) {
                        //delete user since confirmation email failed to send.
                        await UserManager.DeleteAsync(user);

                        //print to IIS log
                        Console.WriteLine(ex.ToString());

                        //add error to model state
                        ModelState.AddModelError("Email Send Failure", "The account was not created. The confirmation email was unable to be sent, but is required for login. This erorr has been reported, please try again later.");
                    }
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public void TestAddress1()
        {
            const string addressString = "*****@*****.**";
            var address = new MailAddress(addressString);

            Assert.AreEqual("eric", address.User, "Username incorrect");
            Assert.AreEqual("ericdomain.com", address.Host, "Domain incorrect");
            Assert.AreEqual(addressString, address.Address, "Address incorrect");
            Assert.AreEqual(addressString, address.ToString(), "ToString incorrect");
        }
Exemple #11
0
        // FIXME: simple implementation, could be brushed up.
        private void SendToFile(MailMessage message)
        {
            if (!Path.IsPathRooted(pickupDirectoryLocation))
            {
                throw new SmtpException("Only absolute directories are allowed for pickup directory.");
            }

            string filename = Path.Combine(pickupDirectoryLocation,
                                           Guid.NewGuid() + ".eml");

            try {
                writer = new StreamWriter(filename);

                MailAddress from = message.From;

                if (from == null)
                {
                    from = defaultFrom;
                }

                SendHeader(HeaderName.Date, DateTime.Now.ToString("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo));
                SendHeader(HeaderName.From, from.ToString());
                SendHeader(HeaderName.To, message.To.ToString());
                if (message.CC.Count > 0)
                {
                    SendHeader(HeaderName.Cc, message.CC.ToString());
                }
                SendHeader(HeaderName.Subject, EncodeSubjectRFC2047(message));

                foreach (string s in message.Headers.AllKeys)
                {
                    SendHeader(s, message.Headers [s]);
                }

                AddPriorityHeader(message);

                boundaryIndex = 0;
                if (message.Attachments.Count > 0)
                {
                    SendWithAttachments(message);
                }
                else
                {
                    SendWithoutAttachments(message, null, false);
                }
            } finally {
                if (writer != null)
                {
                    writer.Close();
                }
                writer = null;
            }
        }
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                if (user == null)
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    ViewBag.EmailSentTo = model.Email;
                    return(View("ForgotPasswordConfirmation"));
                }

                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                try {
                    var from     = new System.Net.Mail.MailAddress(WebConfigurationManager.AppSettings["emailsvcusr"], WebConfigurationManager.AppSettings["emailsvcdisplay"]);
                    var emailMsg = new MailMessage(from.ToString(), user.Email)
                    {
                        Subject    = "Simplicita: Reset Password Confirmation Email",
                        Body       = $"<p>To reset your account, please <a href=\"{callbackUrl}\">click here</a>!</p>",
                        IsBodyHtml = true
                    };

                    var emailSvc = new EmailService();
                    await emailSvc.SendAsync(emailMsg);

                    TempData.Add("EmailSentTo", user.Email);
                    return(RedirectToAction("ForgotPasswordConfirmation", "Account"));
                } catch (Exception ex) {
                    Console.WriteLine(ex.ToString());
                    await Task.FromResult(0);
                }

                return(RedirectToAction("ForgotPasswordConfirmation", "Account"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public void sendEmailToFollowUser(string email,string hash)
        {
            var fromAddress = new MailAddress("*****@*****.**", "Smart Audio City Guide");
            var toAddress = new MailAddress(email);
            string fromPassword = "******";
            string subject = "Your friend want a help";
            string body = "Please click on link to follow your friend: http://smartaudiocityguide.azurewebsites.net/HelpMode/follow?hash=" + hash;

            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(fromAddress.ToString(), toAddress.ToString(), subject, body);

            smtp.Send(message);
        }
        public static void sendMail(string toAddress, string subject, string message)
        {
            MailAddress From = new MailAddress("Dungeon Teller <dungeon-teller@localhost>");
            MailAddress To = new MailAddress(toAddress);

            MailMessage msg = new MailMessage(From, To);
            msg.Subject = subject;
            msg.Body = message;

            try
            {
                string address = To.ToString();
                string domain = address.Substring(address.IndexOf('@') + 1);
                string mxRecord = DnsLookUp.GetMXRecords(domain)[0];
                SmtpClient client = new SmtpClient(mxRecord);
                client.SendAsync(msg, "message1");
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("Failed to send email with the following error:\n'{0}'", ex.Message), "Mail-Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemple #15
0
        public void SendEmail(string message, RegisterViewModel model, string callbackUrl)
        {
            var boddy = new StringBuilder();
                var boddyConf = new StringBuilder();

                boddy.Append(message);
                string confirmMessage = "Hi! " + model.Email + "<br/>"
                      + "Click the link to confirm your account " +
                      callbackUrl;
                boddyConf.Append(confirmMessage);

                string bodyForConf = boddyConf.ToString();

                string bodyFor = boddy.ToString();
                string subjectFor = "Registration";
                string subjectForConf = "Confirm Email";

                string toFor = model.Email;
                var mail = new MailAddress("*****@*****.**", "EGO-Administrators");
                WebMail.SmtpServer = "pod51014.outlook.com";
                WebMail.SmtpPort = 587;
                WebMail.UserName = "******";
                WebMail.Password = "******";
                WebMail.From = mail.ToString();
                WebMail.EnableSsl = true;

                try { WebMail.Send(toFor, subjectFor, bodyFor); }
                catch
                {
                    // ignored
                }
                try { WebMail.Send(toFor, subjectForConf, bodyForConf); }
                catch
                {
                    //null
                }
        }
        public int SendMail(string body,string subject)
        {
            int success = 0;

            try
            {

                MailAddress toAddress = new MailAddress(email, this.email);
                
                SmtpClient smtp = new SmtpClient();
                MailAddress fromAddress = new MailAddress(((NetworkCredential)smtp.Credentials).UserName, "TFN");
                using (MailMessage message = new MailMessage()
                {
                    Subject = subject,
                    Body = body,
                    
                })

                {
                    message.IsBodyHtml = true;
                    message.From = fromAddress;
                    message.To.Add(new MailAddress(toAddress.ToString()));
                    smtp.Send(message);
                    

                    success = 1;
                }

            }
            catch
            {
                Console.WriteLine("error in sending mail");
                success = 0;
            }

            return success;
        }
        private static void SendEmail()
        {
            string txt = s_Error;
            Exception e = s_Exception;
 
            try
            {
                MailAddress from = new MailAddress("----Necesity----", "Exception");
                MailAddress to = new MailAddress("----Necesity----", "Bug Reporter");
                MailMessage mail = new MailMessage(from, to);
                mail.Subject = "Automated Chat Error Report";
                mail.Body = Server.Misc.ServerList.ServerName + " \r \r " + txt + " \r \r " + e.Message + " \r \r " + e.Source + " \r \r " + e.StackTrace;
                SmtpClient client = new SmtpClient("----Necesity----");
                Console.WriteLine("Sending an e-mail message to {0} by using SMTP host {1} port {2}.", to.ToString(), client.Host, client.Port);
                client.Send(mail);
            }
            catch(Exception ex)
            {
                Console.WriteLine("Email failed to send.");
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.Source);
                Console.WriteLine(ex.StackTrace);
            }
        }
        public void sendPasswordToUser(string email, string password)
        {
            var fromAddress = new MailAddress("*****@*****.**", "Smart Audio City Guide");
            var toAddress = new MailAddress(email);
            string fromPassword = "******";
            string subject = "Password for Smart Audio City Guide site";
            string body = "Your new password for Smart Audio City Guide is " + password ;

            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(fromAddress.ToString(), toAddress.ToString(), subject, body);

            smtp.Send(message);
        }
Exemple #19
0
        /// <summary>
        /// Creates a new Notification subscription for the desired user and starts listening. Automatically assigns subscriptions to adequate CAS connections. Uses AutoDiscover to determine User's EWS Url.
        /// </summary>
        /// <param name="userMailAddress">The desired user's mail address. Used for AutoDiscover</param>
        /// <param name="folderIds">The Exchange folders under observation</param>
        /// <param name="eventTypes">Notifications will be received for these eventTypes</param>
        public void AddSubscription(MailAddress userMailAddress, IEnumerable<FolderId> folderIds, IEnumerable<EventType> eventTypes)
        {
            AutodiscoverService autodiscoverService = new AutodiscoverService(this._exchangeVersion);
            autodiscoverService.Credentials = this._credentials;
            autodiscoverService.RedirectionUrlValidationCallback = x => true;
            //only on o365!
            autodiscoverService.EnableScpLookup = false;

            var exchangeService = new ExchangeService(this._exchangeVersion) { Credentials = this._credentials };

            Debug.WriteLine("Autodiscover EWS Url for Subscription User...");
            //exchangeService.AutodiscoverUrl(userMailAddress.ToString(), x => true);

            var response = autodiscoverService.GetUserSettings(userMailAddress.ToString(), UserSettingName.GroupingInformation, UserSettingName.ExternalEwsUrl);
            string extUrl = "";
            string groupInfo = "";
            response.TryGetSettingValue<string>(UserSettingName.ExternalEwsUrl, out extUrl);
            response.TryGetSettingValue<string>(UserSettingName.GroupingInformation, out groupInfo);

            var ewsUrl = new Uri(extUrl);
            exchangeService.Url = ewsUrl;
            var collection = FindOrCreateSubscriptionCollection(exchangeService, new GroupIdentifier(groupInfo, ewsUrl));
            collection.Add(userMailAddress.ToString(), folderIds, eventTypes.ToArray());
            if (_subscriptionCollections.Contains(collection) == false)
                this._subscriptionCollections.Add(collection);
        }
Exemple #20
0
 public void should_serialize_mail_address()
 {
     var email = new MailAddress("*****@*****.**", "Test");
     Bender.Serializer.Create().SerializeXml(new BuiltInWriters { MailAddress = email }).ParseXml()
         .Element("BuiltInWriters").Element("MailAddress").Value.ShouldEqual(email.ToString());
 }
 private void AssignMailAddress(MailAddress mailAddress)
 {
     MailAddress = mailAddress.ToString();
     User = mailAddress.User;
     Host = mailAddress.Host;
 }
        public void TestValidUsername()
        {
            var address = new MailAddress("*****@*****.**");

            Assert.IsTrue("user".Equals(address.User), "Username incorrect");
            Assert.IsTrue("mydomain.com".Equals(address.Host), "Domain incorrect");
            Assert.IsTrue("*****@*****.**".Equals(address.Address), "Address incorrect");
            Assert.IsTrue("*****@*****.**".Equals(address.ToString()), "ToString incorrect");

            address = new MailAddress("my_name@my_domain.com");
            address = new MailAddress("*****@*****.**");
        }
Exemple #23
0
 /// <summary>
 /// Creates a Direct address without associated certificates. (The associated certificates
 /// and trust anchors must be later set from, e.g., an external store or source).
 /// </summary>
 /// <param name="address">The <see cref="MailAddress"/> representation of the address.</param>
 public DirectAddress(MailAddress address)
     : this(address.ToString())
 {
 }
Exemple #24
0
        private void validateInputs(object sender, RoutedEventArgs e)
        {
            string validationErrors = "";

            Uri  uriResult;
            bool urlok = Uri.TryCreate(serverUrlBox.Text, UriKind.Absolute, out uriResult) &&
                         (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);

            if (!urlok)
            {
                validationErrors += "Invalid server url. ";
            }

            MailAddress addr = null;

            try
            {
                addr = new System.Net.Mail.MailAddress(this.emailBox.Text);
            }
            catch
            {
                validationErrors += "Invalid email. ";
            }

            string password = this.passwordBox.Password;

            if (this.passwordBox.Password.Length <= 8)
            {
                validationErrors += "Password too short (<8). ";
            }

            if (this.passwordBox.Password != this.passwordBox_confirm.Password)
            {
                validationErrors += "Passwords do not match. ";
            }

            if (validationErrors != "")
            {
                this.errors.Foreground = new SolidColorBrush(Colors.Red);
                this.errors.Text       = validationErrors;
                validationCheckPass    = false;
            }
            else
            {
                this.errors.Foreground = new SolidColorBrush(Colors.Green);
                this.errors.Text       = "Details seem ok. Go ahead!";
                validationCheckPass    = true;
            }

            if (uriResult != null)
            {
                if (!uriResult.ToString().Contains("api"))
                {
                    uriResult = new Uri(uriResult, "/api");
                }
                this.server = uriResult;
            }


            if (addr != null)
            {
                this.email = addr.ToString();
            }

            if (passwordBox.Password != null)
            {
                this.password = passwordBox.Password;
            }
        }
Exemple #25
0
		public void Constructor1 ()
		{
			address = new MailAddress (" [email protected] ", (string) null);
			Assert.AreEqual ("*****@*****.**", address.Address, "#A1");
			Assert.AreEqual (string.Empty, address.DisplayName, "#A2");
			Assert.AreEqual ("example.com", address.Host, "#A3");
			Assert.AreEqual ("*****@*****.**", address.ToString (), "#A4");
			Assert.AreEqual ("foo", address.User, "#A5");

			address = new MailAddress ("<*****@*****.**> WhatEver", " Mr. Foo Bar ");
			Assert.AreEqual ("*****@*****.**", address.Address, "#B1");
			Assert.AreEqual ("Mr. Foo Bar", address.DisplayName, "#B2");
			Assert.AreEqual ("example.com", address.Host, "#B3");
			Assert.AreEqual ("\"Mr. Foo Bar\" <*****@*****.**>", address.ToString (), "#B4");
			Assert.AreEqual ("foo", address.User, "#B5");

			address = new MailAddress ("Mr. F@@ Bar <*****@*****.**> Whatever", "BarFoo");
			Assert.AreEqual ("*****@*****.**", address.Address, "#C1");
			Assert.AreEqual ("BarFoo", address.DisplayName, "#C2");
			Assert.AreEqual ("example.com", address.Host, "#C3");
			Assert.AreEqual ("\"BarFoo\" <*****@*****.**>", address.ToString (), "#C4");
			Assert.AreEqual ("foo", address.User, "#C5");

			address = new MailAddress ("Mr. F@@ Bar <*****@*****.**> Whatever", string.Empty);
			Assert.AreEqual ("*****@*****.**", address.Address, "#D1");
			Assert.AreEqual (string.Empty, address.DisplayName, "#D2");
			Assert.AreEqual ("example.com", address.Host, "#D3");
			Assert.AreEqual ("*****@*****.**", address.ToString (), "#D4");
			Assert.AreEqual ("foo", address.User, "#D5");

			address = new MailAddress ("Mr. F@@ Bar <*****@*****.**> Whatever", (string) null);
			Assert.AreEqual ("*****@*****.**", address.Address, "#E1");
			Assert.AreEqual ("Mr. F@@ Bar", address.DisplayName, "#E2");
			Assert.AreEqual ("example.com", address.Host, "#E3");
			Assert.AreEqual ("\"Mr. F@@ Bar\" <*****@*****.**>", address.ToString (), "#E4");
			Assert.AreEqual ("foo", address.User, "#E5");

			address = new MailAddress ("Mr. F@@ Bar <*****@*****.**> Whatever", " ");
			Assert.AreEqual ("*****@*****.**", address.Address, "#F1");
			Assert.AreEqual (string.Empty, address.DisplayName, "#F2");
			Assert.AreEqual ("example.com", address.Host, "#F3");
			Assert.AreEqual ("*****@*****.**", address.ToString (), "#F4");
			Assert.AreEqual ("foo", address.User, "#F5");
		}
        public async Task<ActionResult> OwnerRegister(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                string message = _employee.AddEmployees(model);


                int index = message.IndexOf('~') + 1;
                var user = message.Substring(index, 36).Trim();
                string code = await UserManager.GenerateEmailConfirmationTokenAsync(user);

                var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user, code }, Request.Url.Scheme);

                var boddy = new StringBuilder();
                var boddyConf = new StringBuilder();

                boddy.Append(message.Substring(index + 36).Trim());
                string confirmMessage = "Hi! " + model.Email + "<br/>"
                      + "Click the link to confirm your account " +
                      callbackUrl;
                boddyConf.Append(confirmMessage);

                string bodyForConf = boddyConf.ToString();

                string bodyFor = boddy.ToString();
                string subjectFor = "Registration";
                string subjectForConf = "Confirm Email";

                string toFor = message.Substring(0, index - 1).Trim();
                var mail = new MailAddress("*****@*****.**", "SPBFI-Administrators");
                WebMail.SmtpServer = "pod51014.outlook.com";
                WebMail.SmtpPort = 587;
                WebMail.UserName = "******";
                WebMail.Password = "******";
                WebMail.From = mail.ToString();
                WebMail.EnableSsl = true;

                try { WebMail.Send(toFor, subjectFor, bodyFor); }
                catch
                {
                    // ignored
                }
                try { WebMail.Send(toFor, subjectForConf, bodyForConf); }
                catch
                {
                    //null
                }
                return RedirectToAction("OwnerGetAllEmployees");
            }
            return View(model);
        }
Exemple #27
0
 public void should_serialize_mail_address()
 {
     var email = new MailAddress("*****@*****.**", "Test");
     Bender.Serializer.Create().SerializeJson(new BuiltInWriters { MailAddress = email }).ParseJson()
         .JsonRoot().JsonStringField("MailAddress").Value.ShouldEqual(email.ToString());
 }
Exemple #28
0
		public void Constructor0 ()
		{
			address = new MailAddress (" [email protected] ");
			Assert.AreEqual ("*****@*****.**", address.Address, "#A1");
			Assert.AreEqual (string.Empty, address.DisplayName, "#A2");
			Assert.AreEqual ("example.com", address.Host, "#A3");
			Assert.AreEqual ("*****@*****.**", address.ToString (), "#A4");
			Assert.AreEqual ("foo", address.User, "#A5");

			address = new MailAddress ("Mr. Foo Bar <*****@*****.**>");
			Assert.AreEqual ("*****@*****.**", address.Address, "#B1");
			Assert.AreEqual ("Mr. Foo Bar", address.DisplayName, "#B2");
			Assert.AreEqual ("example.com", address.Host, "#B3");
			Assert.AreEqual ("\"Mr. Foo Bar\" <*****@*****.**>", address.ToString (), "#B4");
			Assert.AreEqual ("foo", address.User, "#B5");

			address = new MailAddress ("Mr. F@@ Bar <*****@*****.**> Whatever@You@Want");
			Assert.AreEqual ("*****@*****.**", address.Address, "#C1");
			Assert.AreEqual ("Mr. F@@ Bar", address.DisplayName, "#C2");
			Assert.AreEqual ("example.com", address.Host, "#C3");
			Assert.AreEqual ("\"Mr. F@@ Bar\" <*****@*****.**>", address.ToString (), "#C4");
			Assert.AreEqual ("foo", address.User, "#C5");

			address = new MailAddress ("\"Mr. F@@ Bar\" <*****@*****.**> Whatever@You@Want");
			Assert.AreEqual ("*****@*****.**", address.Address, "#D1");
			Assert.AreEqual ("Mr. F@@ Bar", address.DisplayName, "#D2");
			Assert.AreEqual ("example.com", address.Host, "#D3");
			Assert.AreEqual ("\"Mr. F@@ Bar\" <*****@*****.**>", address.ToString (), "#D4");
			Assert.AreEqual ("foo", address.User, "#D5");

			address = new MailAddress ("FooBar <*****@*****.**>");
			Assert.AreEqual ("*****@*****.**", address.Address, "#E1");
			Assert.AreEqual ("FooBar", address.DisplayName, "#E2");
			Assert.AreEqual ("example.com", address.Host, "#E3");
			Assert.AreEqual ("\"FooBar\" <*****@*****.**>", address.ToString (), "#E4");
			Assert.AreEqual ("foo", address.User, "#E5");

			address = new MailAddress ("\"FooBar\"[email protected]   ");
			Assert.AreEqual ("*****@*****.**", address.Address, "#F1");
			Assert.AreEqual ("FooBar", address.DisplayName, "#F2");
			Assert.AreEqual ("example.com", address.Host, "#F3");
			Assert.AreEqual ("\"FooBar\" <*****@*****.**>", address.ToString (), "#F4");
			Assert.AreEqual ("foo", address.User, "#F5");

			address = new MailAddress ("\"   FooBar   \"< *****@*****.** >");
			Assert.AreEqual ("*****@*****.**", address.Address, "#G1");
			Assert.AreEqual ("FooBar", address.DisplayName, "#G2");
			Assert.AreEqual ("example.com", address.Host, "#G3");
			Assert.AreEqual ("\"FooBar\" <*****@*****.**>", address.ToString (), "#G4");
			Assert.AreEqual ("foo", address.User, "#G5");

			address = new MailAddress ("<*****@*****.**>");
			Assert.AreEqual ("*****@*****.**", address.Address, "#H1");
			Assert.AreEqual (string.Empty, address.DisplayName, "#H2");
			Assert.AreEqual ("example.com", address.Host, "#H3");
			Assert.AreEqual ("*****@*****.**", address.ToString (), "#H4");
			Assert.AreEqual ("foo", address.User, "#H5");

			address = new MailAddress ("    <  *****@*****.**  >");
			Assert.AreEqual ("*****@*****.**", address.Address, "#H1");
			Assert.AreEqual (string.Empty, address.DisplayName, "#H2");
			Assert.AreEqual ("example.com", address.Host, "#H3");
			Assert.AreEqual ("*****@*****.**", address.ToString (), "#H4");
			Assert.AreEqual ("foo", address.User, "#H5");
		}
Exemple #29
0
        public override void ProcessMubbleRequest(System.Web.HttpContext context)
        {
            MailerResponse response = new MailerResponse();

            response.Type = MailerResponseType.InvalidFromAddress;
            response.Message = "This feature is currently disabled.";
            this.sendResponse(response, context);
            return;

            IRssItem item = Controller.GetCurrentRssItem(this.Url.Path, this.Url.PathExtra, Security.User.GetRoles());

            if (item == null)
            {
                response.Type = MailerResponseType.NoContentItem;
                response.Message = "There is no content available at that URL.";

                this.sendResponse(response, context);
                return;
            }

            string toAddresses = context.Request.Form["RecipientEmail"];
            string[] to = new string[0];
            if (toAddresses != null)
            {
                to = toAddresses.Split(new char[] { ',', ' ', ';' });
            }

            if (to.Length > 5)
            {
                response.Type = MailerResponseType.TooManyRecipients;
                response.Message = "Only 5 recipients allowed.";
                this.sendResponse(response, context);
                return;
            }

            MailAddress fromAddress = null;
            try
            {
                fromAddress = new MailAddress(context.Request.Form["SenderEmail"], context.Request.Form["SenderName"]);
            }
            catch (Exception e)
            {
                response.Type = MailerResponseType.InvalidFromAddress;
                response.Message = "The from address is not valid.";
                this.sendResponse(response, context);
                return;
            }

            string subject = string.Format(
                "{0} wants you to read \"{1}\"",
                fromAddress.ToString(),
                item.Title
                );
            string message = string.Format(
                "{0}\r\n\r\n--------------\r\n\r\n{1}\r\n\r\n--------------\r\n\r\n{2}",
                context.Request.Form["Message"],
                MubbleUrl.Url(item.Url, "HtmlHandler"),
                item.Excerpt
                );

            foreach (string address in to)
            {
                MailAddress toAddress = null;
                try
                {
                    toAddress = new MailAddress(address);
                }
                catch (Exception e)
                {
                    response.Type = MailerResponseType.InvalidRecipientAddress;
                    response.Message = string.Format("\"{0}\" is not a valid email address", address);
                }
                SentEmail sent = new SentEmail();
                sent.SenderEmail = fromAddress.Address;
                sent.SenderIP = context.Request.UserHostAddress;
                sent.SenderName = fromAddress.DisplayName;
                sent.RecipientEmail = address;
                sent.SentAt = DateTime.Now;
                sent.IsSpam = false;

                if (sent.IsSpammer)
                {
                    response.Type = MailerResponseType.Spam;
                    response.Message = "The system thinks this is spam.";
                    this.sendResponse(response, context);
                    return;
                }

                sent.Save();

                MailMessage msg = new MailMessage(fromAddress, toAddress);
                msg.Subject = subject;
                msg.Body = message;
                msg.IsBodyHtml = false;

                SmtpClient mailer = new SmtpClient();
                mailer.Send(msg);
            }

            response.Type = MailerResponseType.Success;
            this.sendResponse(response, context);
        }
Exemple #30
0
        public static bool TrySendAccountEmailMessageUriAsAdmin(
            ISession session,
            ManagedAccount recepient,
            string relativeuri)
        {
            try
            {
                string sendto = string.Empty;

                if (!recepient.TryGetActiveEmailAddress(out sendto, ManagedAccount.GetAdminSecurityContext(session)))
                    return false;

                MailAddress address = new MailAddress(sendto, recepient.Name);

                return TrySendAccountEmailMessageUriAsAdmin(
                    session, address.ToString(), relativeuri);
            }
            catch
            {
                return false;
            }
        }
Exemple #31
0
        /// <summary>
        /// Takes a message and constructs an MDN for it.
        /// </summary>
        /// <param name="message">The message to send notification about.</param>
        /// <param name="from">MailAddress this notification is from</param>
        /// <param name="notification">The notification to create.</param>
        /// <returns>The MDN.</returns>
        public static NotificationMessage CreateNotificationFor(Message message, MailAddress from, Notification notification)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            if (from == null)
            {
                throw new ArgumentNullException("from");
            }
            if (notification == null)
            {
                throw new ArgumentNullException("notification");
            }
            //
            // Verify that the message is not itself an MDN!
            //
            if (message.IsMDN())
            {
                throw new ArgumentException("Message is an MDN");
            }
            
            string notifyTo = message.GetNotificationDestination();
            if (string.IsNullOrEmpty(notifyTo))
            {
                throw new ArgumentException("Invalid Disposition-Notification-To Header");
            }
            
            string originalMessageID = message.IDValue;
            if (!string.IsNullOrEmpty(originalMessageID))
            {
                notification.OriginalMessageID = originalMessageID;
            }
            
            if (!notification.HasFinalRecipient)
            {
                notification.FinalRecipient = from;
            }
                       
            NotificationMessage notificationMessage = new NotificationMessage(notifyTo, from.ToString(), notification);
            notificationMessage.AssignMessageID();

            string originalSubject = message.SubjectValue;
            if (!string.IsNullOrEmpty(originalSubject))
            {
                notificationMessage.SubjectValue = string.Format("{0}:{1}", notification.Disposition.Notification.AsString(), originalSubject);
            }

            notificationMessage.Timestamp();
            
            return notificationMessage;
        }       
Exemple #32
0
        private void SendCore(MailMessage message)
        {
            SmtpResponse status;

            CheckCancellation();

            client = new TcpClient(host, port);
            stream = client.GetStream();
            // FIXME: this StreamWriter creation is bogus.
            // It expects as if a Stream were able to switch to SSL
            // mode (such behavior is only in Mainsoft Socket API).
            writer = new StreamWriter(stream);
            reader = new StreamReader(stream);

            status = Read();
            if (IsError(status))
            {
                throw new SmtpException(status.StatusCode, status.Description);
            }

            // EHLO

            // FIXME: parse the list of extensions so we don't bother wasting
            // our time trying commands if they aren't supported.
            status = SendCommand("EHLO " + Dns.GetHostName());

            if (IsError(status))
            {
                status = SendCommand("HELO " + Dns.GetHostName());

                if (IsError(status))
                {
                    throw new SmtpException(status.StatusCode, status.Description);
                }
            }
            else
            {
                // Parse ESMTP extensions
                string extens = status.Description;

                if (extens != null)
                {
                    ParseExtensions(extens);
                }
            }

            if (enableSsl)
            {
#if old_comment
                // FIXME: I get the feeling from the docs that EnableSsl is meant
                // for using the SSL-port and not STARTTLS (or, if it includes
                // STARTTLS... only use STARTTLS if the SSL-type in the certificate
                // is TLS and not SSLv2 or SSLv3)

                // FIXME: even tho we have a canStartTLS flag... ignore it for now
                // so that the STARTTLS command can throw the appropriate
                // SmtpException if STARTTLS is unavailable
#else
                // SmtpClient implements STARTTLS support.
#endif
                InitiateSecureConnection();

                // FIXME: re-EHLO?
            }

            if (authMechs != AuthMechs.None)
            {
                Authenticate();
            }

            MailAddress from = message.From;

            if (from == null)
            {
                from = defaultFrom;
            }

            // MAIL FROM:
            status = SendCommand("MAIL FROM:<" + from.Address + '>');
            if (IsError(status))
            {
                throw new SmtpException(status.StatusCode, status.Description);
            }

            // Send RCPT TO: for all recipients
            List <SmtpFailedRecipientException> sfre = new List <SmtpFailedRecipientException> ();

            for (int i = 0; i < message.To.Count; i++)
            {
                status = SendCommand("RCPT TO:<" + message.To [i].Address + '>');
                if (IsError(status))
                {
                    sfre.Add(new SmtpFailedRecipientException(status.StatusCode, message.To [i].Address));
                }
            }
            for (int i = 0; i < message.CC.Count; i++)
            {
                status = SendCommand("RCPT TO:<" + message.CC [i].Address + '>');
                if (IsError(status))
                {
                    sfre.Add(new SmtpFailedRecipientException(status.StatusCode, message.CC [i].Address));
                }
            }
            for (int i = 0; i < message.Bcc.Count; i++)
            {
                status = SendCommand("RCPT TO:<" + message.Bcc [i].Address + '>');
                if (IsError(status))
                {
                    sfre.Add(new SmtpFailedRecipientException(status.StatusCode, message.Bcc [i].Address));
                }
            }

#if TARGET_JVM // List<T>.ToArray () is not supported
            if (sfre.Count > 0)
            {
                SmtpFailedRecipientException[] xs = new SmtpFailedRecipientException[sfre.Count];
                sfre.CopyTo(xs);
                throw new SmtpFailedRecipientsException("failed recipients", xs);
            }
#else
            if (sfre.Count > 0)
            {
                throw new SmtpFailedRecipientsException("failed recipients", sfre.ToArray());
            }
#endif

            // DATA
            status = SendCommand("DATA");
            if (IsError(status))
            {
                throw new SmtpException(status.StatusCode, status.Description);
            }

            // Send message headers
            SendHeader(HeaderName.Date, DateTime.Now.ToString("ddd, dd MMM yyyy HH':'mm':'ss zzz", DateTimeFormatInfo.InvariantInfo));
            SendHeader(HeaderName.From, from.ToString());
            SendHeader(HeaderName.To, message.To.ToString());
            if (message.CC.Count > 0)
            {
                SendHeader(HeaderName.Cc, message.CC.ToString());
            }
            SendHeader(HeaderName.Subject, EncodeSubjectRFC2047(message));

            foreach (string s in message.Headers.AllKeys)
            {
                SendHeader(s, message.Headers [s]);
            }

            AddPriorityHeader(message);

            boundaryIndex = 0;
            if (message.Attachments.Count > 0)
            {
                SendWithAttachments(message);
            }
            else
            {
                SendWithoutAttachments(message, null, false);
            }

            SendData(".");

            status = Read();
            if (IsError(status))
            {
                throw new SmtpException(status.StatusCode, status.Description);
            }

            try {
                status = SendCommand("QUIT");
            } catch (System.IO.IOException) {
                // We excuse server for the rude connection closing as a response to QUIT
            }

            writer.Close();
            reader.Close();
            stream.Close();
            client.Close();
        }
Exemple #33
0
        /// <summary>
        /// Takes a message and constructs an DSN for it.
        /// </summary>
        /// <param name="message">The message to send notification about.</param>
        /// <param name="from">MailAddress this notification is from</param>
        /// <param name="dsn">The dsn to create.</param>
        /// <returns>The DSN.</returns>
        public static DSNMessage CreateNotificationFor(Message message, MailAddress from, DSN dsn)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            if (from == null)
            {
                throw new ArgumentNullException("from");
            }
            if (dsn == null)
            {
                throw new ArgumentNullException("dsn");
            }
            //
            // Verify that the message is not itself an MDN!
            //
            if (message.IsMDN())
            {
                throw new ArgumentException("Message is an MDN");
            }

            string notifyTo = message.From.Value;

            DSNMessage statusMessage = new DSNMessage(notifyTo, from.ToString(), dsn);
            statusMessage.AssignMessageID();

            statusMessage.SubjectValue = string.Format("{0}:{1}", "Rejected", message.SubjectValue);
            
            statusMessage.Timestamp();

            return statusMessage;
        }
Exemple #34
0
 public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
 {
     System.Net.Mail.MailAddress _mail = (MailAddress)value;
     writer.WriteValue(_mail.ToString());
 }
Exemple #35
0
		private static string EncodeAddress(MailAddress address)
		{
			if (!String.IsNullOrEmpty (address.DisplayName)) {
				string encodedDisplayName = ContentType.EncodeSubjectRFC2047 (address.DisplayName, Encoding.UTF8);
				return "\"" + encodedDisplayName + "\" <" + address.Address + ">";
			}
			return address.ToString ();
		}
        public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);
                if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return View("ForgotPasswordConfirmation");
                }

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code }, Request.Url.Scheme);
                //await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");


                //code herere today
                var boddy = new StringBuilder();

                boddy.Append("Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");

                string bodyFor = boddy.ToString();
                string subjectFor = "Forgot Password";


                string toFor = model.Email;

                var mail = new MailAddress("*****@*****.**", "SPBFI-Administrators");
                WebMail.SmtpServer = "pod51014.outlook.com";
                WebMail.SmtpPort = 587;
                WebMail.UserName = "******";
                WebMail.Password = "******";
                WebMail.From = mail.ToString();
                WebMail.EnableSsl = true;

                try { WebMail.Send(toFor, subjectFor, bodyFor); }
                catch
                {
                    // ignored
                }
                return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }