Example #1
0
        /// <summary>
        /// Send the email directly
        /// </summary>
        /// <param name="emailAccount"></param>
        /// <param name="emailModel"></param>
        /// <returns></returns>
        public ResponseModel SendEmailDirectly(EmailAccount emailAccount, EmailModel emailModel)
        {
            var mailSetting = new EmailSetting
            {
                Host      = emailAccount.Host,
                Port      = emailAccount.Port,
                Timeout   = emailAccount.TimeOut,
                EnableSsl = emailAccount.EnableSsl,
                User      = emailAccount.Username,
                Password  = emailAccount.Password
            };

            var mailUtilities = new MailUtilities(mailSetting);

            try
            {
                mailUtilities.SendEmail(emailModel);
                return(new ResponseModel
                {
                    Success = true,
                    Message = T("EmailAccount_Message_SendEmailDirectlySuccessfully")
                });
            }
            catch (Exception exception)
            {
                return(new ResponseModel
                {
                    Success = false,
                    Message = T("EmailAccount_Message_SendEmailDirectlyFailure"),
                    DetailMessage = exception.Message
                });
            }
        }
        public HttpResponseMessage Submit(Contact PostData)
        {
            // Save our model
            using (var db = new MessageContext())
            {
                db.Messages.Add(new SavedMessage
                {
                    FirstName = PostData.FirstName,
                    LastName  = PostData.LastName,
                    Email     = PostData.Email,
                    Phone     = PostData.Phone,
                    Subject   = PostData.Subject,
                    Body      = PostData.Message
                });
                db.SaveChanges();
            }

            // Send our email
            MailUtilities.LoginMail("*****@*****.**", "J!qHvpQ~j8`;<MuF", "ContactBot");

            StringBuilder MailBuilder = new StringBuilder();

            MailBuilder.Append($"Name: {PostData.FirstName} {PostData.LastName}<br>");
            MailBuilder.Append($"Email: {PostData.Email}<br>");
            MailBuilder.Append($"Telephone number:{PostData.Phone}<br>");
            MailBuilder.Append($"onderwerp: {PostData.Subject}<br>");
            MailBuilder.Append($"<pre>{PostData.Message}</pre>");

            MailUtilities.SendMail("*****@*****.**", $"Message from {PostData.FirstName} {PostData.LastName}", MailBuilder.ToString());

            var response = new HttpResponseMessage(HttpStatusCode.Created);

            Response.Redirect("/Contact/thankyou");
            return(response);
        }
Example #3
0
            private async Task <int> OnExecute(IConsole console, DatabaseContext database, ConfirmationMailService mailingService)
            {
                if (!MailUtilities.IsValidAddress(AccountName))
                {
                    console.Error.WriteLine("Please use a valid email address!");
                    return(1);
                }

                console.Out.WriteLine("WARNING: Argon2 hash is currently not supported!");

                (var account, var confirmation, bool success) = await database.AddAccount(AccountName, Array.Empty <byte>()).ConfigureAwait(false);

                if (success)
                {
                    console.Out.WriteLine($"Created account with ID {account.AccountId}");
                    console.Out.WriteLine($"Visit {mailingService.GetConfirmationUrl(confirmation.Token)} to confirm the mail address");

                    if (SendMail)
                    {
                        console.Out.WriteLine("Sending confirmation mail...");
                        await mailingService.SendMailAsync(AccountName, confirmation.Token).ConfigureAwait(false);
                    }
                    return(0);
                }
                else
                {
                    console.Error.WriteLine($"The AccountName {AccountName} already exists!");
                    return(1);
                }
            }
Example #4
0
 public IEnumerable <IMailReference> GetAllMailForDomain(string domain)
 {
     return(References.Where(
                r => string.Equals(
                    MailUtilities.GetDomainFromMailbox(r.Recipients[0]),
                    domain,
                    StringComparison.OrdinalIgnoreCase)));
 }
        public static void Execute()
        {
            var manager = DocumentManagerProvider.Get() as SharepointDocumentManager;

            if (manager != null && manager.SharepointUseInternalTagFolder)
            {
                using (var db = FactoryDbContext.Create())
                {
                    var sql = @"WITH Folders (Id, Name, FullPath, EntityId, ReferenceId, InternalTag, IsProcessed, Level)
                                AS
                                (
                                    SELECT F.Id, F.Name, F.FullPath, EF.EntityId, EF.ReferenceId, CAST(InternalId AS NVARCHAR(MAX)) AS InternalTag, EF.IsProcessed, 0 AS Level
                                    FROM Folder F
                                    INNER JOIN EntityFolder EF ON F.Id = EF.Id
                                    WHERE F.ParentId IS NULL
                                    UNION ALL
                                    SELECT F.Id, F.Name, F.FullPath, EF.EntityId, EF.ReferenceId, CAST(F.InternalId AS NVARCHAR(MAX)) AS InternalTag, EF.IsProcessed, P.Level + 1
                                    FROM Folder F
                                    INNER JOIN Folders P ON F.ParentId = P.Id
                                    INNER JOIN EntityFolder EF ON F.Id = EF.Id
                                )
                                SELECT Id, Name, FullPath, EntityId, ReferenceId, InternalTag AS Tag, IsProcessed
                                FROM Folders
                                ORDER BY EntityId, ReferenceId, Level DESC;";

                    var folders = db.Database.SqlQuery <FolderImport>(sql).ToList().Where(x => !x.IsProcessed).ToList();
                    var errors  = new List <string>();
                    var i       = 0;
                    var count   = folders.Count;

                    folders.ForEach(folder =>
                    {
                        try
                        {
                            manager.RenameFolder(folder.EntityId, folder.ReferenceId, folder.Tag, folder.Name, folder.FullPath.HasValue() ? folder.FullPath : folder.Name, db);
                            db.Database.ExecuteSqlCommand("UPDATE EntityFolder SET IsProcessed = 1 WHERE Id = {0}", folder.Id);
                            i++;
                        }
                        catch (Exception ex)
                        {
                            errors.Add(string.Format("Id: {0}; Name: {1}; FullPath: {2}", folder.Id, folder.Name, folder.FullPath) + Environment.NewLine + ex.Message);

                            Console.WriteLine(ex.Message);
                        }
                    });

                    if (errors.HasValue())
                    {
                        var message = errors.JoinBy(Environment.NewLine);

                        MailUtilities.SendMail(new List <string>()
                        {
                            ConfigurationManager.AppSettings["AlertRecipient"]
                        }, "ERROR Rename Folder SharePoint", message);
                    }
                }
            }
        }
Example #6
0
        public IHttpActionResult PostRelicense([FromBody] RelicenseRequest request)
        {
            logger.Debug("PostRelicense(ReliscenseRequest) entered ...");

            try
            {
                // Check if already listed as a device.
                MobileDevice device = db.MobileDevices.Include("Company").FirstOrDefault(d => d.SerialNo == request.SerialNo);

                if (device == null)
                {
                    logger.InfoFormat("Device with Serial # : {0} not registered", request.SerialNo);

                    return(Ok(new LicenseResponse()
                    {
                        Error = "Device not registered",
                        Result = (int)RelicenceResultCode.NotRegistered
                    }));
                }

#if ENABLE_EMAIL
                // Send email ...
                MailUtilities.SendEmail(db, device, "relicensed");
#endif

                // Return configuration.
                return(Ok(new LicenseResponse()
                {
                    Result = (int)RelicenceResultCode.Success,
                    DeviceNo = device.MobileDeviceId,
                    Url = device.Company.ColossusMobileUrl,
                    ConsignorName = device.Company.ConsignorName,
                    ConsignorAdd1 = device.Company.ConsignorAdd1,
                    ConsignorAdd2 = device.Company.ConsignorAdd2,
                    ConsignorAdd3 = device.Company.ConsignorAdd3,
                    Error = string.Empty
                }));
            }
            catch (Exception ex)
            {
                logger.Error("Error relicensing device", ex);

                return(Ok(new LicenseResponse()
                {
                    Result = (int)RelicenceResultCode.Unknown,
                    Error = "Unknown Error",
                    Url = string.Empty
                }));
            }
            finally
            {
                logger.Debug("PostRelicense(ReliscenseRequest) exited");
            }
        }
        public IHttpActionResult Register(RegisterModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var account = Service.CreateCredentials(model.UserName, model.Password, model.Email, model.LegionId,
                                                    model.FirstName, model.LastName);
            var verificationCode = Service.CreateVerificationCode(account);

            MailUtilities.SendEmail(model.Email, verificationCode, GetVerificationPath());
            return(Ok("Verification Email Sent"));
        }
 /// <summary>
 /// SendKeyByEmail method implementation
 /// </summary>
 public static void SendKeyByEmail(string email, string upn, string key)
 {
     CultureInfo info = null;
     try
     {
         info = CultureInfo.CurrentUICulture;
     }
     catch
     {
         info = new CultureInfo(ManagementService.Config.DefaultCountryCode);
     }
     MailUtilities.SendKeyByEmail(email, upn, key, ManagementService.Config.MailProvider, ManagementService.Config, info);
 }
        private async Task <string> ApplyEnqueuedModificationsAsync(MBoxWriteReference mbox)
        {
            var targetMailbox = mbox.Mailbox;
            var name          = MailUtilities.GetNameFromMailbox(targetMailbox);
            var rootName      = StripExtension(name);
            var currentPath   = mbox.TempPath;

            if (name != rootName)
            {
                currentPath = await AugmentReferencesAsync(currentPath, targetMailbox);
            }

            return(currentPath);
        }
        private void button6_Click(object sender, EventArgs e)
        {
            Mail mail = new Mail();

            mail.To      = "*****@*****.**";
            mail.From    = "*****@*****.**";
            mail.Subject = "teste";
            mail.Body    = "teste de envio de email sobre a SSL";

            //KhronusReturn ret = MailUtilities.send("email-ssl.com.br", "*****@*****.**", "k070213r", 587, true, mail); //funciona
            KhronusReturn ret = MailUtilities.send("email-ssl.com.br", "*****@*****.**", "k070213r", 587, false, mail);

            MessageBox.Show(ret.Message);
        }
        private void button7_Click(object sender, EventArgs e)
        {
            Mail mail = new Mail();

            mail.From = txtDe.Text;
            mail.To   = txtPara.Text;
            //mail.Bcc = "*****@*****.**";
            mail.Subject = txtAssunto.Text;
            mail.Body    = txtCorpo.Text;

            //mail.AttachmentList.Add(@"D:\desenvolvimento_old\analise de sistemas\nfe\documentacao\NT_2016_002_v1.51.pdf");

            //KhronusReturn ret = MailUtilities.send("smtp.gmail.com", "*****@*****.**", "fev@030277@", 587, true, mail);
            KhronusReturn ret = MailUtilities.send(txtSmtp.Text, txtUsuario.Text, txtSenha.Text, NumberUtilities.parseInt(txtPorta.Text), chkSsl.Checked, mail);

            MessageBox.Show(ret.Status + " " + ret.Message);
        }
Example #12
0
        /**
         * @author Anthony Scheeres
         */
        private void validateAUsersEmailUsingAValidationEmaill(string toEmailAddress, string username, string token)
        {
            MailUtilities mailUtilities = new MailUtilities();
            string        protocol      = ProtocolModel.http.ToString();
            string        subject       = "Please, verifiëer uw email";
            //link to verify email to change the is_email_verified boolean record
            RestApiModel server = DataModel.getConfigModel().server;

            if (server.UseHttps)
            {
                protocol = ProtocolModel.https.ToString();
            }
            string body = "http://" + server.hostName + ":" + server.portNumber + "/api/User/validateToken?token=" + token;


            mailUtilities.sendEmailToAdressWithABodyAndSubjectUsingCredentialsInDataModel(toEmailAddress, username, subject, body);
        }
        private static async Task AssertMessage(
            string inputMessage,
            string expectedMessage,
            string inputSender,
            string expectedSender)
        {
            expectedMessage = expectedMessage ?? inputMessage;
            expectedSender  = expectedSender ?? inputSender;
            Stream newStream = null;

            try
            {
                var stream = new MemoryStream(Encoding.ASCII.GetBytes(
                                                  inputMessage));
                var headers = await MailUtilities.ParseHeadersAsync(stream);

                string newSender;

                (newStream, newSender) =
                    await MailDispatcher.ReplaceSenderAsync(headers, stream, inputSender, CancellationToken.None);

                if (inputMessage == expectedMessage && inputSender == expectedSender)
                {
                    Assert.Same(stream, newStream);
                }
                else
                {
                    Assert.NotSame(stream, newStream);
                    Assert.Throws <ObjectDisposedException>(() => stream.ReadByte());
                }

                Assert.Equal(0, newStream.Position);
                Assert.Equal(expectedSender, newSender);
                using (var reader = new StreamReader(newStream, Encoding.ASCII, false, 1024, true))
                {
                    Assert.Equal(expectedMessage, await reader.ReadToEndAsync());
                }
            }
            finally
            {
                newStream.Dispose();
            }
        }
        private string GetFolderPath(string mailbox, string folder, string status)
        {
            // Turn foo/bar into .foo.bar, because that's what maildir says
            string folderPart = string.Join(
                "",
                folder.Split(FolderSeparator, StringSplitOptions.RemoveEmptyEntries)
                .Select(s => "." + s)
                .ToArray()
                );

            var nameFromMailbox = MailUtilities.GetNameFromMailbox(mailbox);


            return(Path.Combine(
                       _settings.MailLocalPath,
                       MailUtilities.GetDomainFromMailbox(mailbox),
                       StripExtension(nameFromMailbox),
                       folderPart,
                       status));
        }
Example #15
0
        private async void MailWork_Click(object sender, RoutedEventArgs e)
        {
            string message;


            foreach (string mail in publishersAssignments.Keys)
            {
                DataTable     territorries       = (DataTable)publishersAssignments[mail];
                List <string> territoriesStrings = new List <string>();
                foreach (DataRow row in territorries.Rows)
                {
                    territoriesStrings.Add(row[0].ToString());
                }
                MailUtilities mailer = new MailUtilities();
                mailer.sendTerritoryWorkRequestMail(mail, territoriesStrings);
            }

            message = "Courriels (Travail) envoyés aux proclamateurs";
            MessageBoxResult result = await Task.Run(() => MessageBox.Show(message, "INFO", MessageBoxButton.OK, MessageBoxImage.Information));
        }
Example #16
0
        private async void OkButton_Click(object sender, RoutedEventArgs e)
        {
            string message = textArea.Text.Trim();
            bool   success;


            foreach (string mail in publishersAssignments.Keys)
            {
                DataTable     territorries       = (DataTable)publishersAssignments[mail];
                List <string> territoriesStrings = new List <string>();
                foreach (DataRow row in territorries.Rows)
                {
                    territoriesStrings.Add(row[0].ToString());
                }
                MailUtilities mailer = new MailUtilities();
                success = mailer.sendFreeTextMail(mail, territoriesStrings, message);
            }

            message = "Courriels envoyés aux proclamateurs";
            MessageBoxResult result = await Task.Run(() => MessageBox.Show(message, "INFO", MessageBoxButton.OK, MessageBoxImage.Information));

            this.Close();
        }
        /// <summary>
        /// Parse the email from template and model
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="template"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public EmailTemplateResponseModel ParseEmail <TModel>(EmailTemplate template, TModel model)
        {
            if (template == null)
            {
                return(null);
            }

            var subjectCacheName = template.Type.GetEnumName().GetTemplateCacheName(template.Subject);
            var bodyCacheName    = template.Type.GetEnumName().GetTemplateCacheName(template.Body);
            var response         = new EmailTemplateResponseModel
            {
                From     = template.From,
                FromName = template.FromName,
                CC       = MailUtilities.FormatEmailList(template.CC),
                CCList   = MailUtilities.ParseEmailList(template.CC),
                BCC      = MailUtilities.FormatEmailList(template.BCC),
                BCCList  = MailUtilities.ParseEmailList(template.BCC),
                Subject  = EzRazorEngineHelper.CompileAndRun(template.Subject, model, subjectCacheName),
                Body     = EzRazorEngineHelper.CompileAndRun(template.Body, model, bodyCacheName)
            };

            return(response);
        }
Example #18
0
 public void NoAt()
 {
     Assert.Null(MailUtilities.GetMailboxFromAddress("box_example.com"));
 }
Example #19
0
 public void SimpleWithDisplayName()
 {
     Assert.Equal("*****@*****.**", MailUtilities.GetMailboxFromAddress("Target Human <*****@*****.**>"));
 }
Example #20
0
 public void SimpleMail()
 {
     Assert.Equal("*****@*****.**", MailUtilities.GetMailboxFromAddress("*****@*****.**"));
 }
Example #21
0
 public void QuotedCrainess()
 {
     Assert.Equal(
         "*****@*****.**",
         MailUtilities.GetMailboxFromAddress("\"Target Human <*****@*****.**>\" <*****@*****.**>"));
 }
Example #22
0
        /// <summary>
        /// DoImport() method implmentation
        /// </summary>
        public override bool DoImport()
        {
            char          sep      = Path.DirectorySeparatorChar;
            string        filename = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + sep + "MFA" + sep + "adimport-" + DateTime.Now.ToFileTime().ToString() + ".log";
            TraceListener listen   = InitializeTrace(filename);

            try
            {
                ADDSHost adht = Config.Hosts.ActiveDirectoryHost;
                if (string.IsNullOrEmpty(DomainName))
                {
                    DomainName = adht.DomainName;
                }
                if (string.IsNullOrEmpty(UserName))
                {
                    UserName = adht.Account;
                }
                if (string.IsNullOrEmpty(Password))
                {
                    Password = adht.Password;
                }

                DataRepositoryService client = null;
                switch (Config.StoreMode)
                {
                case DataRepositoryKind.ADDS:
                    client = new ADDSDataRepositoryService(Config.Hosts.ActiveDirectoryHost, Config.DeliveryWindow);
                    break;

                case DataRepositoryKind.SQL:
                    client = new SQLDataRepositoryService(Config.Hosts.SQLServerHost, Config.DeliveryWindow);
                    break;

                case DataRepositoryKind.Custom:
                    client = CustomDataRepositoryActivator.CreateInstance(Config.Hosts.CustomStoreHost, Config.DeliveryWindow);
                    break;
                }

                Trace.WriteLine("");
                Trace.WriteLine(string.Format("Importing for AD : {0}", LDAPPath));
                Trace.Indent();
                Trace.WriteLine("Querying users from AD");
                MFAUserList lst = client.ImportMFAUsers(DomainName, UserName, Password, LDAPPath, CreatedSince, ModifiedSince, MailAttribute, PhoneAttribute, Method, Config.Hosts.ActiveDirectoryHost.UseSSL, DisableAll);
                Trace.WriteLine(string.Format("Querying return {0} users from AD", lst.Count.ToString()));

                DataRepositoryService client2 = null;
                switch (Config.StoreMode)
                {
                case DataRepositoryKind.ADDS:
                    Trace.WriteLine("");
                    Trace.WriteLine("Importing ADDS Mode");
                    Trace.Indent();
                    client2 = new ADDSDataRepositoryService(Config.Hosts.ActiveDirectoryHost, Config.DeliveryWindow);
                    break;

                case DataRepositoryKind.SQL:
                    Trace.WriteLine("");
                    Trace.WriteLine("Importing SQL Mode");
                    Trace.Indent();
                    client2 = new SQLDataRepositoryService(Config.Hosts.SQLServerHost, Config.DeliveryWindow);
                    break;

                case DataRepositoryKind.Custom:

                    Trace.WriteLine("");
                    Trace.WriteLine("Importing Custom Store Mode");
                    Trace.Indent();
                    client2 = CustomDataRepositoryActivator.CreateInstance(Config.Hosts.CustomStoreHost, Config.DeliveryWindow);
                    break;
                }
                client2.OnKeyDataEvent += KeyDataEvent;
                foreach (MFAUser reg in lst)
                {
                    Trace.TraceInformation(string.Format("Importing user {0} from AD", reg.UPN));
                    try
                    {
                        MFAUser ext = client2.GetMFAUser(reg.UPN);
                        if (ext == null)
                        {
                            reg.PIN = Config.DefaultPin;
                            client2.AddMFAUser(reg, ForceNewKey, false);
                            Trace.TraceInformation(string.Format("User {0} Imported in MFA", reg.UPN));
                            if (!string.IsNullOrEmpty(reg.MailAddress))
                            {
                                if (SendEmail)
                                {
                                    string      qrcode = KeysManager.EncodedKey(reg.UPN);
                                    CultureInfo info   = null;
                                    try
                                    {
                                        info = CultureInfo.CurrentUICulture;
                                    }
                                    catch
                                    {
                                        info = new CultureInfo(Config.DefaultCountryCode);
                                    }
                                    MailUtilities.SendKeyByEmail(reg.MailAddress, reg.UPN, qrcode, Config.MailProvider, Config, info);
                                    Trace.TraceInformation(string.Format("Sending Sensitive mail for User {0} Imported in MFA", reg.UPN));
                                }
                            }
                            RecordsCount++;
                        }
                    }
                    catch (Exception ex)
                    {
                        ErrorsCount++;
                        Trace.TraceError("Error importing Record N° {0} \r\r {1}", (RecordsCount + 1).ToString(), ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError(string.Format("Error importing from AD \r\r {0}", ex.Message));
                return(false);
            }
            finally
            {
                Trace.Unindent();
                FinalizeTrace(listen);
            }
            return(true);
        }
Example #23
0
        public IHttpActionResult PostLicense([FromBody] LicenseRequest request)
        {
            logger.Debug("PostLicense(LicenseRequest) entered ...");

            try
            {
                // Validate Company PIN format, if invalid return an error.
                if (request.CompanyPIN.Length != 8)
                {
                    logger.InfoFormat("PIN is incorrect length : {0}, should be 8 characters", request.CompanyPIN.Length);

                    return(Ok(new LicenseResponse()
                    {
                        Error = "PIN must be 8 digits",
                        Result = (int)LicenceResultCode.PinIncorrectLength
                    }));
                }

                // Attempt to find Company from the PIN.
                Company company = db.Companies.FirstOrDefault(c => c.Pin == request.CompanyPIN);

                // If not found return an error.
                if (company == null)
                {
                    logger.InfoFormat("Failed to find Company with PIN : {0}", request.CompanyPIN);

                    return(Ok(new LicenseResponse()
                    {
                        Error = "PIN is invalid",
                        Result = (int)LicenceResultCode.PinNotFound
                    }));
                }

                // Check if already listed as a device.
                MobileDevice device = db.MobileDevices.FirstOrDefault(d => d.SerialNo == request.SerialNo);

                // If the device exists return error showing already registered
                if (device != null)
                {
                    logger.InfoFormat("Device with Serial # : {0} already registered", request.SerialNo);

                    return(Ok(new LicenseResponse()
                    {
                        Error = "Device already registered",
                        Result = (int)LicenceResultCode.DeviceAlreadyRegistered
                    }));
                }

                // Create new device.
                device = new MobileDevice()
                {
                    Company   = company,
                    SerialNo  = request.SerialNo,
                    Created   = DateTime.Now,
                    CompanyId = company.CompanyId,
                };

                // Add to the collection of Mobile Devices ...
                device = db.MobileDevices.Add(device);
                db.SaveChanges();

                logger.DebugFormat("New device with Id : {0} created", device.MobileDeviceId);

                // Send email ...
                int numberOfDevices = db.MobileDevices.Count(d => d.CompanyId == device.MobileDeviceId);
                MailUtilities.SendEmail(numberOfDevices, device, "licensed");

                // Return configuration.
                return(Ok(new LicenseResponse()
                {
                    Result = (int)LicenceResultCode.Success,
                    DeviceNo = device.MobileDeviceId,
                    Url = device.Company.ColossusMobileUrl,
                    ConsignorName = device.Company.ConsignorName,
                    ConsignorAdd1 = device.Company.ConsignorAdd1,
                    ConsignorAdd2 = device.Company.ConsignorAdd2,
                    ConsignorAdd3 = device.Company.ConsignorAdd3,
                    Error = string.Empty
                }));
            }
            catch (Exception ex)
            {
                logger.Error("Error licensing device", ex);

                return(Ok(new LicenseResponse()
                {
                    Result = (int)LicenceResultCode.Unknown,
                    Error = "Unknown Error",
                    Url = string.Empty
                }));
            }
            finally
            {
                logger.Debug("PostLicense(LicenseRequest) exited");
            }
        }
 /// <summary>
 /// SendKeyByEmail method implementation
 /// </summary>
 public static void SendKeyByEmail(string email, string upn, string key)
 {
     MailUtilities.SendKeyByEmail(email, upn, key, ManagementService.Config.MailProvider, ManagementService.Config, CultureInfo.CurrentUICulture);
 }
        protected void CompletaOrdine_OnClick(object sender, EventArgs e)
        {
            try
            {
                string        nome              = txtNome.Text;
                string        cognome           = txtCognome.Text;
                string        email             = txtEmail.Text;
                string        numeroTel         = txtTelefono.Text;
                string        metodoDiPagamento = ddlMetodoDiPagamento.SelectedItem.Text;
                string        tot            = hfPrezzo.Value;
                string        nazione        = txtNazione.Text;
                string        via            = txtVia.Text;
                string        cap            = txtCap.Text;
                string        civico         = txtCivico.Text;
                string        citta          = txtCitta.Text;
                string        ragSoc         = txtRagSoc.Text;
                bool          isFatturazione = !string.IsNullOrEmpty(ragSoc);
                string        pIva           = txtIva.Text;
                string        fVia           = txtSVia.Text;
                string        sede           = txtSede.Text;
                string        codiceFiscale  = txtCF.Text;
                List <string> ordini         = new List <string>();
                if (Page.IsValid)
                {
                    hfOrdine.Value.Split(';').ToList().ForEach(o =>
                    {
                        if (o.Contains("Prezzo"))
                        {
                            var ord =
                                o.Split(new[] { "Prezzo" }, StringSplitOptions.RemoveEmptyEntries)[0].Replace(
                                    "Quantità:", String.Empty);

                            ordini.Add(ord);
                        }
                    });
                    bool sentToHost = MailUtilities.SendOrderToHost(nome, cognome, ordini, metodoDiPagamento, numeroTel,
                                                                    email, nazione,
                                                                    citta,
                                                                    cap, via, civico, tot, isFatturazione, pIva, fVia, ragSoc, codiceFiscale, sede);
                    if (sentToHost)
                    {
                        bool sentToCustomer = MailUtilities.SendOrderToCustomer(nome, cognome, email, ordini,
                                                                                metodoDiPagamento, tot, nazione, via,
                                                                                cap, civico, citta, isFatturazione, ragSoc, pIva, fVia, codiceFiscale, sede);
                        if (sentToCustomer)
                        {
                            string message =
                                "Gentile Ospite, le confermiamo l invio dell ordine. A breve riceverà una email di conferma." +
                                "A presto, Villa Corano";
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "Popup",
                                                                    "ShowPopup('" + message + "');",
                                                                    true);
                        }
                        else
                        {
                            string message = "Gentile Cliente, le confermiamo l invio dell ordine,"
                                             + "Grazie. "
                                             + "A presto, Villa Corano";
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "Popup",
                                                                    "ShowPopup('" + message + "');",
                                                                    true);
                        }
                    }
                    else
                    {
                        throw new Exception();
                    }
                }
            }
            catch (Exception ex)
            {
                string message =
                    "Gentile Cliente, non è stato possibile completare l ordine. La invitiamo a riprovare o a contattarci telefonicamente." +
                    "Grazie. Villa Corano";
                Page.ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup('" + message + "');", true);
            }
        }
Example #26
0
 public IEnumerable <string> GetAllPendingDomains()
 {
     return(References.Select(r => MailUtilities.GetDomainFromMailbox(r.Recipients[0])).Distinct());
 }
Example #27
0
 static void Main(string[] args)
 {
     MailUtilities.SaveEML("*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**", "Subject", "Body", @"C:\temp\test.txt", true, false);
 }
 /// <summary>
 /// SendKeyByEmail method implementation
 /// </summary>
 public static void SendKeyByEmail(string email, string upn, string key)
 {
     MailUtilities.SendKeyByEmail(email, upn, key, Config.SendMail, Config, CultureInfo.CurrentUICulture);
 }
Example #29
0
        public void Run(BackgroundTaskExecuteContext context)
        {
            var logger = HostContainer.GetInstance <ILogger>();

            if (Interlocked.CompareExchange(ref _hasActiveTask, 1, 0) == 0)
            {
                var countEmails = 0;
                try
                {
                    // Update the background task last running time
                    var backgroundTaskService = HostContainer.GetInstance <IEzBackgroundTaskService>();
                    backgroundTaskService.UpdateLastRunningTimeTask(GetType());

                    var emailLogService     = HostContainer.GetInstance <IEmailLogService>();
                    var emailAccountService = HostContainer.GetInstance <IEmailAccountService>();
                    var emailAccounts       = emailAccountService.GetAll().ToList();
                    var emailLogs           = emailLogService.GetEmailSendingQueues();
                    countEmails = emailLogs.Count();
                    foreach (var emailLog in emailLogs)
                    {
                        var emailAccount = emailAccounts.FirstOrDefault(e => e.Id == emailLog.EmailAccountId);
                        if (emailAccount != null)
                        {
                            var emailSetting = new EmailSetting
                            {
                                Host      = emailAccount.Host,
                                Port      = emailAccount.Port,
                                User      = emailAccount.Username,
                                Password  = emailAccount.Password,
                                EnableSsl = emailAccount.EnableSsl,
                                Timeout   = emailAccount.TimeOut
                            };
                            var mailUtilities = new MailUtilities(emailSetting);
                            var logs          = new List <EmailSendingLog>();
                            try
                            {
                                if (!string.IsNullOrEmpty(emailLog.Message))
                                {
                                    logs = SerializeUtilities.Deserialize <List <EmailSendingLog> >(emailLog.Message);
                                }

                                mailUtilities.SendEmail(emailLog.From ?? emailAccount.Email, emailLog.FromName ?? emailAccount.DisplayName, emailLog.To, emailLog.CC, emailLog.Bcc,
                                                        true, emailLog.Subject, emailLog.Body);
                                emailLog.SentOn = DateTime.UtcNow;

                                logs.Add(new EmailSendingLog
                                {
                                    Time    = DateTime.Now,
                                    Message = string.Format("Mail sent at {0} UTC Time", DateTime.UtcNow)
                                });
                            }
                            catch (Exception exception)
                            {
                                logs.Add(new EmailSendingLog
                                {
                                    Time    = DateTime.Now,
                                    Message = string.Format("Error: {0}", exception.Message)
                                });
                            }

                            emailLog.SentTries++;
                            emailLog.Message = SerializeUtilities.Serialize(logs);
                            emailLogService.UpdateMail(emailLog);
                        }
                    }
                }
                catch (Exception exception)
                {
                    logger.Error(string.Format("[{0}]", EzCMSContants.EmailTaskName), exception);
                }
                if (countEmails > 0)
                {
                    logger.Info(string.Format("[{0}] Send {1} email(s) in queues", EzCMSContants.EmailTaskName, countEmails));
                }
                Interlocked.Exchange(ref _hasActiveTask, 0);
            }
        }
Example #30
0
        public override async ValueTask Handle(P02CreateAccount packet)
        {
            var response = Packets.New <P03CreateAccountResponse>();

            if (!MailUtilities.IsValidAddress(packet.AccountName))
            {
                response.StatusCode = CreateAccountStatus.InvalidAccountName;
            }
            else
            {
                using var csp = SHA256.Create();
                byte[] passwordHash = csp.ComputeHash(packet.KeyHash);

                // As of RFC 5321 the local-part of an email address should not be case-sensitive.
                (var newAccount, var confirmation, bool success) =
                    await Database.AddAccount(packet.AccountName.ToLowerInvariant(), passwordHash).ConfigureAwait(false);

                if (!success)
                {
                    response.StatusCode = CreateAccountStatus.AccountNameTaken;
                }
                else
                {
                    Task mail = mailing.SendMailAsync(confirmation.MailAddress, confirmation.Token);

                    Channel loopback = await Database.AddChannel(
                        new Channel
                    {
                        ChannelType = ChannelType.Loopback,
                        OwnerId     = newAccount.AccountId
                    },
                        new ChannelMember { AccountId = newAccount.AccountId })
                                       .ConfigureAwait(false);

                    Channel accountData = await Database.AddChannel(
                        new Channel
                    {
                        ChannelType = ChannelType.AccountData,
                        OwnerId     = newAccount.AccountId
                    },
                        new ChannelMember { AccountId = newAccount.AccountId })
                                          .ConfigureAwait(false);

                    // Create password update packet
                    var passwordUpdate = Packets.New <P15PasswordUpdate>();
                    passwordUpdate.KeyHash      = packet.KeyHash;
                    passwordUpdate.MessageFlags = MessageFlags.Loopback | MessageFlags.Unencrypted;
                    _ = await injector.CreateMessage(passwordUpdate, loopback.ChannelId, newAccount.AccountId).ConfigureAwait(false);

                    // Create email address
                    var mailAddress = Packets.New <P14MailAddress>();
                    mailAddress.MailAddress = await Database.MailConfirmations.AsQueryable()
                                              .Where(c => c.AccountId == newAccount.AccountId)
                                              .Select(c => c.MailAddress).SingleAsync().ConfigureAwait(false);

                    mailAddress.MessageFlags = MessageFlags.Unencrypted;
                    _ = await injector.CreateMessage(mailAddress, accountData.ChannelId, newAccount.AccountId).ConfigureAwait(false);

                    // As newly created account do not have sessions or contacts there is no need to deliver these packets immediately

                    await mail.ConfigureAwait(false);

                    response.StatusCode = CreateAccountStatus.Success;
                }
            }
            await Client.Send(response).ConfigureAwait(false);
        }