public async Task <bool> SendPasswordResetLink(HttpRequest request, string email)
        {
            var user = await _userManager.FindByEmailAsync(email);

            if (user == null)
            {
                return(false);
            }

            var emailIsConfirmed = await _userManager.IsEmailConfirmedAsync(user);

            if (!emailIsConfirmed)
            {
                return(false);
            }

            var token = await GetEncodedPasswordResetToken(user);

            var callbackUrl = $"{request?.Scheme}://{request?.Host}{request?.PathBase}/Account/ResetPassword/{user.Id}?code={token}";
            var settings    = await _settings.Get();

            var htmlBody    = $"Please reset your password by clicking <a href=\"{callbackUrl}\">here</a>";
            var textBody    = callbackUrl;
            var smtpRequest = new SmtpRequest(settings, htmlBody, textBody, user.UserName, Constants.Account.ResetPasswordEmailSubject);
            await _emailSender.SendEmail(smtpRequest);

            return(true);
        }
        public async Task <ActionResult> ApproveRejectLeave(List <ApproveDenyLeave> approveDenyLeaveRequest)
        {
            try
            {
                SmtpRequest conf = new SmtpRequest();
                conf.Host     = _settings.Value.smtp.Host;
                conf.Port     = _settings.Value.smtp.Port;
                conf.UserName = _settings.Value.smtp.Username;
                conf.Password = _settings.Value.smtp.Password;
                AppSettings settings = new AppSettings();
                string      admin    = _settings.Value.Admin;

                _response = await _LeavesService.ApproveRejectLeave(approveDenyLeaveRequest, conf, admin);

                if (_response.Status == false)
                {
                    _json = JsonConvert.SerializeObject(_response, _serializerSettings);
                    return(BadRequest(_json));
                }

                _json = JsonConvert.SerializeObject(_response, _serializerSettings);
                return(new OkObjectResult(_json));
            }
            catch (Exception ex)
            {
                _response.Message = ex.Message;
                _response.Status  = false;
                _json             = JsonConvert.SerializeObject(_response, _serializerSettings);
                return(BadRequest(_json));
            }
        }
        public async Task <ActionResult> Create([FromBody] LeaveRequest leaveRequest)
        {
            try
            {
                SmtpRequest conf = new SmtpRequest();
                conf.Host     = _settings.Value.smtp.Host;
                conf.Port     = _settings.Value.smtp.Port;
                conf.UserName = _settings.Value.smtp.Username;
                conf.Password = _settings.Value.smtp.Password;
                //leaveRequest.UserId = User.Identity.Name;
                AppSettings settings = new AppSettings();
                string      admin    = _settings.Value.Admin;
                _response = await _LeavesService.CreateLeave(leaveRequest, conf, admin);

                if (_response.Status == false)
                {
                    _json = JsonConvert.SerializeObject(_response, _serializerSettings);
                    return(BadRequest(_json));
                }

                _json = JsonConvert.SerializeObject(_response, _serializerSettings);
                return(new OkObjectResult(_json));
            }
            catch (Exception ex)
            {
                _response.Message = ex.Message;
                _response.Status  = false;
                _json             = JsonConvert.SerializeObject(_response, _serializerSettings);
                return(BadRequest(_json));
            }
        }
Exemple #4
0
        public async Task SendEmail_GivenValidSmtpCredentials_SendsEmail()
        {
            try
            {
                //arrange
                var settingsService = _fixture.Resolve <ISiteSettingsService>();
                var settings        = await settingsService.Get();

                var sut         = _fixture.Resolve <IEmailService>();
                var testAddress = Guid.NewGuid().ToString().Substring(0, 5) + "@mailinator.com";
                var order       = OrderStubs.Orders(testAddress).FirstOrDefault();
                var textBody    = EmailTemplates.GetOrderConfirmationTextBody(order, true);
                var htmlBody    = EmailTemplates.GetOrderConfirmationHtmlBody(order);
                var request     = new SmtpRequest(settings, htmlBody, textBody, order.Email, "BlueTapeCrew.com Email Integration Test");

                //act
                await sut.SendEmail(request);

                //assert
                Assert.True(true);
            }
            catch (Exception ex)
            {
                Assert.True(false, ex.Message);
            }
        }
Exemple #5
0
        private static void HandleDeadLetter(SmtpRequest request)
        {
            var dir      = Directory.CreateDirectory(DeadLetterDir);
            var fileName = "outbound-email-" + DateTime.UtcNow.ToFileTimeUtc() + ".json";
            var path     = Path.Combine(dir.FullName, fileName);

            request.Password = "";
            var json = request.ToJson(true);

            File.WriteAllText(path, json);
        }
Exemple #6
0
        private static MimeMessage CreateMessage(SmtpRequest request)
        {
            if (request.To == null)
            {
                throw new ArgumentNullException("request", "[To] property is null on the SmtpRequest Object");
            }
            var message = CreateMimeMessage(request.From, request.To, request.Subject);

            message.Body = CreateMessageBody(request.TextBody, request.HtmlBody);
            return(message);
        }
        public async Task SendEmailConfirmationLink(HttpRequest request, string username)
        {
            var user = await _userManager.FindByEmailAsync(username);

            var token = await GetEncodedEmailConfirmToken(user);

            var callbackUrl = $"{request?.Scheme}://{request?.Host}{request?.PathBase}/Account/ConfirmEmail/{user.Id}?code={token}";
            var settings    = await _settings.Get();

            var htmlBody    = $"Please confirm your account by clicking <a href=\"{callbackUrl}\">here</a>";
            var smtpRequest = new SmtpRequest(settings, htmlBody, callbackUrl, user.Email, Subject);
            await _emailSender.SendEmail(smtpRequest);
        }
        public static bool SendLeaveStatus(string emailAddress, SmtpRequest smtpRequest, bool leaveStatus, string admin)
        {
            try
            {
                StringBuilder emailMessage = new StringBuilder();
                string        status       = leaveStatus ? "approved" : "rejected";
                emailMessage.Append("<p>Hello,</p>");
                emailMessage.Append("<p>You have   " + status + " the leave requested  by " + emailAddress + "");
                SendEmail(admin, emailMessage, "DITS - Leave Status " + emailAddress + " ", true, smtpRequest);

                return(true);
            }
            catch (Exception e)
            {
                // Trace.WriteLine(String.Format("Failure to send email to {0}.", emailAddress));
                return(false);
            }
        }
Exemple #9
0
        public async Task SendEmail(SmtpRequest request)
        {
            using var client = new SmtpClient();
            var message = CreateMessage(request);

            if (string.IsNullOrEmpty(request.Password) || string.IsNullOrEmpty(request.Host) || request.Port == 0)
            {
                HandleDeadLetter(request);
            }
            else
            {
                await client.ConnectAsync(request.Host, request.Port).ConfigureAwait(false);

                client.AuthenticationMechanisms.Remove("XOAUTH2");
                await client.AuthenticateAsync(request.UserName, request.Password).ConfigureAwait(false);

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

                await client.DisconnectAsync(true).ConfigureAwait(false);
            }
        }
        public async Task <BaseResponse> CreateLeave(LeaveRequest leaveRequest, SmtpRequest smtpRequest, string admin)
        {
            try
            {
                var getPendingId = (_globalCodesRepository.GetSingle(x => x.CodeName == "Pending").GlobalCodeId);
                var CreateLeave  = _mapper.Map <Leaves>(leaveRequest);
                CreateLeave.EmployeeId    = leaveRequest.EmployeeId;
                CreateLeave.LeaveType     = leaveRequest.LeaveType;
                CreateLeave.StartDate     = leaveRequest.StartDate;
                CreateLeave.EndDate       = leaveRequest.EndDate;
                CreateLeave.Reason        = leaveRequest.Reason;
                CreateLeave.NumberOfDays  = leaveRequest.NumberOfDays;
                CreateLeave.IsActive      = true;
                CreateLeave.CreatedOn     = DateTime.Now;
                CreateLeave.AppliedDate   = DateTime.Now;
                CreateLeave.RequestStatus = getPendingId;

                var data = _leavesRepository.Add(CreateLeave);

                if (data != null)
                {
                    var leaveTypeName = await _leavesRepository.GetLeaveRecord(data);

                    bool SendEmail = NotificationHelper.SendLeaveRequestEmail(leaveTypeName, smtpRequest, admin);
                    _response.Status  = true;
                    _response.Message = SendEmail? Constants.LEAVE_CREATED :Constants.EMAIL_ERROR;
                }
                else
                {
                    _response.Message = Constants.LEAVE_NOT_CREATED;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                _response.Status  = false;
                _response.Message = Constants.DEFAULT_ERROR_MSG;
            }
            return(_response);
        }
        public static bool SendLeaveRequestEmail(LeaveResponse leaveResponse, SmtpRequest smtpRequest, string admin)
        {
            var startDate        = leaveResponse.StartDate.Date.ToString("%d-%M-yyyy");
            var endDate          = leaveResponse.EndDate.Date.ToString("%d-%M-yyyy");
            var firstAndLastName = (leaveResponse.FirstName).Trim() + " " + (leaveResponse.LastName).Trim();

            try
            {
                var subject = "Leave Request by " + firstAndLastName + " - " + startDate;
                //var subject = "Leave Request by " + leaveResponse.Email + " - " + startDate;
                StringBuilder emailMessage = new StringBuilder();
                emailMessage.Append("<p>Hello,</p>");
                emailMessage.Append("<p>" + leaveResponse.Email + " has requested leave. Details are given below.</p>");
                emailMessage.Append("<table border=1 style='width: 60%;margin-left: 10%;'>");
                emailMessage.Append("<tr><th style='width: 30%;text-align: left;font-family: Arial; font-size: 10pt;'><p style='margin-left: 5%;'>" + "Start Date" + "</p></th>");
                emailMessage.Append("<td style='text-align: left;'><p style='margin-left: 5%;'>" + startDate + "</p></td> </tr>");
                emailMessage.Append("<tr><th style='width: 30%;text-align: left;font-family: Arial; font-size: 10pt;'><p style='margin-left: 5%;'>" + "End Date" + "</p></th>");
                emailMessage.Append("<td style='text-align: left;'><p style='margin-left: 5%;'>" + endDate + "</p></td></tr>");
                emailMessage.Append("<tr><th style='width: 30%;text-align: left;font-family: Arial; font-size: 10pt;'><p style='margin-left: 5%;'>" + "Leave Type " + "</p></th>");
                emailMessage.Append("<td style='text-align: left;'><p style='margin-left: 5%;'>" + leaveResponse.LeaveType + "</p></td></tr>");
                emailMessage.Append("<tr><th style='width: 30%;text-align: left;font-family: Arial; font-size: 10pt;'><p style='margin-left: 5%;'>" + "Duration" + "</p></th>");
                emailMessage.Append("<td style='text-align: left;'><p style='margin-left: 5%;'>" + leaveResponse.Duration + "</p></td></tr>");
                emailMessage.Append("<tr><th style='width: 30%;text-align: left;font-family: Arial; font-size: 10pt;'><p style='margin-left: 5%;'>" + "Reason" + "</p></th>");
                emailMessage.Append("<td style='text-align: left;'><p style='margin-left: 5%; margin-right: 5%;'>" + leaveResponse.Reason + "</p></td></tr>");
                emailMessage.Append("</table>");
                emailMessage.Append("<p>Kindly consider for your kind approval. </p>");
                emailMessage.Append("<p>Thanks </p>");
                emailMessage.Append("<p>" + firstAndLastName + "</p>");
                SendEmail(admin, emailMessage, subject, true, smtpRequest);
                return(true);
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                // Trace.WriteLine(String.Format("Failure to send email to {0}.", emailAddress));
                return(false);
            }
        }
Exemple #12
0
 // TODO: 拡張メソッドへまとめる
 public static void ExecHello(SmtpRequest req)
 {
     new Hello(req).Run();
 }
 private static void SendEmail(string emailAddress, StringBuilder emailMessage, string subject, bool html, SmtpRequest smtpRequest)
 {
     try
     {
         MailMessage email = new MailMessage();
         email.From = new MailAddress(smtpRequest.UserName, requestName);
         email.To.Add(new MailAddress(emailAddress));
         //email.To.Add(new MailAddress("*****@*****.**"));
         email.Subject    = subject;
         email.Body       = emailMessage.ToString();
         email.IsBodyHtml = html;
         SmtpClient smtpServer = new SmtpClient();
         smtpServer.Host = smtpRequest.Host;
         smtpServer.UseDefaultCredentials = false;
         smtpServer.Port           = Convert.ToInt32(smtpRequest.Port);
         smtpServer.Credentials    = new NetworkCredential(smtpRequest.UserName, smtpRequest.Password);
         smtpServer.EnableSsl      = true;
         smtpServer.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
         smtpServer.Send(email);
     }
     catch (Exception ex)
     {
         throw (ex);
     }
 }
        public static bool SendPasswordResetEmail(ForgotPasswordRequest forgotPasswordRequest, string guid, SmtpRequest smtpRequest)
        {
            try
            {
                StringBuilder emailMessage = new StringBuilder();
                //var Url= "http://ditstekdemo.com/ditsportal/change-password";
                emailMessage.Append("<p>Hello,</p>");
                emailMessage.Append("<p style='margin-left:10%;margin-top:5%'>You have requested a password reset for the DITS website.</p>");
                emailMessage.Append(string.Format("<p style='margin-left:10%;'><a href='{0}?email={1}&token={2}'>Please click here to change your password</a></p>", forgotPasswordRequest.Url, forgotPasswordRequest.Email, guid));
                emailMessage.Append("<p style='margin-left:10%;margin-bottom:5%'>If you did not request a password reset, please just ignore this email.");
                emailMessage.Append("<p>Thank you for using Dits Portal</p>");

                SendEmail(forgotPasswordRequest.Email, emailMessage, "DITS - Password Reset Request", true, smtpRequest);

                return(true);
            }
            catch (Exception ex)
            {
                // Trace.WriteLine(String.Format("Failure to send email to {0}.", emailAddress));
                return(false);
            }
        }
Exemple #15
0
 public Rcpt(SmtpRequest req, IEnumerable <string> rcpts)
 {
     Request​ = req;
     Rcpts    = rcpts;
 }
Exemple #16
0
 public Plain(SmtpRequest req)
 {
     Request​ = req;
 }
Exemple #17
0
        /// <summary>
        ///  Create an SMTP request object given a line of the input stream from the client and the current internal state.
        ///  </summary>
        /// <param name="s">line of input</param>
        /// <param name="state">current state</param>
        /// <returns>A populated SmtpRequest object</returns>
        public static SmtpRequest CreateRequest(string s, SmtpState state)
        {
            SmtpActionType action         = null;
            string         request_Params = null;

            if (state == SmtpState.DATA_HDR)
            {
                if (s.Equals("."))
                {
                    action = SmtpActionType.DATA_END;
                }
                else if (s.Length < 1)
                {
                    action = SmtpActionType.BLANK_LINE;
                }
                else
                {
                    action         = SmtpActionType.UNRECOG;
                    request_Params = s;
                }
            }
            else if (state == SmtpState.DATA_BODY)
            {
                if (s.Equals("."))
                {
                    action = SmtpActionType.DATA_END;
                }
                else
                {
                    action         = SmtpActionType.UNRECOG;
                    request_Params = s;
                }
            }
            else
            {
                string su = s.ToUpper();
                if (su.StartsWith("EHLO ") || su.StartsWith("HELO"))
                {
                    action         = SmtpActionType.EHLO;
                    request_Params = s.Substring(5);
                }
                else if (su.StartsWith("MAIL FROM:"))
                {
                    action         = SmtpActionType.MAIL;
                    request_Params = s.Substring(10);
                }
                else if (su.StartsWith("RCPT TO:"))
                {
                    action         = SmtpActionType.RCPT;
                    request_Params = s.Substring(8);
                }
                else if (su.StartsWith("DATA"))
                {
                    action = SmtpActionType.DATA;
                }
                else if (su.StartsWith("QUIT"))
                {
                    action = SmtpActionType.QUIT;
                }
                else if (su.StartsWith("RSET"))
                {
                    action = SmtpActionType.RSET;
                }
                else if (su.StartsWith("NOOP"))
                {
                    action = SmtpActionType.NOOP;
                }
                else if (su.StartsWith("EXPN"))
                {
                    action = SmtpActionType.EXPN;
                }
                else if (su.StartsWith("VRFY"))
                {
                    action = SmtpActionType.VRFY;
                }
                else if (su.StartsWith("HELP"))
                {
                    action = SmtpActionType.HELP;
                }
                else
                {
                    action = SmtpActionType.UNRECOG;
                }
            }

            SmtpRequest req = new SmtpRequest(action, request_Params, state);

            return(req);
        }
Exemple #18
0
 public CramMd5(SmtpRequest req)
 {
     Request​ = req;
 }
Exemple #19
0
 public Mail(SmtpRequest req, string adr)
 {
     Request​    = req;
     ReversePath = new System.Net.Mail.MailAddress(adr).Address;
 }
        public async Task <MainResponse> SetResetPasswordToken(ForgotPasswordRequest forgotPasswordRequest, SmtpRequest smtpRequest)
        {
            try
            {
                var user = _userRepository.GetSingle(x => x.Email == forgotPasswordRequest.Email.ToLower() && x.IsActive == true);
                if (user != null)
                {
                    string guid = Guid.NewGuid().ToString();
                    user.ResetToken        = guid;
                    user.ResetTokenExpired = DateTime.UtcNow.AddMinutes(60);
                    var data = await _userRepository.UpdateAsync(user);

                    bool SendEmail = NotificationHelper.SendPasswordResetEmail(forgotPasswordRequest, guid, smtpRequest);
                    _response.Status  = true;
                    _response.Message = SendEmail ? Constants.RESET_PASSWORD_EMAIL : Constants.EMAIL_ERROR;
                    var userResponse = _mapper.Map <UserResponse>(data);
                    _response.userResponse = userResponse;
                }
                else
                {
                    _response.Status  = false;
                    _response.Message = Constants.NO_RECORD_FOUND;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                _baseResponse.Status = false;
                _response.Message    = Constants.DEFAULT_ERROR_MSG;
            }

            return(_response);
        }
        public async Task <BaseResponse> ApproveRejectLeave(List <ApproveDenyLeave> approveDenyLeaveRequest, SmtpRequest smtpRequest, string admin)
        {
            _baseResponse = new BaseResponse();
            int approved = await GetGlobalCode("Approved");

            int rejected = await GetGlobalCode("Declined");

            try
            {
                if (approveDenyLeaveRequest.Count > 0)
                {
                    foreach (var leave in approveDenyLeaveRequest)
                    {
                        var leaves = ObjContext.Leave.Where(x => x.LeaveId == leave.LeaveId).FirstOrDefault();
                        if (leave.IsApproved == true)
                        {
                            var data = ObjContext.LeavesBalance.Where(x => x.EmployeeId == leave.EmployeeId).FirstOrDefault();

                            if (data != null)
                            {
                                var balance = data.Balance;
                                var availed = data.Availed;
                                data.ModifiedOn = DateTime.Now;
                                data.ModifiedBy = "admin";
                                data.Balance    = balance - leave.NumberOfDays;
                                data.Availed    = availed + leave.NumberOfDays;
                            }
                            //update leaves table
                            leaves.RequestStatus  = approved;
                            _baseResponse.Message = Constants.LEAVE_APPROVED;
                        }
                        else
                        {
                            leaves.RequestStatus   = rejected;
                            leaves.RejectedBy      = "Admin";
                            leaves.RejectionDate   = DateTime.Now;
                            leaves.RejectionReason = leave.RejectionReason;
                            _baseResponse.Message  = Constants.LEAVE_NOT_APPROVED;
                        }
                        leaves.ModifiedBy = "Admin";
                        leaves.ModifiedOn = DateTime.Now;
                        await ObjContext.SaveChangesAsync();

                        string userEmail = await GetUserById(leave.EmployeeId);

                        var  leaveData = ObjContext.Leave.Where(x => x.LeaveId == leaves.LeaveId).FirstOrDefault();
                        bool sendEmail = NotificationHelper.SendLeaveStatusEmail(userEmail, smtpRequest, leave.IsApproved, admin);
                        _baseResponse.Status = true;
                    }
                }
            }

            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                _baseResponse.Status  = false;
                _baseResponse.Message = Constants.LEAVE_NOT_APPROVED;
            }


            return(_baseResponse);
        }
Exemple #22
0
 public Login(SmtpRequest req)
 {
     Request​ = req;
 }
Exemple #23
0
		/// <summary>
		///  Create an SMTP request object given a line of the input stream from the client and the current internal state.
		///  </summary>
		/// <param name="s">line of input</param>
		/// <param name="state">current state</param>
		/// <returns>A populated SmtpRequest object</returns>
		public static SmtpRequest CreateRequest(string s, SmtpState state)
		{
			SmtpActionType action = null;
			string request_Params = null;

			if (state == SmtpState.DATA_HDR)
			{
				if (s.Equals("."))
				{
					action = SmtpActionType.DATA_END;
				}
				else if (s.Length < 1)
				{
					action = SmtpActionType.BLANK_LINE;
				}
				else
				{
					action = SmtpActionType.UNRECOG;
					request_Params = s;
				}
			}
			else if (state == SmtpState.DATA_BODY)
			{
				if (s.Equals("."))
				{
					action = SmtpActionType.DATA_END;
				}
				else
				{
					action = SmtpActionType.UNRECOG;
					request_Params = s;
				}
			}
			else
			{
				string su = s.ToUpper();
				if (su.StartsWith("EHLO ") || su.StartsWith("HELO"))
				{
					action = SmtpActionType.EHLO;
					request_Params = s.Substring(5);
				}
				else if (su.StartsWith("MAIL FROM:"))
				{
					action = SmtpActionType.MAIL;
					request_Params = s.Substring(10);
				}
				else if (su.StartsWith("RCPT TO:"))
				{
					action = SmtpActionType.RCPT;
					request_Params = s.Substring(8);
				}
				else if (su.StartsWith("DATA"))
				{
					action = SmtpActionType.DATA;
				}
				else if (su.StartsWith("QUIT"))
				{
					action = SmtpActionType.QUIT;
				}
				else if (su.StartsWith("RSET"))
				{
					action = SmtpActionType.RSET;
				}
				else if (su.StartsWith("NOOP"))
				{
					action = SmtpActionType.NOOP;
				}
				else if (su.StartsWith("EXPN"))
				{
					action = SmtpActionType.EXPN;
				}
				else if (su.StartsWith("VRFY"))
				{
					action = SmtpActionType.VRFY;
				}
				else if (su.StartsWith("HELP"))
				{
					action = SmtpActionType.HELP;
				}
				else
				{
					action = SmtpActionType.UNRECOG;
				}
			}

			SmtpRequest req = new SmtpRequest(action, request_Params, state);
			return req;
		}
Exemple #24
0
 public Data(SmtpRequest req, Config profile, MailMessage m)
 {
     Request​ = req;
     _profile = profile;
     msg      = m;
 }
 public async Task <BaseResponse> ApproveRejectLeave(List <ApproveDenyLeave> approveDenyLeaveRequest, SmtpRequest smtpRequest, string admin)
 {
     return(await _leavesRepository.ApproveRejectLeave(approveDenyLeaveRequest, smtpRequest, admin));
 }
Exemple #26
0
 public Quit(SmtpRequest req)
 {
     Request​ = req;
 }
Exemple #27
0
 public Hello(SmtpRequest req)
 {
     Request​ = req;
 }