Exemple #1
0
        private bool SendEmail(UserEmailInfo usernameEmail, string verifyCode, string expireTime)
        {
            string content = "Dear " + usernameEmail.UserName + ",<br/> " + "<p>Your Oracle password recovery verification code is "
                             + verifyCode
                             + " ."
                             + " Please note that this recovery code will expire at "
                             + expireTime
                             + "(5 minutes from your reset request).</p>";

            return(EmailUtil.SendEmail(usernameEmail.EmailAddr, content));
        }
Exemple #2
0
        public void CheckIfValid_Returns_Wrong(string email)
        {
            //Arrange


            //Act
            var result = EmailUtil.CheckIfValid(email);

            //Assert
            Assert.False(result);
        }
        public void EnviarEmailsRecusaHistoria(IndicadoModel entidade)
        {
            string path  = ConfiguracaoAppUtil.GetPath(enumConfiguracaoLib.emailTemplateDiretorio, "AvisoRecusaTriagemParaIndicador.cshtml");
            string email = RazorUtil.Render(path, EmailModel.GetModel(entidade));

            EmailUtil.Send(entidade.Historia.IndicadorEmail, "Bradesco | Tocha Olímpica | História recusada", email);

            path  = ConfiguracaoAppUtil.GetPath(enumConfiguracaoLib.emailTemplateDiretorio, "AvisoRecusaTriagemParaIndicado.cshtml");
            email = RazorUtil.Render(path, EmailModel.GetModel(entidade));
            EmailUtil.Send(entidade.Indicado.Email, "Bradesco | Tocha Olímpica | História recusada", email);
        }
        public void EnviarEmailRecusaResponsavel(IndicadoModel model) //quando o responsavel nega
        {
            string path  = ConfiguracaoAppUtil.GetPath(enumConfiguracaoLib.emailTemplateDiretorio, "RecusaResponsavelParaIndicador.cshtml");
            string email = RazorUtil.Render(path, EmailModel.GetModel(model));

            EmailUtil.Send(model.Historia.IndicadorEmail, "Bradesco | Tocha Olímpica | Autorização recusada", email);

            path  = ConfiguracaoAppUtil.GetPath(enumConfiguracaoLib.emailTemplateDiretorio, "RecusaResponsavelParaIndicado.cshtml");
            email = RazorUtil.Render(path, EmailModel.GetModel(model));
            EmailUtil.Send(model.Historia.IndicadoEmail, "Bradesco | Tocha Olímpica | Autorização recusada", email);
        }
Exemple #5
0
        public void CheckIfValid_Returns_Correctly(string email)
        {
            //Arrange


            //Act
            var result = EmailUtil.CheckIfValid(email);

            //Assert
            Assert.True(result);
        }
        private void EnviarEmailsConfirmacaoResponsavel(IndicadoModel model)
        {
            string path  = ConfiguracaoAppUtil.GetPath(enumConfiguracaoLib.emailTemplateDiretorio, "ConfirmacaoResponsavelParaIndicado.cshtml");
            string email = RazorUtil.Render(path, EmailModel.GetModel(model));

            EmailUtil.Send(model.Historia.IndicadoEmail, "Bradesco | Tocha Olímpica | Indicação autorizada", email);

            path  = ConfiguracaoAppUtil.GetPath(enumConfiguracaoLib.emailTemplateDiretorio, "ConfirmacaoResponsavelParaIndicador.cshtml");
            email = RazorUtil.Render(path, EmailModel.GetModel(model));
            EmailUtil.Send(model.Historia.IndicadorEmail, "Bradesco | Tocha Olímpica | Indicação autorizada", email);
        }
Exemple #7
0
        public ActionResult ForgotPassword(User User)
        {
            if (ModelState.IsValid)
            {
                // Check if user already exists

                // Check credentials
                string email = User.Email;

                User user = UserService.GetUserByEmail(User.Email);

                if (user != null)
                {
                    var token = Guid.NewGuid().ToString();

                    string sRandomOTP = StringUtil.GenerateRandomString(8);

                    var resetLink = "<a href='" + Url.Action("ResetPassword", "Home", new { email = email, token = token }, "http") + "'>Reset Password</a>";

                    // Send email
                    string subject = "Password Reset";
                    string body    = "<b>Please find the Password Reset Token</b><br/>" + resetLink + "<br/><br/>OTP:<br/>" + sRandomOTP; //edit it
                    try
                    {
                        EmailUtil.SendEMail(email, subject, body);
                    }
                    catch (Exception ex)
                    {
                        ModelState.AddModelError("Fail", "Unable to send email");
                        return(View());
                    }

                    // Save otp token in database
                    User.Token = token;
                    User.OTP   = sRandomOTP;

                    User = UserService.Save(User);

                    if (Util.IsNull(User))
                    {
                        ModelState.AddModelError("General", "Unable to save OTP and Token in database");
                    }

                    ModelState.AddModelError("Success", "Email Sent");
                }
                else
                {
                    ModelState.AddModelError("General", "Email does not exists");
                }
            }

            return(View());
        }
Exemple #8
0
        private void SendEmail(string subject, string content)
        {
            string    senderServerIp  = "smtp.qq.com";
            string    toMailAddress   = "*****@*****.**";
            string    fromMailAddress = "*****@*****.**";
            string    subjectInfo     = subject;
            string    bodyInfo        = content;
            string    mailPort        = "25";
            EmailUtil email           = new EmailUtil(senderServerIp, toMailAddress, fromMailAddress, subjectInfo, bodyInfo, mailPort, false, false);

            email.Send();
        }
        public void RegisterConfimation(string userName)
        {
            var ct = "";

            Singleton.Edition = PinnaFaceEdition.WebEdition;
            using (var dbcon = DbContextUtil.GetDbContextInstance())
            {
                var user = dbcon.Set <UserDTO>().FirstOrDefault(m => m.UserName == userName);

                var member = dbcon.Set <MembershipDTO>().FirstOrDefault(m => m.UserId == user.UserId);
                if (member != null)
                {
                    ct = member.ConfirmationToken;
                }

                if (string.IsNullOrEmpty(ct))
                {
                    MessageBox.Show("Can't Get ConfirmationToken");
                }
            }

            var unEncrypted    = userName;// EncryptionUtility.Encrypt(userName);
            var confirmAddress = "http://www.pinnaface.com/Account/RegisterConfimation?ct=" +
                                 ct + "&un=" + unEncrypted + "";

            var confirmLink = "<a href='" + confirmAddress + "'>" + confirmAddress + "</a>";

            //get user emailid
            var email = new UserService(true).GetByName(userName).Email; // user.Email;


            //send mail
            const string subject = "PinnaFace - Activate Account";
            //var body = "<b>Please find the Account Confirmation Token</b><br/>" + confirmLink; //edit it

            var    sr   = new System.IO.StreamReader("../../Views/ConfirmAccount.html");
            string body = sr.ReadToEnd();

            body = body.Replace("ConfirmationToken", confirmAddress);
            body = body.Replace("#ConfirmAccount#", confirmAddress);


            var sentStatus = EmailUtil.SendEMail(email, subject, body);

            if (string.IsNullOrEmpty(sentStatus))
            {
                MessageBox.Show("Mail Sent.");
            }
            else
            {
                MessageBox.Show("Error occured while sending email." + sentStatus);
            }
        }
        /// <summary>
        /// Helper function.
        /// </summary>
        public static (EmailForSave result, IEnumerable <(string name, byte[] content)> blobs) ToEntity(EmailToSend emailToSend)
        {
            var blobCount = 1 + emailToSend.Attachments.Count(); // To make sliiightly faster
            var blobs     = new List <(string name, byte[] content)>(blobCount);

            string bodyBlobId = null;

            if (!string.IsNullOrWhiteSpace(emailToSend.Body))
            {
                bodyBlobId = Guid.NewGuid().ToString();
                var bodyBlobName    = EmailUtil.EmailBodyBlobName(bodyBlobId);
                var bodyBlobContent = Encoding.UTF8.GetBytes(emailToSend.Body);

                blobs.Add((bodyBlobName, bodyBlobContent));
            }

            var emailForSave = new EmailForSave
            {
                To          = string.Join(';', emailToSend.To ?? new List <string>()),
                Cc          = string.Join(';', emailToSend.Cc ?? new List <string>()),
                Bcc         = string.Join(';', emailToSend.Bcc ?? new List <string>()),
                Subject     = emailToSend.Subject,
                BodyBlobId  = bodyBlobId,
                Id          = emailToSend.EmailId,
                State       = EmailState.Scheduled,
                Attachments = new List <EmailAttachmentForSave>()
            };

            if (emailToSend.Attachments != null)
            {
                foreach (var att in emailToSend.Attachments)
                {
                    // If there is no content, then don't add the attachment
                    var    contentBlobContent = att.Contents;
                    string contentBlobId      = null;

                    if (contentBlobContent != null && contentBlobContent.Length > 0)
                    {
                        contentBlobId = Guid.NewGuid().ToString();
                        var contentBlobName = EmailUtil.EmailAttachmentBlobName(contentBlobId);
                        blobs.Add((contentBlobName, contentBlobContent));
                    }

                    emailForSave.Attachments.Add(new EmailAttachmentForSave
                    {
                        Name          = att.Name,
                        ContentBlobId = contentBlobId
                    });
                }
            }

            return(emailForSave, blobs);
        }
        public ActionResult SubmitMessage(ContactMessage model)
        {
            if (ModelState.IsValid)
            {
                ViewBag.Message = "Message sent!";

                var msg = $"New Contact request:\r\nEmail: {model.Email}\r\nName: {model.Name}\r\nSubject: {model.Subject}\r\nMessage: {model.Message}";
                EmailUtil.Gmail("*****@*****.**", "*****@*****.**", "", "MemeBox2000 Contact", msg);
            }

            return(View("Index", model));
        }
Exemple #12
0
        protected void btnRecovery_Click(object sender, EventArgs e)
        {
            lstErrorMessages.ForeColor = Color.Red;

            var model = loginControl.Model;

            if (String.IsNullOrWhiteSpace(model.LoginName))
            {
                lstErrorMessages.Text = "გთხოვთ შეიყვანეთ მომხმარებლის სახელი";
                //lstErrorMessages.Text = "Incorrect login name";
                pnlRecovery.Visible = ConfigUtil.UserRecoveryEnabled;

                return;
            }

            var dbUser = (from n in HbSession.Query <UM_User>()
                          where n.DateDeleted == null &&
                          n.IsActive == true &&
                          (
                              n.LoginName.ToLower() == model.LoginName.ToLower() ||
                              n.Email.ToLower() == model.LoginName.ToLower()
                          )
                          select n).FirstOrDefault();

            if (dbUser == null || String.IsNullOrWhiteSpace(dbUser.Email))
            {
                lstErrorMessages.Text = "არასწორია ელ.ფოსტის მისამართი";
                //lstErrorMessages.Text = "Invalid email address";
                pnlRecovery.Visible = ConfigUtil.UserRecoveryEnabled;

                return;
            }

            dbUser.UserCode = Convert.ToString(Guid.NewGuid());
            HbSession.SubmitUpdate(dbUser);

            try
            {
                EmailUtil.SendRecoveryEmail(dbUser);
            }
            catch (Exception ex)
            {
                lstErrorMessages.Text = ex.Message;
                return;
            }

            lstErrorMessages.ForeColor = Color.Green;
            lstErrorMessages.Text      = "თქვენ მიიღებთ პაროლის აღდგენის ბმულს ელ.ფოსტაზე";
            //lstErrorMessages.Text = "Please check your email to finish password recovery";
            pnlRecovery.Visible = ConfigUtil.UserRecoveryEnabled;
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dgvApproval.Rows)
            {
                string approval = row.Cells[0].Value.ToString().Trim();

                if (approval == "---")
                {
                    continue;
                }

                string chaseno = row.Cells[1].Value.ToString().Trim();

                string now = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");

                string query = "";

                if (GlobalService.Owner == GlobalService.IPO1st)
                {
                    if (approval == "Approve")
                    {
                        query = string.Format("update TB_FA_APPROVAL set f_status = '{0}', f_ipo1stapp = '{1}', f_ipo1stdate = '{2}'" +
                                              " where f_chaseno = '{3}'", "IPO 2nd Approval", "Approve", now, chaseno);

                        EmailUtil.SendEmail("*****@*****.**", "*****@*****.**", "Fixed Asset Application Approval");
                    }
                    else
                    {
                        query = string.Format("delete from TB_FA_APPROVAL where f_chaseno = '{0}'", chaseno);

                        RejectStatus(chaseno);
                    }
                }
                else
                {
                    if (approval == "Approve")
                    {
                        query = string.Format("update TB_FA_APPROVAL set f_status = '{0}', f_ipo2ndapp = '{1}', f_ipo2nddate = '{2}'" +
                                              " where f_chaseno = '{3}'", "Ringi Approval", "Approve", now, chaseno);
                    }
                    else
                    {
                        query = string.Format("delete from TB_FA_APPROVAL where f_chaseno = '{0}'", chaseno);

                        RejectStatus(chaseno);
                    }
                }

                DataService.GetInstance().ExecuteNonQuery(query);
            }
        }
        public override void Define()
        {
            SalesOrder salesOrder = null;

            //Customer customer = null;

            When()
            .Match <SalesOrder>(() => salesOrder, so => so.OrderProgressTypeId == OrderProgressStatus.CONFIRMED && so.IsBulkOrder);
            Then()
            .Do(ctx => salesOrder.SetOrderProgressTypeId(OrderProgressStatus.PRINTING, "BulkOrderRule"))
            .Do(ctx => EmailUtil.GetInstance().SendEmailToGroup(Groups.OPERATION, "Printing", "Printing"))
            .Do(ctx => new LogHelper().Log(salesOrder.SalesOrderName + " has been processed by BulkOrderRule"))
            .Do(ctx => ctx.Update(salesOrder));
        }
Exemple #15
0
        private bool SendEmail(UserEmailInfo usernameEmail, string verifyCode, string expireTime)
        {
            string content = "Dear " + usernameEmail.UserName + ",<br/> " + "<p>Your Oracle password recovery verification code is "
                             + verifyCode
                             + " ."
                             + " Please note that this recovery code will expire at "
                             + expireTime
                             + "(5 minutes from your reset request).</p><br/><br/>"
                             + "Sierra System";

            EmailUtil.SendEmailWithGoogle(usernameEmail.EmailAddr, content);
            //EmailUtil.SendEmailAsyncWithSendGrid(usernameEmail.EmailAddr, content);
            return(true);
        }
Exemple #16
0
        protected override async Task <EmailResult> ToEntityResult(EmailForQuery entity, CancellationToken cancellation = default)
        {
            string body = null;

            if (IncludeBody && !string.IsNullOrWhiteSpace(entity.BodyBlobId))
            {
                var blobName = EmailUtil.EmailBodyBlobName(entity.BodyBlobId);
                var bytes    = await _blobService.LoadBlobAsync(_behavior.TenantId, blobName, cancellation);

                body = Encoding.UTF8.GetString(bytes);
            }

            return(new EmailResult(entity, body));
        }
Exemple #17
0
        private bool HandleSendEmailToUser(LoginUsers _objUsers)
        {
            EmailUtil emutil    = new EmailUtil();
            bool      isPrimary = false;
            string    Subject   = null;

            if (CurrentCulture == TMSHelper.PrimaryLanguageCode())
            {
                isPrimary = true;
            }
            var EmailBody = emutil.GetBody(_objUsers.UserID, (isPrimary == true ? _objUsers.P_DisplayName : _objUsers.S_DisplayName), isPrimary, ref Subject);

            return(EmailSend.SendMail(_objUsers.Email, null, Subject, EmailBody, false, null, null));
        }
Exemple #18
0
        public NotificationResult Atualizar(Fornecedor entidade)
        {
            var notificationResult = new NotificationResult();

            try
            {
                if (EmailUtil.ValidarEmail(entidade.Email) == false)
                {
                    notificationResult.Add(new NotificationError("Email Inválido!", NotificationErrorType.USER));
                }

                if (CNPJUtil.ValidarCNPJ(entidade.CNPJ) == false)
                {
                    notificationResult.Add(new NotificationError("CNPJ Do Fornecedor Inválido", NotificationErrorType.USER));
                }

                if (string.IsNullOrEmpty(entidade.TelefoneFixo))
                {
                    notificationResult.Add(new NotificationError("Telefone Inválido", NotificationErrorType.USER));
                }

                if (string.IsNullOrEmpty(entidade.Nome))
                {
                    notificationResult.Add(new NotificationError("Nome Do Fornecedor Inválido", NotificationErrorType.USER));
                }

                if (entidade.idFornecedor <= 0)
                {
                    return(notificationResult.Add(new NotificationError("Código do Fornecedor Inválido!")));
                }

                if (string.IsNullOrEmpty(entidade.EnderecoImagem))
                {
                    notificationResult.Add(new NotificationError("URL da Imagem Inválida ou Não Suportada!", NotificationErrorType.USER));
                }

                if (notificationResult.IsValid)
                {
                    _fornecedorRepositorio.Atualizar(entidade);
                    notificationResult.Add("Fornecedor Atualizado com sucesso.");
                }

                return(notificationResult);
            }
            catch (Exception ex)
            {
                return(notificationResult.Add(new NotificationError(ex.Message)));
            }
        }
 public async Task ErrorAsync(string title, Exception ex, string msg, MailMessageEnum mailMessage)
 {
     await Task.Run(() =>
     {
         LogUtil.Error(msg, ex);
         if (mailMessage == MailMessageEnum.Err || mailMessage == MailMessageEnum.All)
         {
             MailEntity mail  = new MailEntity();
             mail.MailSubject = $"任务调度-{title}【异常】消息";
             mail.SendText    = msg;
             mail.SendHtml    = null;
             EmailUtil.SendMail(mail);
         }
     });
 }
Exemple #20
0
        public bool ChangeRFStatusToRejectedById(RequisitionForm rf, Employee deptHead, string comment)
        {
            using (IDbContextTransaction transcat = db.Database.BeginTransaction())
            {
                try
                {
                    //Find Employee
                    Employee _emp = db.Employees.Find(deptHead.Id);

                    //Check for comment if reject
                    if (comment == null || comment == "")
                    {
                        throw new Exception("There is no reply");
                    }

                    //Find the RF
                    RequisitionForm _rf = db.RequisitionForms.Find(rf.Id);

                    _rf.RFStatus       = RFStatus.Rejected;
                    _rf.RFHeadReply    = comment;
                    _rf.RFApprovalDate = DateTime.Now;
                    _rf.RFApprovalBy   = _emp;
                    db.RequisitionForms.Update(_rf);

                    db.SaveChanges();
                    transcat.Commit();

                    var message = new MimeMessage();
                    message.From.Add(new MailboxAddress("IMS System", "*****@*****.**"));
                    message.To.Add(new MailboxAddress(_rf.Employee.Firstname + " " + _rf.Employee.Lastname, _rf.Employee.Email));
                    message.Subject = "[ " + _rf.RFCode + " ] Status: Rejected";
                    message.Body    = new TextPart("plain")
                    {
                        Text = "[ " + _rf.RFCode + " ]: Approved" +
                               "\n Department Head Comments: " + _rf.RFHeadReply
                    };
                    EmailUtil eUtil = new EmailUtil();
                    eUtil.SendEmail(message);

                    return(true);
                }
                catch
                {
                    transcat.Rollback();
                    return(false);
                }
            }
        }
        public HttpResponseMessage Register([FromBody] JObject account)
        {
            try
            {
                var jsonParams = HttpUtil.Deserialize(account);

                string id    = jsonParams.id;
                string pwd   = ConfigurationManager.AppSettings["DefaultUserPasswd"];
                string name  = jsonParams.name;
                string email = jsonParams.email;

                pwd = HttpUtil.Encrypt(pwd, System.Text.Encoding.UTF8);

                User user = UserDao.GetUserById(id.ToLower());
                if (user == null)
                {
                    return(new Response(1001, "用户不存在").Convert());
                }
                if (user.is_accept != null)
                {
                    return(new Response(1001, "该用户已经激活").Convert());
                }
                user.passwd    = pwd;
                user.name      = name;
                user.email     = jsonParams.email;
                user.is_accept = false;
                UserDao.ChangeInfo(user);

                if (user.email != null)
                {
                    Dictionary <string, string> retData = new Dictionary <string, string>();
                    string uuid = System.Guid.NewGuid().ToString();
                    redis.Set(uuid, id, 60);
                    retData.Add("id", id);
                    retData.Add("token", uuid);
                    string href = ConfigurationManager.AppSettings["webBase"] + "/security/activateAccount" + "?id=" + user.id + "&token=" + uuid;
                    string res  = EmailUtil.SendEmail("账户激活", "请点击以下网址来激活用户", user.id, 1, href);
                    //todo: 发送激活邮件
                    return(new Response(1001, "发送激活邮件", retData).Convert());
                }
                return(new Response(1001, "成功激活").Convert());
            }
            catch (Exception e)
            {
                ErrorLogUtil.WriteLogToFile(e, Request);
                return(new Response(4001).Convert());
            }
        }
        public override void OnException(ExceptionContext filterContext)
        {
            filterContext.ExceptionHandled = true;
            EmailUtil emailUtil = new EmailUtil();

            try
            {
                emailUtil.SendEmail(filterContext.Exception, "Error Handler");
            }
            catch (Exception) { }

            filterContext.Result = new ViewResult()
            {
                ViewName = "Error"
            };
        }
 public async Task InformationAsync(string title, string msg, MailMessageEnum mailMessage)
 {
     await Task.Run(() =>
     {
         LogUtil.Info(msg);
         if (mailMessage == MailMessageEnum.All)
         {
             //发邮件
             MailEntity mail  = new MailEntity();
             mail.MailSubject = $"任务调度-{title}消息";
             mail.SendText    = msg;
             mail.SendHtml    = null;
             EmailUtil.SendMail(mail);
         }
     });
 }
        public IActionResult SendVerificationCode([FromBody] EmailDTO emailDTO)
        {
            var result = new ResultModel(1);

            return(Wrapper(ref result, () => {
                var random = new Random();
                var code = random.Next(1000, 10000);
                var key = $"Register:code:Email:{emailDTO.Email}";
                _csRedisBase.set(key, code.ToString(), 60);
                var content = $"您的验证码是 :{code},有效期60秒,请妥善保管";
                EmailUtil.Send(new List <string>()
                {
                    emailDTO.Email,
                }, "HeyTom注册验证码", content, "HeyTom");
            }, true));
        }
Exemple #25
0
        async static Task <bool> SendEmailTask(EmailUtil email)
        {
            bool bRtnVal = false;

            try
            {
                email.Subject = String.Format("PortFolio Excel for - '{0}'", DateTime.Today.Date.ToString("MM-dd-yyyy"));
                email.Body    = "Please find attached portfolio excel sheet for today.";
                bRtnVal       = EmailUtil.Instance.SendEmail(email);
            }
            catch (Exception ex)
            {
                ApplicationLog.Instance.WriteException(ex);
            }
            return(bRtnVal);
        }
Exemple #26
0
        public async Task <IActionResult> MailContact(Contact model)
        {
            var htmlToConvert = await RenderViewAsync("MailContact", model, true);

            var msg = EmailUtil.sendNotificationEmail(_smtp, _conf.SupportEmail, "ติดต่อจากคุณ" + model.Name, htmlToConvert.ToString());

            if (string.IsNullOrEmpty(msg))
            {
                ViewData["Message"] = "ส่งข้อมูลสำเร็จ";
            }
            else
            {
                ViewData["ErrorMessage"] = "ไม่สามารถส่งข้อมูลได้ กรุณาติดต่อไปยังผู้ดูแลระบบ";
            }
            return(Json(new { Msg = msg }));
        }
Exemple #27
0
        public NotificationResult Salvar(Vendedor entidade)
        {
            var notificationResult = new NotificationResult();

            try
            {
                if (EmailUtil.ValidarEmail(entidade.Email) == false)
                {
                    notificationResult.Add(new NotificationError("Email Inválido!", NotificationErrorType.USER));
                }

                if (string.IsNullOrEmpty(entidade.TelefoneFixo))
                {
                    notificationResult.Add(new NotificationError("Telefone Inválido", NotificationErrorType.USER));
                }

                if (string.IsNullOrEmpty(entidade.Nome))
                {
                    notificationResult.Add(new NotificationError("Nome do Vendedor Inválido!"));
                }

                if (CNPJUtil.ValidarCNPJ(entidade.CNPJ) == false)
                {
                    notificationResult.Add(new NotificationError("CNPJ Do Vendedor Inválido", NotificationErrorType.USER));
                }

                if (string.IsNullOrEmpty(entidade.EnderecoImagem))
                {
                    notificationResult.Add(new NotificationError("URL da Imagem Inválida ou Não Suportada!", NotificationErrorType.USER));
                }

                if (notificationResult.IsValid)
                {
                    _vendedorRepositorio.Adicionar(entidade);
                    notificationResult.Add("Vendedor Cadastrado com sucesso.");
                }

                notificationResult.Result = entidade;

                return(notificationResult);
            }
            catch (Exception ex)
            {
                return(notificationResult.Add(new NotificationError(ex.Message)));
            }
        }
        /// <summary>
        /// Helper function
        /// </summary>
        public static async Task <IEnumerable <EmailToSend> > FromEntities(int tenantId, IEnumerable <EmailForSave> emails, IBlobService blobService, CancellationToken cancellation)
        {
            var result = new List <EmailToSend>();

            foreach (var emailForSave in emails)
            {
                string body = null;
                if (!string.IsNullOrWhiteSpace(emailForSave.BodyBlobId))
                {
                    var bodyBlobName = EmailUtil.EmailBodyBlobName(emailForSave.BodyBlobId);
                    var bodyContent  = bodyBlobName == null ? null : await blobService.LoadBlobAsync(tenantId, bodyBlobName, cancellation);

                    body = Encoding.UTF8.GetString(bodyContent);
                }

                var attachments = new List <EmailAttachmentToSend>();
                result.Add(new EmailToSend()
                {
                    To          = emailForSave.To?.Split(';'),
                    Cc          = emailForSave.Cc?.Split(';'),
                    Bcc         = emailForSave.Bcc?.Split(';'),
                    EmailId     = emailForSave.Id,
                    Subject     = emailForSave.Subject,
                    Body        = body,
                    Attachments = attachments,
                    TenantId    = tenantId
                });

                foreach (var att in emailForSave?.Attachments ?? new List <EmailAttachmentForSave>())
                {
                    if (!string.IsNullOrWhiteSpace(att.ContentBlobId))
                    {
                        var attBlobName = EmailUtil.EmailAttachmentBlobName(att.ContentBlobId);
                        var attContent  = await blobService.LoadBlobAsync(tenantId, attBlobName, cancellation);

                        attachments.Add(new EmailAttachmentToSend
                        {
                            Name     = att.Name,
                            Contents = attContent
                        });
                    }
                }
            }

            return(result);
        }
        private void GetEmailListFromDatabase()
        {
            try
            {
                ApplicationLog.Instance.WriteDebug("Calling database to get list to send emails");
                client        = new DatabaseClass();
                lstCreateUser = new List <string>();
                lstQuotes     = client.GetRequestsToSendEmail(null);

                foreach (GetQuoteInfo obj in lstQuotes)
                {
                    if (obj.NeedToCreateUser)
                    {
                        if (!lstCreateUser.Any(x => x.Equals(obj.Email)))
                        {
                            lstCreateUser.Add(obj.Email);
                        }
                    }

                    ApplicationLog.Instance.WriteInfo(String.Format("Sending request confiramtion Email to {0}", obj.Email));
                    EmailUtil utilObject = new EmailUtil()
                    {
                        ToEmail = obj.Email,
                        ToName  = String.Format("{0} {1}", obj.FirstName, obj.LastName),
                        Subject = String.Format("Request confirmation for {0} service from HappyHut!!!", obj.ServiceName),
                    };
                    //TODO:: Add Body Template
                    bool emailSent = EmailUtil.Instance.SendEmail(utilObject);
                    if (emailSent)
                    {
                        ApplicationLog.Instance.WriteInfo(String.Format("Request confirmation Email sent to {0} for service request id {1}", obj.Email, obj.Id));
                        obj.IsEmailSent = true;
                        obj.EmailSentDt = DateTime.UtcNow;
                    }
                    else
                    {
                        ApplicationLog.Instance.WriteWarning(String.Format("Request email not sent to {0} for service request id '{1}'", obj.Email, obj.Id));
                        //TODO:: Send email to [email protected] && [email protected]
                    }
                }
            }
            catch (Exception ex)
            {
                ApplicationLog.Instance.WriteException(ex);
            }
        }
Exemple #30
0
 public void SendMailUserInfo(string userName, string pass, string toEmail)
 {
     Task.Run(async() =>
     {
         var email = new EmailUtil();
         await email.SendMail("", "Gửi thông tin tài khoản trên hệ thống +++SYSTEM+++", toEmail,
                              new string[] { },
                              "Xin chào " + userName + " <br/><br/>" +
                              "Thông tin tài khoản trên hệ thống của bạn:<br/>" +
                              "Tên tài khoản:" + userName + "<br/>" +
                              "Mật khẩu đăng nhập:" + pass + "<br/>" +
                              "Để đảm bảo an toàn thông tin, bạn vui lòng đăng nhập và đổi mật khẩu để tiếp tục sử dụng dịch vụ. " + "<br /><br />" +
                              "URL: <a href='#'>http://#.vn</a>"
                              + "<br /><br />" +
                              "Trân trọng!");
     });
 }