Example #1
0
        public static void Send(SendEmailModel email)
        {
            try
            {
                MailMessage message    = new MailMessage();
                SmtpClient  smtpclient = new SmtpClient();
                message.From = new MailAddress(email.From);
                foreach (var to in email.To.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    message.To.Add(new MailAddress(to));
                }

                message.Subject                  = email.Subject;
                message.IsBodyHtml               = email.IsHtml; //to make message body as html
                message.Body                     = email.EmailBody;
                smtpclient.Port                  = Convert.ToInt32(port);
                smtpclient.Host                  = smtp; //for gmail host
                smtpclient.EnableSsl             = true;
                smtpclient.UseDefaultCredentials = true;
                smtpclient.Credentials           = new NetworkCredential(username, password);
                smtpclient.DeliveryMethod        = SmtpDeliveryMethod.Network;
                smtpclient.Send(message);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #2
0
        private static void SendEmailToTeamWhenFailToSendEmailOnOrder(object sender, AsyncCompletedEventArgs e)
        {
            var emailModel = new DPO.Common.SendEmailModel();

            SendEmailModel sendEmailModel = emailModel;

            List <string> fromEmails = Utilities.Config("dpo.sys.email.orderSendEmailError").Split(',').ToList();

            emailModel.Subject = string.Format("send email Order Submit error");

            emailModel.From = new MailAddress(fromEmails.First(), "Send Email Error");

            foreach (string email in fromEmails)
            {
                emailModel.To.Add(new MailAddress(email, "Daikin Project Desk"));
            }

            string emailMessage = string.Format(@"An error occured when try to send email for Order Submit.Below are the Order Details: <br />" +
                                                "The below are the error details: <br /> {0}",
                                                (e.Error.InnerException != null) ? e.Error.InnerException.Message : e.Error.Message);

            sendEmailModel.Subject           = "Order Submit Email Failure Notification.";
            sendEmailModel.RenderTextVersion = true;
            sendEmailModel.BodyTextVersion   = emailMessage;

            new EmailServices().SendEmail(sendEmailModel);
        }
Example #3
0
        public string SendAdhokEmail(SendEmailModel mail)
        {
            var result = new DataServiceResult();

            try
            {
                EmailHelper.Send(mail);
                var data = new SendSmsOrEmail();
                data.MessageContent = mail.EmailBody;
                data.MessageDate    = DateTime.Now.Date;
                data.MessgeType     = mail.MessageType;
                data.To             = mail.To;
                data.Subject        = mail.Subject;
                data.From           = mail.From;
                data.MessageReciver = mail.Reciver;
                emailrepo.SaveEmailSMSEntry(data);
                result.Success       = true;
                result.ResultMessage = "Mail send successfully";
            }
            catch (Exception ex)
            {
                result.Success       = false;
                result.ResultMessage = "Mail sending failed";
                result.ExceptionInfo = new ExceptionInfo(ex);
            }
            return(JsonConvert.SerializeObject(result));
        }
Example #4
0
        public async Task SendEmailAsync(SendEmailModel model)
        {
            var emailMessage = new MimeMessage {
                From =
                {
                    new MailboxAddress(_options.Value.Name, _options.Value.SenderEmail)
                },
                To =
                {
                    new MailboxAddress(_options.Value.Name, model.Recipient)
                },
                Subject = model.Subject,
                Body    = new TextPart("html")
                {
                    Text = model.Body
                }
            };

            using (var client = new SmtpClient()) {
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                await client.ConnectAsync(_options.Value.Smtp, _options.Value.Port, false).ConfigureAwait(false);

                client.AuthenticationMechanisms.Remove("XOAUTH2");
                client.Authenticate(_options.Value.SmtpUsername, _options.Value.SmtpPassword);

                await client.SendAsync(emailMessage).ConfigureAwait(false);

                await client.DisconnectAsync(true).ConfigureAwait(false);
            }
        }
Example #5
0
        public void SendEmail(SendEmailModel model)
        {
            AsyncMethodCaller caller          = new AsyncMethodCaller(SendMailInSeperateThread);
            AsyncCallback     callbackHandler = new AsyncCallback(AsyncCallback);

            caller.BeginInvoke(model, callbackHandler, null);
        }
Example #6
0
        public static async Task <ExecutionResponse <bool> > SendEmail(SendEmailModel model)
        {
            ExecutionResponse <bool> response = new ExecutionResponse <bool>();

            try
            {
                var from             = new EmailAddress(model.SenderEmail, "");
                var to               = new EmailAddress(model.DeptEmail, "");
                var plainTextContent = model.Message;
                var htmlContent      = model.htmlContent;
                var subject          = model.Subject;

                var email             = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
                var sendEmailAsyncRes = await sendGridClient.SendEmailAsync(email);

                if (sendEmailAsyncRes.StatusCode != HttpStatusCode.Accepted)
                {
                    MessagesHelper.SetValidationMessages(response, "Email_Error", sendEmailAsyncRes.Body.ToString(), lang: "en");
                    return(response);
                }
                response.State  = ResponseState.Success;
                response.Result = true;
            }
            catch (Exception ex)
            {
                MessagesHelper.SetException(response, ex);
            }
            return(response);
        }
Example #7
0
        public ServiceResponse GetUserEmailModel(UserSessionModel user, UserModel model)
        {
            this.Response = new ServiceResponse();

            var emailModel = new SendEmailModel();

            // Send to group owners if account registered.
            if (model.UserId.HasValue)
            {
                var users = (from u in this.Db.QueryUserViewableByUserId(user, model.UserId.Value)
                             select new UserListModel
                {
                    UserId = u.UserId,
                    Email = u.Email,
                    FirstName = u.FirstName,
                    MiddleName = u.MiddleName,
                    LastName = u.LastName
                }).ToList();

                users.ForEach(e => emailModel.To.Add(new MailAddress(e.Email, e.DisplayName)));
            }

            emailModel.From = new MailAddress(Utilities.Config("dpo.sys.email.from"), "Daikin Office Project");


            this.Response.Model = emailModel;

            return(this.Response);
        }
        public async Task <IActionResult> SendActiveEmailCode(EmailValidCodeModel model)
        {
            if (TempData[ConstList.VALIDCODE] == null)
            {
                return(Json(new AjaxResult {
                    Status = "error", ErrorMsg = "验证码过期"
                }));
            }
            string code = (string)TempData[ConstList.VALIDCODE];

            TempData[ConstList.VALIDCODE] = null;
            if (!code.Equals(model.ValidCode, StringComparison.InvariantCultureIgnoreCase))
            {
                return(Json(new AjaxResult {
                    Status = "error", ErrorMsg = "验证码错误"
                }));
            }
            SendEmailModel send = new SendEmailModel();

            send.RecipientEmail = model.RecipientEmail;
            send.SendType       = SendType.ActiveEmail;
            string emailCode = await SendEmailSvc.SendRegisterEmailAsync(send);

            if (string.IsNullOrEmpty(emailCode))
            {
                return(Json(new AjaxResult {
                    Status = "error", ErrorMsg = SendEmailSvc.ErrorMsg
                }));
            }
            TempData[ConstList.EMAILVALIDCODE]           = emailCode;
            TempData[ConstList.REGISTERORFOUNDPASSEMAIL] = model.RecipientEmail;
            return(Json(new AjaxResult {
                Status = "ok"
            }));
        }
        public ActionResult Send_Email(SendEmailModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    String toEmail  = "*****@*****.**";
                    String subject  = model.Subject;
                    String contents = model.Contents;

                    EmailSender es = new EmailSender();
                    es.Send(toEmail, subject, contents);

                    ViewBag.Result = "Email has been send.";

                    ModelState.Clear();

                    return(View(new SendEmailModel()));
                }
                catch
                {
                    return(View());
                }
            }

            return(View());
        }
Example #10
0
        public async Task <IActionResult> RetrievePasswordAsync(string email)
        {
            Regex regex = new Regex(@"[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?");

            if (!regex.IsMatch(email))
            {
                return(Ok(new { code = 1, msg = "请输入正确的邮箱!" }));
            }

            SendEmailModel sendEmailModel = new SendEmailModel
            {
                Title        = "重置密码",
                EmailAddress = email,
                Content      = "缺缺提醒您:请联系管理员,QQ:3393597524!",
                Key          = "******",
                Addresser    = "缺缺",
                Recipients   = ""
            };
            var response = await _httpClient.PostAsJsonAsync("/api/service/smtp", new List <SendEmailModel>() { sendEmailModel });

            if (response.IsSuccessStatusCode)
            {
                return(Ok("发送成功!"));
            }
            else
            {
                return(Ok("服务器错误,请联系管理员!"));
            }
        }
Example #11
0
        public CustomerModel()
        {
            AvailableTimeZones = new List <SelectListItem>();
            SendEmail          = new SendEmailModel()
            {
                SendImmediately = true
            };
            SendPm = new SendPmModel();

            SelectedCustomerRoleIds = new List <int>();
            AvailableCustomerRoles  = new List <SelectListItem>();

            AvailableCountries = new List <SelectListItem>();
            AvailableStates    = new List <SelectListItem>();
            AvailableVendors   = new List <SelectListItem>();
            CustomerAttributes = new List <CustomerAttributeModel>();
            AvailableNewsletterSubscriptionStores  = new List <SelectListItem>();
            SelectedNewsletterSubscriptionStoreIds = new List <int>();
            AddRewardPoints = new AddRewardPointsToCustomerModel();
            CustomerRewardPointsSearchModel                  = new CustomerRewardPointsSearchModel();
            CustomerAddressSearchModel                       = new CustomerAddressSearchModel();
            CustomerOrderSearchModel                         = new CustomerOrderSearchModel();
            CustomerShoppingCartSearchModel                  = new CustomerShoppingCartSearchModel();
            CustomerActivityLogSearchModel                   = new CustomerActivityLogSearchModel();
            CustomerBackInStockSubscriptionSearchModel       = new CustomerBackInStockSubscriptionSearchModel();
            CustomerAssociatedExternalAuthRecordsSearchModel = new CustomerAssociatedExternalAuthRecordsSearchModel();
            CustomerVendorsModel = new List <CustomerVendorModel>();
        }
Example #12
0
        public async Task <IHttpActionResult> Invite(InviteUserModel model)
        {
            try
            {
                if (string.IsNullOrEmpty(model.Email))
                {
                    return(BadRequest(ResponseMessages.InviteUserEmailRequired.ToDesc()));
                }

                if (await _userRepository.IsUserActive(model.Email))
                {
                    return(BadRequest(ResponseMessages.EmailDuplicate.ToDesc()));
                }

                if (!await _userRepository.IsEmailExists(model.Email))
                {
                    await _userRepository.AddAsync(new User
                    {
                        IsActive = false,
                        Email    = model.Email
                    });
                }

                var user = await _userRepository.GetUserAsync(model.Email);

                if (user == null)
                {
                    return(BadRequest(ResponseMessages.UserNotFound.ToDesc()));
                }

                await _logRepository.UpdateAccess(new LogAccessModel
                {
                    LogId    = model.LogId,
                    UserId   = user._id.ToString(),
                    CanRead  = model.CanRead,
                    CanWrite = model.CanWrite
                });

                var body = _emailTemplateRenderer.Render(EmailTemplateName.InviteUser, new
                {
                    ClientDomain = ConfigurationManager.AppSettings["ClientDomain"],
                });

                var sendEmailModel = new SendEmailModel
                {
                    Body    = body,
                    Subject = "You has been invited to monitorr.io",
                    Emails  = { model.Email }
                };

                await _emailSender.SendAsync(sendEmailModel);

                return(Ok(ResponseMessages.Ok.ToDesc()));
            }
            catch (Exception ex)
            {
                LogVerbose(ex);
            }
            return(InternalServerError());
        }
Example #13
0
        public ActionResult EmailView(SendEmailModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var    toEmail  = model.SelectedEmailAddresses.ToList();
                    String subject  = model.Subject;
                    String contents = model.Contents;

                    EmailSender es = new EmailSender();
                    es.Send(toEmail, subject, contents, model.Upload);

                    ViewBag.Result = "Email has been sent.";

                    ModelState.Clear();
                    model.Contents            = "";
                    model.Subject             = "";
                    ViewBag.AllEmailAddresses = GetEmails();
                    return(View(model));
                }
                catch
                {
                    ViewBag.AllEmailAddresses = GetEmails();
                    return(View());
                }
            }
            ViewBag.AllEmailAddresses = GetEmails();
            return(View());
        }
        public bool Invite(string sub, [FromUri] List <string> membersInvite, string director, DateTime date)
        {
            string         body = "you are invited for meeting by " + director + " on " + date + " about " + sub;
            SendEmailModel sem  = new SendEmailModel(null, sub, body, membersInvite);

            return(_GeneralBL.CreateMail(sem));
        }
        public ActionResult Admin_Send_Email(SendEmailModel model)
        {
            //  model.ToEmail = "*****@*****.**";
            // if (ModelState.IsValid)
            //{
            try
            {
                String toEmail   = model.ToEmail;
                String subject   = model.Subject;
                String message   = model.Message;
                string totalPath = null;
                string filePath  = null;

                //StringBuilder sbMessage = new StringBuilder();
                //sbMessage.Append(HttpUtility.HtmlEncode(message));
                //sbMessage.Replace("&lt;b&gt;","<b>");
                //sbMessage.Replace("&lt;u&gt;", "<u>");
                //sbMessage.Replace("&lt;/b&gt;", "</b>");
                //sbMessage.Replace("&lt;/u&gt;", "</u>");
                //sbMessage.Replace("&lt;i&gt;", "<i>");
                //sbMessage.Replace("&lt;/i&gt;", "</i>");
                //message = sbMessage.ToString();



                foreach (string fileName in Request.Files)
                {
                    HttpPostedFileBase uploadFile = Request.Files[fileName];
                    if (uploadFile != null && uploadFile.ContentLength > 0)
                    {
                        var    myUniqueFileName = string.Format(@"{0}", Guid.NewGuid());
                        string imagePath        = myUniqueFileName;

                        string serverPath    = Server.MapPath("~/Uploads/");
                        string fileExtention = Path.GetExtension(uploadFile.FileName);
                        filePath  = imagePath + fileExtention;
                        imagePath = filePath;

                        uploadFile.SaveAs(serverPath + imagePath);

                        totalPath = serverPath + "\\" + imagePath;
                    }
                }

                EmailSender sender = new EmailSender();
                int         count  = sender.Send(toEmail, subject, message, filePath, totalPath);
                ViewBag.Result = "Email has been send to " + count + " reciepients";

                ModelState.Clear();

                return(View(new SendEmailModel()));
            }
            catch
            {
                return(View());
            }
            // }
            // return View();
        }
Example #16
0
        public EmailResult SendEmail(SendEmailModel model)
        {
            To.Add(SendEmailModel.To);
            From    = model.Email;
            Subject = SendEmailModel.Subject + " from " + model.FullName;

            return(Email("SendEmail", model));
        }
Example #17
0
 public CustomerModel()
 {
     AvailableTimeZones = new List<SelectListItem>();
     SendEmail = new SendEmailModel();
     SendPm = new SendPmModel();
     AssociatedExternalAuthRecords = new List<AssociatedExternalAuthModel>();
     AvailableCountries = new List<SelectListItem>();
     AvailableStates = new List<SelectListItem>();
 }
Example #18
0
 public CustomerModel()
 {
     AvailableTimeZones            = new List <SelectListItem>();
     SendEmail                     = new SendEmailModel();
     SendPm                        = new SendPmModel();
     AssociatedExternalAuthRecords = new List <AssociatedExternalAuthModel>();
     AvailableCountries            = new List <SelectListItem>();
     AvailableStates               = new List <SelectListItem>();
 }
Example #19
0
        public UserModel()
        {
            SendEmail = new SendEmailModel()
            {
                SendImmediately = true
            };

            AvailableUserRoles = new List <SelectListItem>();
        }
 public bool SendEmail()
  {
      SendEmailModel model = new SendEmailModel()
      {
          Body="checking",
          Subject="checking",                
      };
    return _GeneralBL.CreateMail(model);
  }
        public IActionResult ContactWithUs(SendEmailModel sendEmailModel)
        {
            sendEmailModel.Body = $"Email from: {sendEmailModel.SentFrom}.\n" + sendEmailModel.Body;
            var mailMessage = MailMessageMapper("*****@*****.**", sendEmailModel.Subject, sendEmailModel.Body);
            var smtpClient  = SmtpClientMapper();

            smtpClient.Send(mailMessage);
            return(RedirectToAction(nameof(Index)));
        }
Example #22
0
        public void Handle(LoanHasBeenPaidOffEvent @event)
        {
            // Some logic (maybe business as well) related with actions when customer has taken loan

            var mailBody = $"Hi, {@event.CustomerFirstName}\n\n" +
                           $"Your loan for {@event.LoanAmount} {@event.LoanCurrency} has been paid off.";
            var sendEmailModel = new SendEmailModel(@event.CustomerMailAddress, MailSubject, mailBody);

            _emailSender.SendMail(sendEmailModel);
        }
Example #23
0
        public ActionResult SendEmail(SendEmailModel model)
        {
            if (!ModelState.IsValid)
            {
                ViewBag.DesktopInstructions = MvcHelper.CreateFakeInstructions(9);
                ViewBag.MobileInstructions  = MvcHelper.CreateFakeInstructions(3);
                return(View(model));
            }

            return(RedirectToAction("Index"));
        }
Example #24
0
        public Task SendEmailConfirmationAsync(EmailConfirmationModel emailConfirmationModel)
        {
            var sendEmailModel = new SendEmailModel
            {
                Email   = emailConfirmationModel.Email,
                Subject = "Confirm your email",
                Message = $"Please confirm your account by clicking this link: <a href='{HtmlEncoder.Default.Encode(emailConfirmationModel.Link)}'>link</a>"
            };

            return(SendEmailAsync(sendEmailModel));
        }
Example #25
0
        public Task SendEmailResetPasswordAsync(EmailResetPasswordModel emailResetPasswordModel)
        {
            var sendEmailModel = new SendEmailModel
            {
                Email   = emailResetPasswordModel.Email,
                Subject = "Reset Password",
                Message = $"Please reset your password by clicking here: <a href='{emailResetPasswordModel.Link}'>link</a>"
            };

            return(SendEmailAsync(sendEmailModel));
        }
        public async Task <IActionResult> SendEmail([FromBody] SendEmailModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            await _emailSender.SendMailAsync(model.Recipient, model.Subject, model.Message);

            return(Ok());
        }
Example #27
0
        public ActionResult SendEmail(SendEmailModel model)
        {
            ReturnToClient returnToClient = new ReturnToClient();
            string         strEndToAddr   = string.Empty;

            try
            {
                if (model.SenderAddr.IsNullOrEmpty() || model.SenderDisplayName.IsNullOrEmpty() ||
                    model.ToAddr.IsNullOrEmpty() || model.Subuject.IsNullOrEmpty())
                {
                    throw new Exception("数据参数错误,确保发件人信息,主题,收件人邮箱 信息完整");
                }

                //根据发件人和发件人邮箱获取 密码和host
                var senderInfo = senderAddrInfoList.FirstOrDefault(a => a.SenderAddr == model.SenderAddr && a.SenderDisplayName == model.SenderDisplayName);
                if (senderInfo == null)
                {
                    throw new Exception("数据参数错误");
                }

                Regex r = new Regex(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");

                model.EmailBody = model.EmailBody.Replace("data-custom=\"actionCol\"", " style=\"display:none;\" ");
                model.ColNames  = model.ColNames.Replace("data-custom=\"actionCol\"", " style=\"display:none;\" ");

                var emailBodyArr   = model.EmailBody.Split(new string[] { "$$$" }, StringSplitOptions.RemoveEmptyEntries);
                var emailToAddrArr = model.ToAddr.Split(new string[] { "$$$" }, StringSplitOptions.RemoveEmptyEntries);

                for (int i = 0; i < emailBodyArr.Length; i++)
                {
                    strEndToAddr = emailToAddrArr[i];
                    if (!r.IsMatch(emailToAddrArr[i]))
                    {
                        throw new Exception("邮箱地址错误");
                    }
                    string body = "<table border=\"1\" align=\"left\" cellpadding=\"3\" cellspacing=\"0\">" +
                                  model.ColNames + emailBodyArr[i] +
                                  "</table>";


                    EmailHelper.SendPrivateMail(model.SenderAddr, senderInfo.Password, model.SenderDisplayName, senderInfo.Host, model.Subuject, emailToAddrArr[i], body);
                }
            }
            catch (Exception ex)
            {
                returnToClient.Result    = -1;
                strEndToAddr             = strEndToAddr.IsNullOrEmpty() ? strEndToAddr: "在给" + strEndToAddr + "发送时";
                returnToClient.ErrorDesc = strEndToAddr + "[" + ex.Message + "]";
            }
            string data = JsonHelper.ToJson(returnToClient);

            return(Json(data));
        }
        public static async Task <bool> SendSMTP(SendEmailModel sendEmailModel, CancellationToken cancellationToken)
        {
            var email = Email
                        .From(sendEmailModel.From)
                        .To(sendEmailModel.To)
                        .Subject(sendEmailModel.Subject)
                        .Body(sendEmailModel.Body, true);

            SendResponse sendResponse = await email.SendAsync(cancellationToken);

            return(sendResponse.Successful);
        }
        public void Handle(CustomerHasTakenLoanEvent @event)
        {
            // Some logic (maybe business as well) related with actions when customer has taken loan

            // NOTE: In this example it looks exactly the same as Approach#3,
            // but in this case dependencies should be installed via NuGet instead of direct referring EmailSender project 

            var mailBody = $"Hi, {@event.CustomerFirstName}\n\n" +
                           $"You have taken a loan for {@event.LoanAmount} {@event.LoanCurrency}.";
            var sendEmailModel = new SendEmailModel(@event.CustomerMailAddress, MailSubject, mailBody);
            _emailSender.SendMail(sendEmailModel);
        }
Example #30
0
 public CustomerModel()
 {
     AvailableTimeZones                    = new List <SelectListItem>();
     SendEmail                             = new SendEmailModel();
     SendPm                                = new SendPmModel();
     AvailableCustomerRoles                = new List <CustomerRoleModel>();
     AssociatedExternalAuthRecords         = new List <AssociatedExternalAuthModel>();
     AvailableCountries                    = new List <SelectListItem>();
     AvailableStates                       = new List <SelectListItem>();
     AvailableVendors                      = new List <SelectListItem>();
     CustomerAttributes                    = new List <CustomerAttributeModel>();
     AvailableNewsletterSubscriptionStores = new List <StoreModel>();
 }
Example #31
0
        public async Task <IActionResult> Post(SendEmailModel model)
        {
            try
            {
                await _sendEmailService.SendMailAsync(model);
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message + " | " + e.InnerException?.Message));
            }

            return(NoContent());
        }