public async Task with_duplicated_person_not_contains_same_email_should_return_new_SSG_Email()
        {
            _testEmailId = Guid.NewGuid();
            _odataClientMock.Setup(x => x.For <SSG_Email>(null).Set(It.Is <EmailEntity>(x => x.Email == "notContain"))
                                   .InsertEntryAsync(It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(new SSG_Email()
            {
                Email   = "notContain",
                EmailId = _testEmailId
            })
                     );
            _duplicateServiceMock.Setup(x => x.Exists(It.Is <SSG_Person>(m => m.PersonId == _testId), It.Is <EmailEntity>(m => m.Email == "notContain")))
            .Returns(Task.FromResult(Guid.Empty));

            var emailEntity = new EmailEntity()
            {
                Email  = "notContain",
                Person = new SSG_Person()
                {
                    PersonId = _testId, IsDuplicated = true
                }
            };

            var result = await _sut.CreateEmail(emailEntity, CancellationToken.None);

            Assert.AreEqual("notContain", result.Email);
            Assert.AreEqual(_testEmailId, result.EmailId);
        }
Beispiel #2
0
        static void Main(string [] args)
        {
            //Entidade são classes e objetos que SÃO ALGUMA COISA
            EmailEntity emailModel = new EmailEntity();

            emailModel.MailTo  = "*****@*****.**";
            emailModel.Subject = "Teste123";
            emailModel.Message = "Corpo do Texto";

            List <string> emailsCcList = new List <string>();

            emailsCcList.Add("*****@*****.**");
            emailsCcList.Add("*****@*****.**");


            //Serviços ou Interface são classes e objetos que FAZEM ALGUMA COISA
            IEmailService emailService = new EmailService();

            if (emailService.SendEmails(emailModel, emailsCcList))
            {
                Console.WriteLine("Emails enviados com sucesso!");
            }
            else
            {
                Console.WriteLine("Erro ao enviar e-mails!");
            }
        }
        public async Task with_non_duplicated_person_CreateEmail_should_return_new_SSG_Email()
        {
            _testEmailId = Guid.NewGuid();
            _odataClientMock.Setup(x => x.For <SSG_Email>(null).Set(It.Is <EmailEntity>(x => x.Email == "normal"))
                                   .InsertEntryAsync(It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(new SSG_Email()
            {
                Email   = "normal",
                EmailId = _testEmailId
            })
                     );
            var emailEntity = new EmailEntity()
            {
                Email  = "normal",
                Person = new SSG_Person()
                {
                    PersonId = _testId
                }
            };

            var result = await _sut.CreateEmail(emailEntity, CancellationToken.None);

            Assert.AreEqual("normal", result.Email);
            Assert.AreEqual(_testEmailId, result.EmailId);
        }
Beispiel #4
0
        public EmailEntity GetEmailServerDetails()
        {
            string         CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            SqlDataAdapter adapter;
            DataSet        ds     = new DataSet();
            EmailEntity    retobj = new EmailEntity();

            try
            {
                using (SqlConnection con = new SqlConnection(CS))
                {
                    SqlCommand cmd = new SqlCommand("USP_GetEmailServerDetails", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    con.Open();
                    adapter = new SqlDataAdapter(cmd);
                    adapter.Fill(ds);

                    for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
                    {
                        EmailEntity obj = new EmailEntity();
                        obj.Port         = ds.Tables[0].Rows[i]["Port"] == DBNull.Value ? 587 : Convert.ToInt32(ds.Tables[0].Rows[i]["Port"].ToString());
                        obj.Host         = ds.Tables[0].Rows[i]["Host"] == DBNull.Value ? "smtp.gmail.com" : ds.Tables[0].Rows[i]["Host"].ToString();
                        obj.UserName     = ds.Tables[0].Rows[i]["UserName"] == DBNull.Value ? "" : ds.Tables[0].Rows[i]["UserName"].ToString();
                        obj.UserPassword = ds.Tables[0].Rows[i]["UserPassword"] == DBNull.Value ? "" : ds.Tables[0].Rows[i]["UserPassword"].ToString();
                        obj.EnableSsl    = Convert.ToBoolean(ds.Tables[0].Rows[i]["EnableSsl"]);
                        retobj           = obj;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(retobj);
        }
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByEmailAsync(model.Email);

                if (user == null)
                {
                    ViewBag.UserNotFound = true;
                    return(View());
                }

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

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

                SendEmail.Send(user.Email, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
                var emailEntity = new EmailEntity
                {
                    Affiliate   = user,
                    CallbackUrl = callbackUrl,
                    Culture     = _cookie.GetCookieLanguage(Request, Response).Value
                };
                _notificationService.SendEmailFromTemplate(NotificationTemplateTypes.ForgotPassword, emailEntity);
                return(RedirectToAction("Index", "Home"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public bool CreateSupplier(AddressBook addressBook, EmailEntity emailEntity, LocationAddress locationAddress)
        {
            try
            {
                AddressBook
                .CreateSupplierAddressBook(addressBook, emailEntity)
                .Apply();

                Task <AddressBook> addressBookLookupTask = Task.Run(async() => await AddressBook.Query().GetAddressBookbyEmail(emailEntity.Email));

                locationAddress.AddressId = addressBookLookupTask.Result.AddressId;

                LocationAddress

                .AddLocationAddress(locationAddress)
                .Apply();

                Email.CreateSupplierEmail(addressBook.AddressId, emailEntity).Apply();

                Supplier supplier = new Supplier {
                    AddressId = addressBook.AddressId, Identification = emailEntity.Email
                };

                Supplier
                .AddSupplier(supplier)
                .Apply();
                return(true);
            }
            catch (Exception ex) { throw new Exception("CreateSupplier", ex); }
        }
Beispiel #7
0
    private bool SendEmail(string newLink)
    {
        try
        {
            EmailEntity    emailEntity    = new EmailEntity();
            EmailOperation emailOperation = new EmailOperation();

            emailEntity.SmtpServer = ConfigurationSettings.AppSettings["SMTPServer"].ToString();
            emailEntity.From       = ConfigurationSettings.AppSettings["FromMailID"].ToString();
            emailEntity.ToEmail    = txtContAdminEmailID.Text.ToString();
            emailEntity.Password   = ConfigurationSettings.AppSettings["Password"].ToString();
            emailEntity.Subject    = "Your account details for - live.lawallies.com";
            emailEntity.Body       = "Dear user, <br/> Please use the link below to login to the websitel live.lawllies.com . <br/> " + newLink.ToString() + " <br/> User Id=" + txtUserName.Text.ToString().Trim() + " <br/> Password="******"\n", " ");
            lblError.Text    = "Error : " + strError + "<br/> Stack Trace : " + ex.StackTrace.ToString();
            lblError.Visible = true;
            return(false);
        }
    }
        public bool SendEmail()
        {
            Guid        newId = Guid.NewGuid();
            EmailEntity email = new EmailEntity
            {
                Id         = newId.ToString(),
                From       = "*****@*****.**",
                To         = "*****@*****.**",
                Subject    = "test message 1",
                Message    = $"This is a test email message sent by an application.<img src=\"https://Your_Api_Address_Here/api/Receiv/{newId}.jpg\"/>",
                IsBodyHtml = true,
                IsReceived = false,
                TimeStamp  = DateTime.Now
            };

            var id = _emailRepo.InsertAsync(email);

            MailAddress from    = new MailAddress(email.From, "Jane Clayton", System.Text.Encoding.UTF8);
            MailAddress to      = new MailAddress(email.To);
            MailMessage message = new MailMessage(from, to);

            message.IsBodyHtml      = email.IsBodyHtml;
            message.Body            = email.Message;
            message.BodyEncoding    = System.Text.Encoding.UTF8;
            message.Subject         = email.Subject;
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            string userState = "test message1";

            _smtpClient.SendAsync(message, userState);
            message.Dispose();



            return(true);
        }
Beispiel #9
0
        public IActionResult SendEmailEveryXDay([Bind] EmailEntity model, string time, CancellationToken ct)
        {
            var dummyDays = int.Parse(time);

            RecurringJob.AddOrUpdate(() => _emailService.SendAsync(model, ct), Cron.DayInterval(dummyDays));
            return(Ok());
        }
Beispiel #10
0
        public Result Edit(long id, EditEmailRequest editEmail)
        {
            _logger.LogInformation($"Editing Email. EmailId {id}");

            ValidationResult validationResult = _editEmailValidator.Validate(editEmail);

            if (!validationResult.IsValid)
            {
                _logger.LogWarning($"Invalid {nameof(EditEmailRequest)} model");
                return(Result.Fail(validationResult.Errors));
            }

            Result <EmailEntity> getEmailResult = Get(id);

            if (getEmailResult.Failure)
            {
                return(Result.Fail(getEmailResult.Errors));
            }

            EmailEntity emailEntity = getEmailResult.Value;

            emailEntity.Update(editEmail.Subject, editEmail.Body);
            bool updateResult = _emailRepository.Update(emailEntity);

            if (!updateResult)
            {
                _logger.LogError($"Failed to update email", "Failed to update email");
                return(Result.Fail("failed_to_update_email", "Failed to update email"));
            }

            return(Result.Ok());
        }
Beispiel #11
0
        public async Task <string> InsertAsync(EmailEntity email)
        {
            _context.Email.Add(email);
            await _context.SaveChangesAsync();

            return(email.Id.ToString());
        }
        public async Task Send(EmailEntity email)
        {
            var smtpClient = new SmtpClient(appSettings.Host)
            {
                Port        = appSettings.Port,
                Credentials = new NetworkCredential(appSettings.Username, appSettings.Password),
                EnableSsl   = true,
            };

            //smtpClient.Send("email", "recipient", "subject", "body");

            var mailMessage = new MailMessage
            {
                From    = new MailAddress(email.GetSender().Address, email.GetSender().Name),
                Subject = email.Subject,
                Body    = email.Body
            };

            foreach (var r in email.GetRecipients())
            {
                mailMessage.To.Add(new MailAddress(r.Address, r.Name));
            }

            await smtpClient.SendMailAsync(mailMessage);
        }
Beispiel #13
0
        public async Task GivenEmail_WhenCreate_ThenCreateSuccessful()
        {
            //?Given
            var id           = "1234";
            var userName     = "******";
            var creationTime = new DateTime();

            var email = new Email
            {
                Id           = id,
                UserName     = userName,
                CreationTime = creationTime
            };

            var emailEntity = new EmailEntity
            {
                Id           = id,
                UserName     = userName,
                CreationTime = creationTime
            };

            _mockMapper.Setup(x => x.Map <EmailEntity>(It.IsAny <Email>()))
            .Returns(emailEntity)
            .Verifiable();

            //?When
            await _emailRepository.Create(email);

            //?Then
            _mockMapper.Verify();
            _mockService.Verify();
            _mockService.Verify(t => t.Create(It.IsAny <string>(), It.Is <EmailEntity>(e => EmailIsWellCreated(e, email))), Times.Once);
        }
        public object Authenticate(IObjectSpace objectSpace)
        {
            IAuthenticationOAuthUser user = null;
            AuthenticateResult       authenticateResult = Authenticate().Result;

            if (authenticateResult != null)
            {
                Claim emailClaim = authenticateResult.Identity.FindFirst(ClaimTypes.Email);
                if (emailClaim != null)
                {
                    user = (IAuthenticationOAuthUser)objectSpace.FindObject(userType, CriteriaOperator.Parse(string.Format("OAuthAuthenticationEmails[Email = '{0}']", emailClaim.Value)));
                    if (user == null && CreateUserAutomatically)
                    {
                        user          = (IAuthenticationOAuthUser)objectSpace.CreateObject(userType);
                        user.UserName = emailClaim.Value;
                        EmailEntity email = objectSpace.CreateObject <EmailEntity>();
                        email.Email = emailClaim.Value;
                        user.OAuthAuthenticationEmails.Add(email);
                        ((CustomSecurityStrategyComplex)security).InitializeNewUser(objectSpace, user);
                        objectSpace.CommitChanges();
                    }
                }
            }
            else
            {
                WebApplication.Redirect(WebApplication.LogonPage);
            }
            if (user == null)
            {
                throw new Exception("Login failed");
            }
            return(user);
        }
        public async Task <IActionResult> Edit(int id, [Bind("Id,Subject,Body")] EmailEntity emailEntity)
        {
            if (id != emailEntity.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(emailEntity);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!EmailEntityExists(emailEntity.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(emailEntity));
        }
Beispiel #16
0
        public IFluentEmail CreateCustomerEmail(CustomerView customerView)
        {
            Task <AddressBook> lookupAddressBookTask = Task.Run(() => unitOfWork.addressBookRepository.GetAddressBookByCustomerView(customerView));

            Task.WaitAll(lookupAddressBookTask);
            customerView.AddressId = lookupAddressBookTask.Result.AddressId;

            if (customerView.AddressId > 0)
            {
                EmailEntity emailEntity = new EmailEntity();
                emailEntity.AddressId  = customerView.AddressId;
                emailEntity.Email      = customerView.AccountEmail;
                emailEntity.LoginEmail = customerView.AccountEmailLogin;
                emailEntity.Password   = customerView.AccountEmailPassword;

                AddEmail(emailEntity);
                processStatus = CreateProcessStatus.Insert;
            }
            else
            {
                processStatus = CreateProcessStatus.Failed;
            }

            return(this as IFluentEmail);
        }
Beispiel #17
0
 private void btn_send_Click(object sender, EventArgs e)
 {
     try
     {
         EmailEntity email = new EmailEntity();
         email.mailFrom    = "*****@*****.**";
         email.mailPwd     = "saDECLINE123";
         email.mailSubject = msgTitle;                                //邮件主题
         email.mailBody    = tb_fkyj.Text + "=======反馈人联系方式:" + lxfs; //邮件内容
         email.isbodyHtml  = false;                                   //是否是HTML
         email.host        = "smtp.163.com";                          //如果是QQ邮箱则:smtp:qq.com,依次类推
         email.mailToArray = new string[] { "*****@*****.**" };    //接收者邮件集合
         email.mailCcArray = new string[] { "*****@*****.**" };    //抄送者邮件集合
         if (email.Send())
         {
             MessageForm mf = new MessageForm("反馈已发送,小二会尽力满足需求并及时更新!");
             mf.Show();
         }
     }
     catch (Exception ex)
     {
         MessageForm mf = new MessageForm("发送失败,原因为:" + ex.Message);
         mf.Show();
     }
 }
Beispiel #18
0
        private async Task <bool> UploadEmails()
        {
            if (_foundPerson.Emails == null)
            {
                return(true);
            }
            try
            {
                _logger.LogDebug($"Attempting to create emails records for SearchRequest[{_searchRequest.SearchRequestId}]");

                foreach (var e in _foundPerson.Emails)
                {
                    EmailEntity email = _mapper.Map <EmailEntity>(e);
                    email.SearchRequest = _searchRequest;
                    //email.SupplierTypeCode = _providerDynamicsID;
                    email.Person = _returnedPerson;
                    SSG_Email ssgEmail = await _searchRequestService.CreateEmail(email, _cancellationToken);
                    await CreateResultTransaction(ssgEmail);
                }
                return(true);
            }
            catch (Exception ex)
            {
                LogException(ex);
                return(false);
            }
        }
Beispiel #19
0
        protected EmailEntity GetEmailFromReader(int mailQueueId, IDataReader reader)
        {
            if (reader.Read())
            {
                EmailEntity emailEntity = new EmailEntity(
                    mailQueueId,
                    reader["Subject"].ToString().Trim(),
                    reader["Contents"].ToString().Trim()
                    );

                reader.Close();
                reader.Dispose();
                disConnect_dbcn_ExcuteReader();

                return(emailEntity);
            }
            else
            {
                EmailEntity dlvEntity = new EmailEntity();
                reader.Close();
                reader.Dispose();
                disConnect_dbcn_ExcuteReader();
                return(dlvEntity);
            }
        }
Beispiel #20
0
        private void DoWork(object state)
        {
            SmtpClient SMTPClient = null;
            lock (_lockObj) {
                if (_usingSMTPClients.Count < _oSMTPClients.Count && (_countWorkThreads < _configuration.MaxSendThreads || _configuration.MaxSendThreads == 0)) {
                    int i = 0;
                    for (; i < _oSMTPClients.Count; i++)
                    {
                        if (!_usingSMTPClients.Contains(_oSMTPClients[i])) {
                            _usingSMTPClients.Add(_oSMTPClients[i]);
                            SMTPClient = _oSMTPClients[i];
                            _countWorkThreads++;
                            break;
                        }
                    }
                    if (i == _oSMTPClients.Count)
                        return;
                }
                else return;
            }

            /* = new SmtpClient(oSMTPClient.Host, oSMTPClient.Port);
            SMTPClient.Credentials = oSMTPClient.Credentials;
            SMTPClient.EnableSsl = oSMTPClient.EnableSsl;
            SMTPClient.UseDefaultCredentials = oSMTPClient.UseDefaultCredentials;
            SMTPClient.DeliveryMethod = oSMTPClient.DeliveryMethod;
            SMTPClient.PickupDirectoryLocation = oSMTPClient.PickupDirectoryLocation;
            SMTPClient.DeliveryFormat = oSMTPClient.DeliveryFormat;
            SMTPClient.Timeout = oSMTPClient.Timeout;
            SMTPClient.TargetName = oSMTPClient.TargetName;*/
            EmailEntity emailEntity = null;
            bool isSended = true;
            for (int i = 0; i < _configuration.MaxSendEmailInOneThread && !_emailService.EmailQueue.IsEmpty(); i++)
            {
                emailEntity = _emailService.EmailQueue.Dequeue();
                isSended = true;
                try
                {
                    SMTPClient.Send(emailEntity.Message);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    isSended = false;
                }
                Console.WriteLine($"Sended from {((NetworkCredential)SMTPClient.Credentials).UserName} {isSended}!");
                emailEntity.CompletedEventHandler?.Invoke(new EmailSendCompleatedEntity
                {
                    EmailEntity = emailEntity,
                    EndSendingTime = DateTime.Now,
                    IsSended = isSended
                });
            }
            lock (_lockObj)
            {
                _usingSMTPClients.Remove(SMTPClient);
                _countWorkThreads--;
            }
        }
 public static string Create(EmailEntity emailEntity, string pointOfContactName)
 {
     var sb = new StringBuilder();
     sb.AppendLine(emailEntity.Salutation.Replace("[FirstName]", pointOfContactName));
     sb.AppendLine(emailEntity.Body.Replace("[NiceWeekend]", RandomNiceWeekend()));
     sb.AppendLine(emailEntity.Signature);
     return sb.ToString();
 }
Beispiel #22
0
        public async Task <SupplierView> GetSupplierViewByEmail(EmailEntity emailEntity)
        {
            Supplier supplier = await _unitOfWork.supplierRepository.GetEntityByEmail(emailEntity);

            SupplierView view = await MapToSupplierView(supplier);

            return(view);
        }
        public string CreateNew(string subjet, string author, string body)
        {
            string newId = (index++).ToString();
            var    e     = new EmailEntity(newId, author, subjet, body);

            storage.Add(newId, e);
            return(newId);
        }
Beispiel #24
0
        public IActionResult SendEmailAfterward([Bind] EmailEntity model, string time, CancellationToken ct)
        {
            // BackgroundJob.Schedule(() => _emailService.SendAsync(model, ct), TimeSpan.FromMinutes(1));

            var dummyMinutes = int.Parse(time);

            BackgroundJob.Schedule(() => _emailService.SendAsync(model, ct), TimeSpan.FromMinutes(dummyMinutes));
            return(Ok());
        }
        public static void SendEmailWithAttachement(ClientEntity clientEntity, EmailEntity emailEntity, IInvoiceDetails invoiceDetails, string pdfFileName, DateTime now)
        {
            var subject = "Invoice #" + InvoiceNameGenerator.GetName(invoiceDetails.Number, now);
            var sender = new Sender(new DefaultSmtpWrapper().Data);

            var body = EmailBodyCreator.Create(emailEntity, clientEntity.PointOfContactName);

            sender.Send(clientEntity.PointOfContactEmail, subject, body, new List<string> { pdfFileName });
        }
Beispiel #26
0
 public void SendMail(EmailEntity model)
 {
     //var message = new Message(new string[] { "*****@*****.**" }, "Test email", "This is the content from our email.");
     foreach (var item in model.To)
     {
         var message = new Message(model.To, model.Subject, model.Body);
         _emailSender.SendEmail(message);
     }
 }
Beispiel #27
0
        public async Task <IActionResult> DeleteEmails([FromBody] EmailEntityView view)
        {
            EmailModule invMod = new EmailModule();
            EmailEntity email  = await invMod.Email.Query().MapToEntity(view);

            invMod.Email.DeleteEmail(email).Apply();

            return(Ok(view));
        }
Beispiel #28
0
        public bool Send(EmailEntity model)
        {
            // Operation to send email goes here

            // save email object to database
            _context.Add(model);
            var t = _context.SaveChanges();

            return(t > 0);
        }
        public async Task <Response <string> > Handle(GetEmailStatusQuery request, CancellationToken cancellationToken)
        {
            EmailEntity email = emailRepo.GetById(request.EmailId);

            if (email == null)
            {
                return(Response.Fail <string>(EmailResult.NotExists));
            }
            return(Response.Ok <string>(email.Status.ToString()));
        }
Beispiel #30
0
        public async Task <Response <EmailDto> > Handle(GetEmailDetailsQuery request, CancellationToken cancellationToken)
        {
            EmailEntity email = emailRepo.GetById(request.EmailId);

            if (email == null)
            {
                return(Response.Fail <EmailDto>(EmailResult.NotExists));
            }
            return(Response.Ok <EmailDto>(EmailDto.Make(email)));
        }
Beispiel #31
0
        public Result Insert(EmailEntity entity)
        {
            var con   = new DapperConnectionManager();
            var query = new QueryEntity();

            query.Entity = entity;
            query.Query  = @"INSERT INTO Emails (Type, Title, Body) 
                                             VALUES(@Type, @Title, @Body)";

            return(con.InsertQuery(query));
        }
Beispiel #32
0
 protected EmailEntity AddEmailReceiver(EmailEntity emailEntity, IDataReader reader)
 {
     while (reader.Read())
     {
         emailEntity.receiver.Add(reader["EmailAddr"].ToString().Trim());
     }
     reader.Close();
     reader.Dispose();
     disConnect_dbcn_ExcuteReader();
     return(emailEntity);
 }