コード例 #1
0
        /// <summary>
        /// Sends the MimeMessage to an SMTP server. This is the lowest level of sending a message.
        /// Connects and authenticates if necessary, but leaves the connection open.
        /// </summary>
        /// <param name="smtpClient"></param>
        /// <param name="message"></param>
        /// <param name="config"></param>
        internal void SendMimeMessageToSmtpServer(SmtpClient smtpClient, MimeMessage message, SmtpClientConfig config)
        {
            var          hostPortConfig = $"{config.SmtpHost}:{config.SmtpPort} using configuration '{config.Name}'";
            const string errorConnect   = "Error trying to connect";
            const string errorAuth      = "Error trying to authenticate on";

            try
            {
                if (!smtpClient.IsConnected)
                {
                    smtpClient.Connect(config.SmtpHost, config.SmtpPort, config.SecureSocketOptions,
                                       _cancellationTokenSource.Token);
                }
            }
            catch (SmtpCommandException ex)
            {
                throw new SmtpCommandException(ex.ErrorCode, ex.StatusCode, ex.Mailbox,
                                               $"{errorConnect} {hostPortConfig}'. " + ex.Message);
            }
            catch (SmtpProtocolException ex)
            {
                throw new SmtpProtocolException(
                          $"{errorConnect} {hostPortConfig}'. " + ex.Message);
            }
            catch (System.IO.IOException ex)
            {
                throw new System.IO.IOException($"{errorConnect} {hostPortConfig}'. " + ex.Message);
            }

            if (config.NetworkCredential != null && !smtpClient.IsAuthenticated && smtpClient.Capabilities.HasFlag(SmtpCapabilities.Authentication))
            {
                try
                {
                    smtpClient.Authenticate(config.NetworkCredential, _cancellationTokenSource.Token);
                }
                catch (AuthenticationException ex)
                {
                    throw new AuthenticationException($"{errorAuth} {hostPortConfig}. " + ex.Message);
                }
                catch (SmtpCommandException ex)
                {
                    throw new SmtpCommandException(ex.ErrorCode, ex.StatusCode, ex.Mailbox,
                                                   $"{errorAuth} {hostPortConfig}. " + ex.Message);
                }
                catch (SmtpProtocolException ex)
                {
                    throw new SmtpProtocolException($"{errorAuth} {hostPortConfig}. " + ex.Message);
                }
            }

            try
            {
                smtpClient.Send(message, _cancellationTokenSource.Token);
            }
            catch (SmtpCommandException ex)
            {
                switch (ex.ErrorCode)
                {
                case SmtpErrorCode.RecipientNotAccepted:
                    throw new SmtpCommandException(ex.ErrorCode, ex.StatusCode, ex.Mailbox,
                                                   $"Recipient not accepted by {hostPortConfig}. " + ex.Message);

                case SmtpErrorCode.SenderNotAccepted:
                    throw new SmtpCommandException(ex.ErrorCode, ex.StatusCode, ex.Mailbox,
                                                   $"Sender not accepted by {hostPortConfig}. " + ex.Message);

                case SmtpErrorCode.MessageNotAccepted:
                    throw new SmtpCommandException(ex.ErrorCode, ex.StatusCode, ex.Mailbox,
                                                   $"Message not accepted by {hostPortConfig}. " + ex.Message);

                default:
                    throw new SmtpCommandException(ex.ErrorCode, ex.StatusCode, ex.Mailbox,
                                                   $"Error sending message to {hostPortConfig}. " + ex.Message);
                }
            }
            catch (SmtpProtocolException ex)
            {
                throw new SmtpProtocolException($"Error while sending message to {hostPortConfig}. " + ex.Message, ex);
            }
        }
コード例 #2
0
        public void NotifyApprovers()
        {
            using var scope = _scopeFactory.CreateScope();
            using var db    = scope.ServiceProvider.GetRequiredService <PortalContext>();
            var Configuration = scope.ServiceProvider.GetRequiredService <IConfiguration>();

            string host        = Configuration["SMTP:Host"];
            string userName    = Configuration["SMTP:UserName"];
            string password    = Configuration["SMTP:Password"];
            string port_str    = Configuration["SMTP:Port"];
            string sender      = Configuration["NotificationCenter:Sender"];
            string senderEmail = Configuration["NotificationCenter:SenderEmail"];
            string portalUrl   = Configuration["NotificationCenter:PortalUrl"];
            string subject     = Configuration["NotificationCenter:PendingChecksSubject"];

            if (string.IsNullOrEmpty(host) || !int.TryParse(port_str, out int port))
            {
                return;
            }

            var departmentIds = db.SecurityChecks
                                .Where(c => c.Status == DeviceStatus.Submitted)
                                .Select(c => c.Device.DepartmentId)
                                .ToArray();
            var departmentCounts = departmentIds
                                   .GroupBy(id => id)
                                   .ToDictionary(g => g.Key, g => g.Count());
            var departmentIdSet = departmentIds.ToHashSet();

            var departmentMap = db.Departments
                                .Where(d => departmentIdSet.Contains(d.Id))
                                .Select(d => new { d.Id, d.Name })
                                .ToDictionary(d => d.Id, d => d.Name);
            var approvers = db.Users
                            .Where(u => u.CanApprove && u.Departments.Any(d => departmentIdSet.Contains(d.DepartmentId)))
                            .Select(u => new { u.Name, u.Email, DepartmentIds = u.Departments.Select(d => d.DepartmentId) })
                            .ToArray();

            using var client = new SmtpClient();
            client.Connect(host, port, false);
            if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
            {
                client.Authenticate(userName, password);
            }

            foreach (var approver in approvers)
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(sender, senderEmail));
                message.To.Add(new MailboxAddress(approver.Name, approver.Email));
                message.Subject = subject;

                HashSet <int> userDepartmentIds = approver.DepartmentIds
                                                  .Intersect(departmentIdSet)
                                                  .ToHashSet();
                string[] departmentNames = userDepartmentIds
                                           .Select(id => departmentMap[id])
                                           .ToArray();
                int count = userDepartmentIds
                            .Select(id => departmentCounts[id])
                            .Sum();
                message.Body = new TextPart("html")
                {
                    Text = MailBody(approver.Name, departmentNames, count, portalUrl),
                };
                client.Send(message);
            }

            client.Disconnect(true);
        }
コード例 #3
0
        private async void sendTimer_Tick(object sender, EventArgs e)
        {
            logger.Debug("Send Timer Tick");
            sendInfoToolStripStatusLabel.Text = "Sending...";

            MailItem mailItem = new MailItem();

            mailItem.Timestamp        = DateTime.Now;
            mailItem.Ticks            = mailItem.Timestamp.Ticks;
            mailItem.ToAddress        = Properties.Settings.Default.smtpToAddress;
            mailItem.TimeoutTimestamp = mailItem.Timestamp.AddSeconds(Decimal.ToDouble(Properties.Settings.Default.receiveTimeout));

            Task sendTask = Task.Run(() =>
            {
                string hostName       = Dns.GetHostName();
                string hostIPv4       = "unknown";
                IPAddress[] addresses = Dns.GetHostAddresses(hostName);
                foreach (IPAddress ip4 in addresses.Where(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork))
                {
                    hostIPv4 = ip4.ToString();
                    break;
                }

                MimeMessage message = new MimeMessage();
                message.From.Add(new MailboxAddress(Properties.Settings.Default.smtpFromName, Properties.Settings.Default.smtpFromAddress));
                message.To.Add(MailboxAddress.Parse(mailItem.ToAddress));
                message.Subject = String.Format("Mail Check Client {0}", mailItem.Ticks);

                message.Body = new TextPart("plain")
                {
                    Text = String.Format(
                        "Hello\n\nThis e-mail was automatically generated by Mail Check Client.\n\nVersion: {0}\nClient-Host: {1} ({2})\nClient-Timestamp: {3}\nTicks: {4}\n\nEnd of message.",
                        System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                        hostName, hostIPv4,
                        mailItem.Timestamp,
                        mailItem.Ticks
                        )
                };


                using (SmtpClient client = Properties.Settings.Default.smtpLoggingEnabled ? new SmtpClient(new ProtocolLogger(Properties.Settings.Default.smtpLoggingFile)) : new SmtpClient())
                {
                    client.Timeout = Decimal.ToInt32(Properties.Settings.Default.smtpNetworkTimeout) * 1000;
                    client.ServerCertificateValidationCallback = NoSslCertificateValidationCallback;

                    try
                    {
                        if (Properties.Settings.Default.smtpSSL)
                        {
                            client.Connect(Properties.Settings.Default.smtpHost, Decimal.ToInt32(Properties.Settings.Default.smtpPort), MailKit.Security.SecureSocketOptions.Auto);
                        }
                        else
                        {
                            client.Connect(Properties.Settings.Default.smtpHost, Decimal.ToInt32(Properties.Settings.Default.smtpPort), false);
                        }

                        if (Properties.Settings.Default.smtpLoginUsername.Length > 0)
                        {
                            client.Authenticate(Properties.Settings.Default.smtpLoginUsername, Properties.Settings.Default.smtpLoginPassword);
                        }

                        logger.Info(String.Format("Sending message tick {0}", mailItem.Ticks));
                        client.Send(message);
                        mailItem.Status = MailItem.StatusType.Sent;
                        logger.Info("Message successfully sent.");
                    }
                    catch (Exception ex)
                    {
                        mailItem.Status = MailItem.StatusType.Error;
                        logger.Error("Sending mail failed", ex);
                    }
                    finally
                    {
                        lock (mailItems)
                        {
                            mailItems.Add(mailItem);
                        }
                        client.Disconnect(true);
                    }
                }
            });

            await(sendTask);
            sendTask.Dispose();
            sendInfoToolStripStatusLabel.Text = "";
            insertMailListViewItem(mailItem);
        }
コード例 #4
0
        static void SendMailMime(MailInputs maildata)
        {
            try
            {
                //---------------------
                //  Configuration

                //  User setup
                string User     = maildata.User;
                string UserName = maildata.User;
                string pssw     = maildata.Password;

                //  Server setup
                string server = maildata.Server;
                int    port   = Convert.ToInt32(maildata.Port);

                //  Mail setup
                string attachment  = maildata.Attachment;
                string MailBody    = maildata.Body;
                string MailSubject = maildata.Subject;

                string toAddressString  = maildata.To;
                string ccAddressString  = maildata.Cc;
                string bccAddressString = maildata.Bcc;

                //--------------------

                MimeMessage message = new MimeMessage();

                MailboxAddress from = new MailboxAddress(UserName, User);
                message.From.Add(from);

                if (!string.IsNullOrEmpty(toAddressString))
                {
                    InternetAddressList toList = new InternetAddressList();
                    toList.AddRange(MimeKit.InternetAddressList.Parse(toAddressString));
                    message.To.AddRange(toList);
                }


                if (!string.IsNullOrEmpty(ccAddressString))
                {
                    InternetAddressList ccList = new InternetAddressList();
                    ccList.AddRange(MimeKit.InternetAddressList.Parse(ccAddressString));
                    message.Cc.AddRange(ccList);
                }


                if (!string.IsNullOrEmpty(bccAddressString))
                {
                    InternetAddressList bccList = new InternetAddressList();
                    bccList.AddRange(MimeKit.InternetAddressList.Parse(bccAddressString));
                    message.Bcc.AddRange(bccList);
                }

                //Mail body

                BodyBuilder bodyBuilder = new BodyBuilder();
                //bodyBuilder.HtmlBody = "<h1>This is a mail body</h1>";
                message.Subject = MailSubject;
                if (!string.IsNullOrEmpty(MailBody))
                {
                    bodyBuilder.TextBody = MailBody;
                }


                //
                if (!string.IsNullOrEmpty(attachment))
                {
                    bodyBuilder.Attachments.Add(attachment);
                }

                message.Body = bodyBuilder.ToMessageBody();


                SmtpClient client = new SmtpClient();


                client.Connect(server, port, SecureSocketOptions.None);
                client.Authenticate(User, pssw);


                client.Send(message);
                client.Disconnect(true);
                client.Dispose();



                Console.WriteLine("");
                //Console.ReadLine();

                //............................
            }
            catch (Exception ep)
            {
                Console.WriteLine("failed to send email with the following error:");
                Console.WriteLine(ep.Message);
                Console.ReadLine();
            }
        }
コード例 #5
0
ファイル: UserAuth.cs プロジェクト: arn3342/Mailarn
        public SmtpClient Authenticate(string email = "", string pwd = "", string smtpserver = "", int smtpport = 0, int ParallelCount = 0)
        {
            string TempPath = Path.GetTempPath() + "\\Mailarn\\";

            if (Directory.Exists(TempPath) && Directory.GetFiles(TempPath).Length > 0)
            {
                email = Email(); pwd = Password(); smtpserver = SMTP(); smtpport = SMTPPort();
                SignIn(email, pwd, smtpserver, smtpport);
            }
            else
            {
                Random r = new Random();
                MailKitClient = new SmtpClient(new ProtocolLogger("smtp" + r.Next(1, 100).ToString() + ".log"));
                if (email != "")
                {
                    Directory.CreateDirectory(TempPath);
                    File.WriteAllLines(TempPath + "ucc.data", new string[] { Cipher.Encrypt(email, securitykey),
                                                                             Cipher.Encrypt(pwd, securitykey),
                                                                             Cipher.Encrypt(smtpserver, securitykey),
                                                                             Cipher.Encrypt(smtpport.ToString(), securitykey) });
                    SignIn(email, pwd, smtpserver, smtpport);
                    try
                    {
                        var message = new MimeMessage();
                        message.From.Add(new MailboxAddress("Mailarn Test", email));
                        message.To.Add(new MailboxAddress("Test", email));
                        message.Subject = "A test email";
                        message.Body    = new TextPart("plain")
                        {
                            Text = @"This is a test email sent from Mailarn E-Marketing software."
                        };
                        if (MailKitClient.IsConnected)
                        {
                            MailKitClient.Disconnect(true);
                        }
                        MailKitClient.Connect(smtpserver, smtpport, SecureSocketOptions.StartTls);
                        MailKitClient.Authenticate(email, pwd);
                        MailKitClient.Send(message);
                        MailKitClient.Disconnect(true);
                    }
                    catch (Exception ex)
                    {
                        errorstring = "Failed to send test email " + Environment.NewLine + "Details : " + ex.ToString();
                    }
                    if (errorstring == "")
                    {
                        UserManagement          userManagement = new UserManagement(Email: email, Password: pwd);
                        int                     userId         = userManagement.GetUser().U_Id;
                        AuthSuccessEventHandler Success        = AuthSuccess;
                        Success?.Invoke(userId);
                    }
                }
                else
                {
                    EventHandler LoginReq = LoginRequired;
                    LoginReq?.Invoke(null, null);
                    ProgressEventHandler Login = Progress;
                    Login?.Invoke("Initializing");
                }
            }
            return(MailKitClient);
        }
コード例 #6
0
ファイル: EmailService.cs プロジェクト: ahammedunni/EbTestCi
            public string Post(EmailServicesMqRequest request)
            {
                var _InfraDb  = base.ResolveService <ITenantDbFactory>() as TenantDbFactory;
                var myService = base.ResolveService <EbObjectService>();
                var res       = (EbObjectParticularVersionResponse)myService.Get(new EbObjectParticularVersionRequest()
                {
                    RefId = request.refid
                });
                EbEmailTemplate ebEmailTemplate = new EbEmailTemplate();

                foreach (var element in res.Data)
                {
                    ebEmailTemplate = EbSerializers.Json_Deserialize(element.Json);
                }



                var myDs    = base.ResolveService <EbObjectService>();
                var myDsres = (EbObjectParticularVersionResponse)myDs.Get(new EbObjectParticularVersionRequest()
                {
                    RefId = ebEmailTemplate.DataSourceRefId
                });
                // get sql from ebdatasource and render the sql
                EbDataSource ebDataSource = new EbDataSource();

                foreach (var element in myDsres.Data)
                {
                    ebDataSource = EbSerializers.Json_Deserialize(element.Json);
                }
                var ds      = _InfraDb.ObjectsDB.DoQueries(ebDataSource.Sql);
                var pattern = @"\{{(.*?)\}}";
                var matches = Regex.Matches(ebEmailTemplate.Body, pattern);
                Dictionary <string, object> dict = new Dictionary <string, object>();

                foreach (Match m in matches)
                {
                    string str = Regex.Replace(m.Value, "[{}]", "");
                    foreach (var dt in ds.Tables)
                    {
                        string colname = dt.Rows[0][str.Split('.')[1]].ToString();
                        ebEmailTemplate.Body = ebEmailTemplate.Body.Replace(m.Value, colname);
                    }
                }
                var emailMessage = new MimeMessage();

                emailMessage.From.Add(new MailboxAddress("EXPRESSbase", "*****@*****.**"));
                emailMessage.To.Add(new MailboxAddress("", request.To));
                emailMessage.Subject = ebEmailTemplate.Subject;
                emailMessage.Body    = new TextPart("html")
                {
                    Text = ebEmailTemplate.Body
                };
                try
                {
                    using (var client = new SmtpClient())
                    {
                        client.LocalDomain = "www.expressbase.com";
                        client.Connect("smtp.gmail.com", 465, true);
                        client.Authenticate(new System.Net.NetworkCredential()
                        {
                            UserName = "******", Password = "******"
                        });
                        client.Send(emailMessage);
                        client.Disconnect(true);
                    }
                }
                catch (Exception e)
                {
                    return(e.Message);
                }
                return(null);
            }
コード例 #7
0
        public IActionResult SendMessage(Message m, string returnURL, bool checkAll = false, bool checkAllBrokers = false, bool checkStaff = false,
                                         bool checkNewBrokers = false, bool checkBrokersInTransition = false, bool checkTransferBrokers    = false)
        {
            var message = new Message
            {
                Subject  = m.Subject,
                Body     = m.Body,
                DateSent = DateTime.Now,
            };


            messageRepo.AddMessage(message);

            if (checkAll == true)
            {
                brokers = brokerRepo.GetAllBrokers(false, true);
                staff   = staffRepo.GetAllStaffProfiles(true);
            }
            else
            {
                if (checkAllBrokers == true)
                {
                    brokers = brokerRepo.GetAllBrokers(false, true);
                }
                else
                {
                    if (checkNewBrokers == true)
                    {
                        if (brokers != null)
                        {
                            var newBrokers = brokerRepo.GetBrokersByType("New Broker", true);
                            foreach (var b in newBrokers)
                            {
                                brokers.Append(b);
                            }
                        }
                        else
                        {
                            brokers = brokerRepo.GetBrokersByType("New Broker", true);
                        }
                    }

                    if (checkBrokersInTransition == true)
                    {
                        if (brokers != null)
                        {
                            var transitionBrokers = brokerRepo.GetBrokersByType("In Transition", true);
                            foreach (var b in transitionBrokers)
                            {
                                brokers.Append(b);
                            }
                        }
                        else
                        {
                            brokers = brokerRepo.GetBrokersByType("In Transition", true);
                        }
                    }
                    if (checkTransferBrokers == true)
                    {
                        if (brokers != null)
                        {
                            var transferBrokers = brokerRepo.GetBrokersByType("Transfer", true);
                            foreach (var b in transferBrokers)
                            {
                                brokers.Append(b);
                            }
                        }
                        else
                        {
                            brokers = brokerRepo.GetBrokersByType("Transfer", true);
                        }
                    }
                }
                if (checkStaff == true)
                {
                    staff = staffRepo.GetAllStaffProfiles(true);
                }
            }
            var email = new MimeMessage();

            email.From.Add(new MailboxAddress("KWFCI", "*****@*****.**"));
            email.Subject = message.Subject;
            email.Body    = new TextPart("plain")
            {
                Text = message.Body
            };
            if (brokers != null)
            {
                foreach (var b in brokers)
                {
                    email.Bcc.Add(new MailboxAddress(b.FirstName + " " + b.LastName, b.Email));
                }
            }

            if (staff != null)
            {
                foreach (var st in staff)
                {
                    email.Bcc.Add(new MailboxAddress(st.FirstName + " " + st.LastName, st.Email));
                }
            }
            using (var client = new SmtpClient())
            {
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                client.Connect("smtp.gmail.com", 587, false);

                client.AuthenticationMechanisms.Remove("XOAUTH2");
                client.Authenticate("kwfamilycheckin", "Fancy123!");

                client.Send(email);
                client.Disconnect(true);
            }



            return(Redirect(returnURL));
        }
コード例 #8
0
        public async Task Send(NotificationMessage model, EmailNotificationSettings settings)
        {
            try
            {
                EnsureArg.IsNotNullOrEmpty(settings.SenderAddress);
                EnsureArg.IsNotNullOrEmpty(model.To);
                EnsureArg.IsNotNullOrEmpty(model.Message);
                EnsureArg.IsNotNullOrEmpty(settings.Host);

                var body = new BodyBuilder
                {
                    HtmlBody = model.Message,
                };

                if (model.Other.ContainsKey("PlainTextBody"))
                {
                    body.TextBody = model.Other["PlainTextBody"];
                }

                var message = new MimeMessage
                {
                    Body    = body.ToMessageBody(),
                    Subject = model.Subject
                };

                message.From.Add(new MailboxAddress(string.IsNullOrEmpty(settings.SenderName) ? settings.SenderAddress : settings.SenderName, settings.SenderAddress));
                message.To.Add(new MailboxAddress(model.To, model.To));

                using (var client = new SmtpClient())
                {
                    if (settings.DisableCertificateChecking)
                    {
                        client.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
                    }

                    if (settings.DisableTLS)
                    {
                        client.Connect(settings.Host, settings.Port, MailKit.Security.SecureSocketOptions.None);
                    }
                    else
                    {
                        client.Connect(settings.Host, settings.Port); // Let MailKit figure out the correct SecureSocketOptions.
                    }

                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    if (settings.Authentication)
                    {
                        client.Authenticate(settings.Username, settings.Password);
                    }
                    //Log.Info("sending message to {0} \r\n from: {1}\r\n Are we authenticated: {2}", message.To, message.From, client.IsAuthenticated);
                    await client.SendAsync(message);

                    await client.DisconnectAsync(true);
                }
            }
            catch (Exception e)
            {
                _log.LogError(e, "Exception when attempting to send email");
                throw;
            }
        }
コード例 #9
0
        public void godkendelseskode(object sender, EventArgs p)
        {
            _activi.IsRunning = true;

            var navn      = _navn.Text;
            var efternavn = _efternavn.Text;
            var email     = _email.Text;

            var chars       = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            var numbers     = "0123456789";
            var stringChars = new char[8];
            var random      = new Random();


            for (int i = 0; i < 2; i++)
            {
                stringChars[i] = chars[random.Next(chars.Length)];
            }
            for (int i = 2; i < 6; i++)
            {
                stringChars[i] = numbers[random.Next(numbers.Length)];
            }
            for (int i = 6; i < 8; i++)
            {
                stringChars[i] = chars[random.Next(chars.Length)];
            }

            var finalString = new String(stringChars);



            var message = new MimeMessage();

            message.From.Add(new MailboxAddress("Godkendelse", "*****@*****.**"));
            message.To.Add(new MailboxAddress(navn, email));
            message.Subject = "Godkendelseskode";



            message.Body = new TextPart("plain")
            {
                Text = navn + "<br>" + efternavn + "<br>" + email + "<br>" + "Godkendelseskode:" + finalString
            };
            using (var client = new SmtpClient())
            {
                // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                client.Connect("smtp.outlook.com", 587, false);

                // Note: only needed if the SMTP server requires authentication
                client.Authenticate("*****@*****.**", "helsingor123");

                client.Send(message);
                client.Disconnect(true);
            }

            _kode.IsVisible    = true;
            _godkend.IsVisible = true;

            _navn.IsVisible      = false;
            _efternavn.IsVisible = false;
            _email.IsVisible     = false;
            _send.IsVisible      = false;
            _annuller.IsVisible  = false;
            _tjek.IsVisible      = false;


            _activi.IsRunning = false;

            _godkend.Clicked += async(object asas, EventArgs aaaa) =>
            {
                if (_kode.Text.Equals(finalString))
                {
                    _activi.IsRunning = true;

                    var person = new DatabaseFolder.person(navn, efternavn, email);



                    FirebaseFolder.FirebaseTetrizBegivenhederDB db = new FirebaseFolder.FirebaseTetrizBegivenhederDB();
                    await db.AddDeltager(getkeyy, person);



                    _navn.Text      = "";
                    _efternavn.Text = "";
                    _email.Text     = "";

                    await Navigation.PopPopupAsync();

                    _activi.IsRunning = false;
                }
                else
                {
                    Console.WriteLine("oc, det virker ikke");
                }
            };
        }
コード例 #10
0
ファイル: EmailGrain.cs プロジェクト: osmidhun/rrod
        public Task SendEmail(Email email)
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(smtpSettings.FromDisplayName, smtpSettings.FromAddress));
            email.To.ForEach(address => message.To.Add(MailboxAddress.Parse(address)));
            message.Subject = email.Subject.Replace('\r', ' ').Replace('\n', ' ');
            var body = new TextPart("html")
            {
                Text = email.MessageBody
            };

            if (email.Attachments != null)
            {
                var multipart = new Multipart("mixed")
                {
                    body
                };
                email.Attachments.ForEach(attachment => {
                    multipart.Add(new MimePart(attachment.MimeType)
                    {
                        Content                 = new MimeContent(new MemoryStream(attachment.Data), ContentEncoding.Default),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName                = attachment.Name
                    });
                });
                message.Body = multipart;
            }
            else
            {
                message.Body = body;
            }

            Task.Run(() =>
            {
                try
                {
                    using (var client = new SmtpClient())
                    {
                        // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                        client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                        client.Connect(smtpSettings.Host, smtpSettings.Port, false);

                        // Note: since we don't have an OAuth2 token, disable
                        // the XOAUTH2 authentication mechanism.
                        client.AuthenticationMechanisms.Remove("XOAUTH2");

                        // Note: only needed if the SMTP server requires authentication
                        client.Authenticate(smtpSettings.UserName, smtpSettings.Password);

                        client.Send(message);
                        client.Disconnect(true);
                    }
                }
                catch (Exception e)
                {
                    this.logger.LogError(e, "EmailGrain: Error sending email");
                }
            });

            return(Task.CompletedTask);
        }
コード例 #11
0
        private void SendEmail(Order order)
        {
            if (order.Suppliers.Count() > 1)
            {
                Debug.WriteLine(order.Suppliers);
                string[] emails = order.Suppliers.Split(',');

                foreach (string emailaddress in emails)
                {
                    Debug.WriteLine(emailaddress);
                    var currentuser = HttpContext.Session.GetObjectFromJson <User>("CurrentUser");
                    var message     = new MimeMessage();
                    message.From.Add(new MailboxAddress("LPX Orders", "*****@*****.**"));
                    message.To.Add(new MailboxAddress("Suppliers", emailaddress));
                    message.Subject = "LPX Order: " + order.OrderNumber;

                    var bodyBuilder = new BodyBuilder();
                    bodyBuilder.HtmlBody = String.Format("<h2>Hello You have a new LPX Order {0}</h2>" + "\n" + "<p>this order was placed by {1}.</p>" + "\n " + @"<a href=""/suppliers/"">Please clcik here to fulfill the order</a>", order.OrderNumber, order.PlacedBy);



                    message.Body = bodyBuilder.ToMessageBody();

                    using (var client = new SmtpClient())
                    {
                        client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                        client.Connect("smtp.gmail.com", 587);



                        // Note: since we don't have an OAuth2 token, disable
                        // the XOAUTH2 authentication mechanism.
                        client.AuthenticationMechanisms.Remove("XOAUTH2");

                        // Note: only needed if the SMTP server requires authentication
                        client.Authenticate("*****@*****.**", "Asking12");

                        client.Send(message);
                        client.Disconnect(true);
                    }
                }
            }

            else
            {
                var currentuser = HttpContext.Session.GetObjectFromJson <User>("CurrentUser");
                var message     = new MimeMessage();
                message.From.Add(new MailboxAddress("LPX Orders", "*****@*****.**"));
                message.To.Add(new MailboxAddress("Suppliers", order.Suppliers));
                message.Subject = "LPX Order: " + order.OrderNumber;

                var bodyBuilder = new BodyBuilder();
                bodyBuilder.HtmlBody = String.Format("<h2>Hello You have a new LPX Order {0}</h2>" + "\n" + "<p>this order was placed by {1}.</p>" + "\n " + @"<a href=""/suppliers/"">Please clcik here to fulfill the order</a>", order.OrderNumber, order.PlacedBy);



                message.Body = bodyBuilder.ToMessageBody();

                using (var client = new SmtpClient())
                {
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    client.Connect("smtp.gmail.com", 587);



                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    // Note: only needed if the SMTP server requires authentication
                    client.Authenticate("*****@*****.**", "Asking12");

                    client.Send(message);
                    client.Disconnect(true);
                }
            }
        }
コード例 #12
0
        public JsonResult SendLocal(IEnumerable <string> emails)
        {
            try
            {
                var sender = db.Account.SingleOrDefault(a => a.AccountEmail == email);

                foreach (var email in emails)
                {
                    var rcpt = db.LocalPaySlip.SingleOrDefault(l => l.Email == email);

                    var message = new MimeMessage();
                    message.From.Add(new MailboxAddress(sender.AccountEmail));
                    message.To.Add(new MailboxAddress(email));
                    message.Subject = $"Pay Slip for {DateTime.Now.ToString("MMM-yyyy")}";
                    // message.Subject = $"Pay Slip for June 2019";
                    message.Body = new TextPart(TextFormat.Html)
                    {
                        Text = "<style>" +
                               "table { border-collapse: collapse; } " +
                               "th, td { border: 1px solid #ddd; padding: 3px; font-family: Calibri; font-size: 10.5pt; } " +
                               ".emp-info { background: lightyellow; } " +
                               ".income, .payable {background: lightgreen; } " +
                               ".deduction { background: red; }" +
                               "</style>" +
                               "<table>" +
                               "<thead>" +
                               "<tr>" +
                               "<th class='emp-info'>No.</th>" +
                               "<th class='emp-info'>Name</th>" +
                               "<th class='emp-info'>Email</th>" +
                               "<th class='emp-info'>Region</th>" +
                               "<th class='emp-info'>Bank Details</th>" +
                               "<th class='income'>Base Salary</th>" +
                               "<th class='income'>Total Working Days</th>" +
                               "<th class='income'>Actual Working Days</th>" +
                               "<th class='income'>Total Base Salary</th>" +
                               "<th class='income'>Overtime</th>" +
                               "<th class='income'>Others Income</th>" +
                               "<th class='income'>Gross Taxable Income</th>" +
                               "<th class='deduction'>SSB</th>" +
                               "<th class='deduction'>Tax Payment</th>" +
                               "<th class='deduction'>Others Deduction</th>" +
                               "<th class='deduction'>Total Deduction</th>" +
                               "<th class='payable'>Net Pay</th>" +
                               "<th class='payable'>New Per Diem</th>" +
                               "<th class='payable'>Others</th>" +
                               "<th class='payable'>Payable</th>" +
                               "</tr>" +
                               "</thead>" +
                               "<tbody>" +
                               "<tr>" +
                               $"<td>{rcpt.EmpId}</td>" +
                               $"<td>{rcpt.Name}</td>" +
                               $"<td>{rcpt.EmpId}</td>" +
                               $"<td>{rcpt.Region}</td>" +
                               $"<td>{rcpt.BankDetails}</td>" +
                               $"<td>{rcpt.BaseSalary}</td>" +
                               $"<td>{rcpt.TotalWorkingDays}</td>" +
                               $"<td>{rcpt.ActualWorkingDays}</td>" +
                               $"<td>{rcpt.TotalBaseSalary}</td>" +
                               $"<td>{rcpt.Overtime}</td>" +
                               $"<td>{rcpt.OthersIncome}</td>" +
                               $"<td>{rcpt.GrossTaxableIncome}0</td>" +
                               $"<td>{rcpt.Ssb}</td>" +
                               $"<td>{rcpt.TaxPayment}</td>" +
                               $"<td>{rcpt.OthersDeduction}</td>" +
                               $"<td>{rcpt.TotalDeduction}</td>" +
                               $"<td>{rcpt.NetPay}</td>" +
                               $"<td>{rcpt.NewPerDiem}</td>" +
                               $"<td>{rcpt.Others}</td>" +
                               $"<td>{rcpt.Payable}</td>"
                    };

                    using (var client = new SmtpClient())
                    {
                        client.Connect("smtp.office365.com", 587, false);
                        client.Authenticate(sender.AccountEmail, service.Decrypt(sender.AccountPassword, sender.AccountSalt));
                        client.Send(message);
                        client.Disconnect(true);
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);
            }

            return(Json(emails));
        }
コード例 #13
0
        public JsonResult SendExpat(IEnumerable <string> emails)
        {
            try
            {
                var sender = db.Account.SingleOrDefault(a => a.AccountEmail == email);

                foreach (var email in emails)
                {
                    var rcpt = db.ExpatPaySlip.SingleOrDefault(l => l.Email == email);

                    var message = new MimeMessage();
                    message.From.Add(new MailboxAddress(sender.AccountEmail));
                    message.To.Add(new MailboxAddress(email));
                    message.Subject = $"Pay Slip for {DateTime.Now.ToString("MMM-yyyy")}";
                    // message.Subject = $"Pay Slip for June 2019";
                    message.Body = new TextPart(TextFormat.Html)
                    {
                        Text = "<style>" +
                               "table { border-collapse: collapse; } " +
                               "th, td { border: 1px solid #ddd; padding: 3px; font-family: Calibri; font-size: 10.5pt; } " +
                               ".emp-info { background: lightyellow; } " +
                               ".income, .payable {background: lightgreen; } " +
                               ".deduction { background: red; }" +
                               "</style>" +
                               "<table>" +
                               "<thead>" +
                               "<tr>" +
                               "<th class='emp-info'>No.</th>" +
                               "<th class='emp-info'>Name</th>" +
                               "<th class='emp-info'>Email</th>" +
                               "<th class='emp-info'>Region</th>" +
                               "<th class='emp-info'>Designation</th>" +
                               "<th class='emp-info'>MonthlySalary_USD</th>" +
                               "<th class='income'>FxRate</th>" +
                               "<th class='income'>BaseSalary_MMK</th>" +
                               "<th class='income'>WorkingDays</th>" +
                               "<th class='income'>ActualWorkedDays</th>" +
                               "<th class='income'>TotalBaseSalary</th>" +
                               "<th class='income'>HousingAllowance_MMK</th>" +
                               "<th class='income'>MedicalAllowance_MMK</th>" +
                               "<th class='deduction'>OtherBenefits_MMK</th>" +
                               "<th class='deduction'>GrossTaxableIncome_MMK</th>" +
                               "<th class='deduction'>SSB_MMK</th>" +
                               "<th class='deduction'>TaxPayment_MMK</th>" +
                               "<th class='payable'>ThirdPartyPaidBenefits_MMK</th>" +
                               "<th class='payable'>OtherDeduction_MMK</th>" +
                               "<th class='payable'>TotalDeduction_MMK</th>" +
                               "<th class='payable'>NetPay_MMK</th>" +
                               "<th class='payable'>NetPay_USD</th>" +
                               "<th class='payable'>ExpenseClaims_USD</th>" +
                               "<th class='payable'>TotalPayable_USD</th>" +
                               "</tr>" +
                               "</thead>" +
                               "<tbody>" +
                               "<tr>" +
                               $"<td>{rcpt.EmpId}</td>" +
                               $"<td>{rcpt.Name}</td>" +
                               $"<td>{rcpt.EmpId}</td>" +
                               $"<td>{rcpt.Region}</td>" +
                               $"<td>{rcpt.Designation}</td>" +
                               $"<td>{rcpt.MonthlySalaryUsd}</td>" +
                               $"<td>{rcpt.FxRate}</td>" +
                               $"<td>{rcpt.BaseSalaryMmk}</td>" +
                               $"<td>{rcpt.WorkingDays}</td>" +
                               $"<td>{rcpt.ActualWorkedDays}</td>" +
                               $"<td>{rcpt.TotalBaseSalary}</td>" +
                               $"<td>{rcpt.HousingAllowanceMmk}</td>" +
                               $"<td>{rcpt.MedicalAllowanceMmk}</td>" +
                               $"<td>{rcpt.OtherBenefitsMmk}</td>" +
                               $"<td>{rcpt.GrossTaxableIncomeMmk}</td>" +
                               $"<td>{rcpt.SsbMmk}</td>" +
                               $"<td>{rcpt.TaxPaymentMmk}</td>" +
                               $"<td>{rcpt.ThirdPartyPaidBenefitsMmk}</td>" +
                               $"<td>{rcpt.OtherDeductionMmk}</td>" +
                               $"<td>{rcpt.TotalDeductionMmk}</td>" +
                               $"<td>{rcpt.NetPayMmk}</td>" +
                               $"<td>{rcpt.NetPayUsd}</td>" +
                               $"<td>{rcpt.ExpenseClaimsUsd}</td>" +
                               $"<td>{rcpt.TotalPayableUsd}</td>"
                    };

                    using (var client = new SmtpClient())
                    {
                        client.Connect("smtp.office365.com", 587, false);
                        client.Authenticate(sender.AccountEmail, service.Decrypt(sender.AccountPassword, sender.AccountSalt));
                        client.Send(message);
                        client.Disconnect(true);
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);
            }

            return(Json(emails));
        }
コード例 #14
0
        public IActionResult CheckOut(Order order)
        {
            List <Product> products = HttpContext.Session.Get <List <Product> >("products");



            //[email protected]
            //000001234500000
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress("Online Store", "*****@*****.**"));
            message.To.Add(new MailboxAddress(order.Name.ToString(), order.Email.ToString()));
            message.Subject = "Test Online MAil";
            var htmlString = " Hello Thank you for buying from our site, we will deliver your order as soon as possible <br/>";

            htmlString += @"<div>
                 <table>
                    <thead>
                        <tr>
                            
                            <th>Name</th>
                            <th>Price</th>
                            <th>Product Type</th>
                            <th>Color</th>
                            <th></th>
                        </tr>
                    </thead>";

            htmlString += @"<tbody>";



            foreach (var item in products)
            {
                htmlString += @"<tr>
                    
                       <td>" + item.Name + "</td>" +

                              "<td>" + item.Price + " </td>" +

                              "<td>" + item.ProductTypes.ProductType + " </td>" +

                              "<td>" + item.ProductColor + " </td>" +
                              "</tr>";
            }
            htmlString += @"</tbody>";

            message.Body = new TextPart(TextFormat.Html)
            {
                Text = htmlString
            };



            using (var client = new SmtpClient())
            {
                client.Connect("smtp.gmail.com", 587, false);
                client.Authenticate("*****@*****.**", "000001234500000");
                client.Send(message);
                client.Disconnect(true);
            }



            if (products != null)
            {
                foreach (var product in products)
                {
                    OrderDetails orderDetails = new OrderDetails();
                    orderDetails.ProductId = product.Id;

                    order.OrderDetails.Add(orderDetails);
                }
            }


            order.OrderNo = GetOrderNo();
            orderRepository.Add(order);
            HttpContext.Session.Set("products", new List <Product>());
            return(RedirectToAction("ThankYou"));
        }
コード例 #15
0
        // GET: ComPersona
        public async Task <IActionResult> Index(string reporte, string valuesOrder, string searchPerson)
        {
            try
            {
                var persona = from s in _context.ComPersona select s;
                persona = persona.Include(c => c.ComCatEscolaridad).Include(c => c.ComCatSexo);

                // Generar reporte PDF
                ViewData["GenerateReports"] = "reporte";

                if (!String.IsNullOrEmpty(reporte))
                {
                    // Creamos el documento PDF con el formato de hoja A4, y Rotate() para ponerla horizontal.
                    Document doc = new Document(PageSize.A4.Rotate());
                    // Indicamos la ruta donde se va a guardar el documento.
                    PdfWriter writer = PdfWriter.GetInstance(doc,
                                                             new FileStream(@"/Users/marcosmontiel/Desktop/personas.pdf", FileMode.Create));
                    // Colocamos el titulo y autor del documento (Esto no será visible en el documento).
                    doc.AddTitle("Reporte - Personas");
                    doc.AddCreator("Marcos Gabriel Cruz Montiel");
                    // Abrimos el documento.
                    doc.Open();
                    // Creamos el tipo de fuente, tamaño, estilo y color que vamos a utilizar.
                    Font fontPrincipal = new Font(Font.HELVETICA, 10, Font.BOLD, BaseColor.White);
                    Font fontBody      = new Font(Font.HELVETICA, 8, Font.NORMAL, BaseColor.Black);
                    // Añadimos el encabezado del documento.
                    doc.Add(new Paragraph("Reporte - Personas"));
                    doc.Add(Chunk.Newline);
                    // Creamos la tabla que contendrá los registro de la tabla ComPersona.
                    PdfPTable tblPersona = new PdfPTable(7)
                    {
                        WidthPercentage = 100
                    };
                    // Configuramos el titulo de las columnas.
                    PdfPCell colNombre = new PdfPCell(new Phrase("Nombre", fontPrincipal))
                    {
                        BorderWidth       = 0,
                        BorderColor       = WebColors.GetRgbColor("#009432"),
                        BackgroundColor   = WebColors.GetRgbColor("#009432"),
                        PaddingTop        = 10,
                        PaddingRight      = 0,
                        PaddingBottom     = 13,
                        PaddingLeft       = 15,
                        VerticalAlignment = Element.ALIGN_CENTER
                    };

                    PdfPCell colAPaterno = new PdfPCell(new Phrase("A. Paterno", fontPrincipal))
                    {
                        BorderWidth       = 0,
                        BorderColor       = WebColors.GetRgbColor("#009432"),
                        BackgroundColor   = WebColors.GetRgbColor("#009432"),
                        PaddingTop        = 10,
                        PaddingRight      = 0,
                        PaddingBottom     = 13,
                        PaddingLeft       = 15,
                        VerticalAlignment = Element.ALIGN_CENTER
                    };

                    PdfPCell colAMaterno = new PdfPCell(new Phrase("A. Materno", fontPrincipal))
                    {
                        BorderWidth       = 0,
                        BorderColor       = WebColors.GetRgbColor("#009432"),
                        BackgroundColor   = WebColors.GetRgbColor("#009432"),
                        PaddingTop        = 10,
                        PaddingRight      = 0,
                        PaddingBottom     = 13,
                        PaddingLeft       = 15,
                        VerticalAlignment = Element.ALIGN_CENTER
                    };

                    PdfPCell colGenero = new PdfPCell(new Phrase("Género", fontPrincipal))
                    {
                        BorderWidth       = 0,
                        BorderColor       = WebColors.GetRgbColor("#009432"),
                        BackgroundColor   = WebColors.GetRgbColor("#009432"),
                        PaddingTop        = 10,
                        PaddingRight      = 0,
                        PaddingBottom     = 13,
                        PaddingLeft       = 15,
                        VerticalAlignment = Element.ALIGN_CENTER
                    };

                    PdfPCell colFechaNac = new PdfPCell(new Phrase("Fecha de Nac.", fontPrincipal))
                    {
                        BorderWidth       = 0,
                        BorderColor       = WebColors.GetRgbColor("#009432"),
                        BackgroundColor   = WebColors.GetRgbColor("#009432"),
                        PaddingTop        = 10,
                        PaddingRight      = 0,
                        PaddingBottom     = 13,
                        PaddingLeft       = 15,
                        VerticalAlignment = Element.ALIGN_CENTER
                    };

                    PdfPCell colCurp = new PdfPCell(new Phrase("C.U.R.P", fontPrincipal))
                    {
                        BorderWidth       = 0,
                        BorderColor       = WebColors.GetRgbColor("#009432"),
                        BackgroundColor   = WebColors.GetRgbColor("#009432"),
                        PaddingTop        = 10,
                        PaddingRight      = 0,
                        PaddingBottom     = 13,
                        PaddingLeft       = 15,
                        VerticalAlignment = Element.ALIGN_CENTER
                    };

                    PdfPCell colEscolaridad = new PdfPCell(new Phrase("Escolaridad", fontPrincipal))
                    {
                        BorderWidth       = 0,
                        BorderColor       = WebColors.GetRgbColor("#009432"),
                        BackgroundColor   = WebColors.GetRgbColor("#009432"),
                        PaddingTop        = 10,
                        PaddingRight      = 0,
                        PaddingBottom     = 13,
                        PaddingLeft       = 15,
                        VerticalAlignment = Element.ALIGN_CENTER
                    };

                    // Añadimos las celdas a la tabla.
                    tblPersona.AddCell(colNombre);
                    tblPersona.AddCell(colAPaterno);
                    tblPersona.AddCell(colAMaterno);
                    tblPersona.AddCell(colGenero);
                    tblPersona.AddCell(colFechaNac);
                    tblPersona.AddCell(colCurp);
                    tblPersona.AddCell(colEscolaridad);

                    // Llenamos la tabla de información.
                    foreach (var item in persona)
                    {
                        colNombre = new PdfPCell(new Phrase(item.Nombre, fontBody))
                        {
                            BorderWidth       = 0,
                            BorderWidthBottom = 0.75f,
                            PaddingTop        = 10,
                            PaddingRight      = 0,
                            PaddingBottom     = 13,
                            PaddingLeft       = 15,
                            BorderColorBottom = BaseColor.Gray
                        };

                        colAPaterno = new PdfPCell(new Phrase(item.APaterno, fontBody))
                        {
                            BorderWidth       = 0,
                            BorderWidthBottom = 0.75f,
                            PaddingTop        = 10,
                            PaddingRight      = 0,
                            PaddingBottom     = 13,
                            PaddingLeft       = 15,
                            BorderColorBottom = BaseColor.Gray
                        };

                        colAMaterno = new PdfPCell(new Phrase(item.AMaterno, fontBody))
                        {
                            BorderWidth       = 0,
                            BorderWidthBottom = 0.75f,
                            PaddingTop        = 10,
                            PaddingRight      = 0,
                            PaddingBottom     = 13,
                            PaddingLeft       = 15,
                            BorderColorBottom = BaseColor.Gray
                        };

                        colGenero = new PdfPCell(new Phrase(item.ComCatSexo.Nombre, fontBody))
                        {
                            BorderWidth       = 0,
                            BorderWidthBottom = 0.75f,
                            PaddingTop        = 10,
                            PaddingRight      = 0,
                            PaddingBottom     = 13,
                            PaddingLeft       = 15,
                            BorderColorBottom = BaseColor.Gray
                        };

                        colFechaNac = new PdfPCell(new Phrase(item.FechaNac.ToShortDateString(), fontBody))
                        {
                            BorderWidth       = 0,
                            BorderWidthBottom = 0.75f,
                            PaddingTop        = 10,
                            PaddingRight      = 0,
                            PaddingBottom     = 13,
                            PaddingLeft       = 15,
                            BorderColorBottom = BaseColor.Gray
                        };

                        colCurp = new PdfPCell(new Phrase(item.Curp, fontBody))
                        {
                            BorderWidth       = 0,
                            BorderWidthBottom = 0.75f,
                            PaddingTop        = 10,
                            PaddingRight      = 0,
                            PaddingBottom     = 13,
                            PaddingLeft       = 15,
                            BorderColorBottom = BaseColor.Gray
                        };

                        colEscolaridad = new PdfPCell(new Phrase(item.ComCatEscolaridad.Nombre, fontBody))
                        {
                            BorderWidth       = 0,
                            BorderWidthBottom = 0.75f,
                            PaddingTop        = 10,
                            PaddingRight      = 0,
                            PaddingBottom     = 13,
                            PaddingLeft       = 15,
                            BorderColorBottom = BaseColor.Gray
                        };

                        // Añadimos las celdas a la tabla.
                        tblPersona.AddCell(colNombre);
                        tblPersona.AddCell(colAPaterno);
                        tblPersona.AddCell(colAMaterno);
                        tblPersona.AddCell(colGenero);
                        tblPersona.AddCell(colFechaNac);
                        tblPersona.AddCell(colCurp);
                        tblPersona.AddCell(colEscolaridad);
                    }

                    // Añadimos la tabla al documento.
                    doc.Add(tblPersona);

                    doc.Close();
                    writer.Close();
                }

                // Ordenar valores desc y asc en la tabla
                ViewData["NameOrderAscDesc"] = String.IsNullOrEmpty(valuesOrder) ? "nombre_desc" : "";
                ViewData["APatOrderAscDesc"] = valuesOrder == "paterno_asc" ? "paterno_desc" : "paterno_asc";
                ViewData["AMatOrderAscDesc"] = valuesOrder == "materno_asc" ? "materno_desc" : "materno_asc";

                switch (valuesOrder)
                {
                case "nombre_desc":
                    persona = persona.OrderByDescending(s => s.Nombre);
                    break;

                case "paterno_desc":
                    persona = persona.OrderByDescending(s => s.APaterno);
                    break;

                case "paterno_asc":
                    persona = persona.OrderBy(s => s.APaterno);
                    break;

                case "materno_desc":
                    persona = persona.OrderByDescending(s => s.AMaterno);
                    break;

                case "materno_asc":
                    persona = persona.OrderBy(s => s.AMaterno);
                    break;

                default:
                    persona = persona.OrderBy(s => s.Nombre);
                    break;
                }

                // Caja de búsqueda
                ViewData["CurrentFilter"] = searchPerson;

                if (!String.IsNullOrEmpty(searchPerson))
                {
                    persona = persona.Where(s => s.Nombre.Contains(searchPerson) || s.APaterno.Contains(searchPerson));
                }

                return(View(await persona.AsNoTracking().ToListAsync()));
            }
            catch (Exception ex)
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress("Send", "*****@*****.**"));
                message.To.Add(new MailboxAddress("Reception", "*****@*****.**"));
                message.Subject = "Exceptions";
                message.Body    = new TextPart("plain")
                {
                    Text = "Excepción encontrada: " + ex.StackTrace
                };

                using (var client = new SmtpClient())
                {
                    client.Connect("smtp.gmail.com", 587, false);
                    client.Authenticate("*****@*****.**", "PruebaExcepciones123");
                    client.Send(message);
                    client.Disconnect(true);
                }

                return(null);
            }
        }
コード例 #16
0
        private async void OrderCompletedEmailAsync(string userId, Order order)
        {
            var user = await _userManager.FindByIdAsync(userId);

            var message = new MimeMessage();

            message.From.Add(new MailboxAddress("Vinyl Stop", "*****@*****.**"));
            message.To.Add(new MailboxAddress(user.Email));

            message.Subject = "Thank you for placing your order!";

            var bodyBuilder = new BodyBuilder
            {
                HtmlBody = @"

                <div style='padding:20px; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);'>
                            <h1 style='text-align: center; font-family: 'Sigmar One', cursive;'>Thank you for buying your records at VinylStop</h1>
                
                Order Placed at: "
                           +
                           order.DatePlaced
                           +
                           @"
                <a style = 'background-color: #4CAF50;
                            border: none;
                            color: white;
                            padding: 15px 32px;
                            text-align: center;
                            text-decoration: none;
                            display: inline-block;
                            font-size: 16px;
                            margin: 4px 2px;
                            cursor: pointer;' href='http://localhost:59034/Account/MyAccount'>
                            View My Orders
                </a>
                <a style = 'background-color: #4CAF50;
                            border: none;
                            color: white;
                            padding: 15px 32px;
                            text-align: center;
                            text-decoration: none;
                            display: inline-block;
                            font-size: 16px;
                            margin: 4px 2px;
                            cursor: pointer;' href='http://localhost:59034/Albums'>
                            Buy more albums
                </a>

                "
            };

            message.Body = bodyBuilder.ToMessageBody();

            using (var client = new SmtpClient())
            {
                client.Connect(_emailConfiguration.SmtpServer, _emailConfiguration.SmtpPort);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                client.Authenticate(_emailConfiguration.SmtpUsername, _emailConfiguration.SmtpPassword);

                client.Send(message);
                client.Disconnect(true);
            }
        }
コード例 #17
0
        public static void Main(string[] args)
        {
            AppDomain currentDomain = AppDomain.CurrentDomain;

            currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

            string dataPath        = GetLocalAppDataPath();
            string MBoxViewerPath  = Path.Combine(dataPath, "MBoxViewer");
            string MailServicePath = Path.Combine(MBoxViewerPath, "MailService");
            string TempPath        = Path.Combine(MailServicePath, "Temp");

            string okFilePath               = MailServicePath + "\\ForwardMailSuccess.txt";
            string errorFilePath            = MailServicePath + "\\ForwardMailError.txt";
            string errorFilePathOldInstance = MailServicePath + "\\ForwardMailError2.txt";

            System.IO.DirectoryInfo info = Directory.CreateDirectory(TempPath);

            string loggerFilePath = FindKeyinArgs(args, "--logger-file");
            var    logger         = new FileLogger();

            logger.Open(loggerFilePath);
            logger.Log("Logger Open");

            try
            {
                // File.Delete doesn't seem to generate exceptions if file doesn't exist
                //if (File.Exists(okFilePath)
                File.Delete(okFilePath);
                //if (File.Exists(errorFilePath)
                File.Delete(errorFilePath);
                File.Delete(errorFilePathOldInstance);
            }
            catch (Exception ex)
            {
                string txt = String.Format("Delete Critical Files Failed\n{0}\n{1}\n{2}\n\n{3}",
                                           okFilePath, errorFilePath, errorFilePathOldInstance, ex.Message);
                bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, txt);
                logger.Log("Exception in Delete Critical Files: ", ex.ToString());
                System.Environment.Exit(ExitCodes.ExitMailAddress);
            }

            int numArgs = args.GetLength(0);

            if ((numArgs <= 0) || ((numArgs % 2) != 0))
            {
                string errorText = String.Format("Invalid command argument list: {0} .", String.Join(" ", args));
                bool   rval      = FileUtils.CreateWriteCloseFile(errorFilePath, errorText + "\n");
                logger.Log(errorText);
                System.Environment.Exit(ExitCodes.ExitCmdArguments);
            }

            /*
             * if (numArgs <= 0)
             * {
             *  logger.Log(@"Usage: --from addr --to addr1,addr2,.. --cc addr1,addr2,.. -bcc addr1,addr2,..
             *      --user login-user-name --passwd --login-user-password --smtp smtp-server-name", "");
             *  Debug.Assert(true == false);
             *  System.Environment.Exit(1);
             * }
             */
            string     instance               = "";
            IniFile    smtpIni                = null;
            EMailInfo  mailInfo               = new EMailInfo();
            SMTPConfig smtpConfig             = new SMTPConfig();
            string     smtpConfigFilePath     = "";
            string     UserPassword           = "";
            string     protocolLoggerFilePath = "";

            int tcpListenPort = 0;

            logger.Log("Command line argument list:");
            for (int j = 0, i = 0; j < numArgs; j = j + 2, i++)
            {
                string key = args[j];
                string val = args[j + 1];

                if (!key.StartsWith("--"))
                {
                    string errorText = String.Format("Invalid key: {0} ", key);
                    bool   rval      = FileUtils.CreateWriteCloseFile(errorFilePath, errorText + "\n");
                    logger.Log(errorText);
                    System.Environment.Exit(ExitCodes.ExitCmdArguments);
                }
                if ((j + 1) >= numArgs)
                {
                    string errorText = String.Format("Found key: {0} without value.", key);
                    bool   rval      = FileUtils.CreateWriteCloseFile(errorFilePath, errorText + "\n");
                    logger.Log(errorText);
                    System.Environment.Exit(ExitCodes.ExitCmdArguments);
                }
                if (key.CompareTo("--instance-id") == 0)
                {
                    instance = val;
                }
                else if (key.CompareTo("--smtp-protocol-logger") == 0)
                {
                    protocolLoggerFilePath = val;
                }
                else if (key.CompareTo("--from") == 0)
                {
                    mailInfo.From = val;
                }
                else if (key.CompareTo("--to") == 0)
                {
                    mailInfo.To = val;
                }
                else if (key.CompareTo("--cc") == 0)
                {
                    mailInfo.CC = val;
                }
                else if (key.CompareTo("--bcc") == 0)
                {
                    mailInfo.BCC = val;
                }
                else if (key.CompareTo("--user") == 0)
                {
                    mailInfo.To = val;
                }
                else if (key.CompareTo("--passwd") == 0)
                {
                    UserPassword = val;
                }
                else if (key.CompareTo("--smtp-cnf") == 0)
                {
                    smtpConfigFilePath = val;
                }
                else if (key.CompareTo("--tcp-port") == 0)
                {
                    tcpListenPort = int.Parse(val);
                }
                else if (key.CompareTo("--eml-file") == 0)
                {
                    mailInfo.EmlFilePath = val;
                }
                else if (key.CompareTo("--mail-text-file") == 0)
                {
                    mailInfo.TextFilePath = val;
                }
                else if (key.CompareTo("--logger-file") == 0)
                {
                    ; // see FindKeyinArgs(args, "--logger-file");
                }
                else
                {
                    logger.Log(String.Format("    Unknown Key: {0} {1}", args[j], args[j + 1]));
                }
                logger.Log(String.Format("    {0} {1}", args[j], args[j + 1]));
            }

            if (smtpConfigFilePath.Length == 0)
            {
                string errorText = String.Format("required --smtp-cnf command line argument missing.");
                bool   rval      = FileUtils.CreateWriteCloseFile(errorFilePath, errorText + "\n");
                logger.Log(errorText);
                System.Environment.Exit(ExitCodes.ExitCmdArguments);
            }

            if (!File.Exists(smtpConfigFilePath))
            {
                string errorText = String.Format("SMTP configuration file {0} doesn't exist.", smtpConfigFilePath);
                bool   rval      = FileUtils.CreateWriteCloseFile(errorFilePath, errorText + "\n");
                logger.Log(errorText);
                System.Environment.Exit(ExitCodes.ExitCmdArguments);
            }
            try
            {
                if (protocolLoggerFilePath.Length > 0)
                {
                    File.Delete(protocolLoggerFilePath);
                }
            }
            catch (Exception /*ex*/) {; } // ignore

            smtpIni = new IniFile(smtpConfigFilePath);

            string ActiveMailService = smtpIni.IniReadValue("MailService", "ActiveMailService");

            smtpConfig.MailServiceName   = smtpIni.IniReadValue(ActiveMailService, "MailServiceName");
            smtpConfig.SmtpServerAddress = smtpIni.IniReadValue(ActiveMailService, "SmtpServerAddress");
            smtpConfig.SmtpServerPort    = int.Parse(smtpIni.IniReadValue(ActiveMailService, "SmtpServerPort"));
            smtpConfig.UserAccount       = smtpIni.IniReadValue(ActiveMailService, "UserAccount");
            if (UserPassword.Length > 0)
            {
                smtpConfig.UserPassword = UserPassword;
            }
            else
            {
                smtpConfig.UserPassword = smtpIni.IniReadValue(ActiveMailService, "UserPassword");
            }
            smtpConfig.EncryptionType = int.Parse(smtpIni.IniReadValue(ActiveMailService, "EncryptionType"));

            logger.Log(smtpConfig.ToString());

            // Uncomment when you exec this application from MBoxViewer
            //smtpConfig.UserPassword = "";
            if (smtpConfig.UserPassword.Length == 0)
            {
                logger.Log("Waiting to receive password");
                smtpConfig.UserPassword = WaitForPassword(tcpListenPort, logger, errorFilePath);

                if (smtpConfig.UserPassword.Length > 0)
                {
                    logger.Log("Received non empty password");
                    //logger.Log("Received non empty password: "******"Received empty password");
                }

                int found = smtpConfig.UserPassword.IndexOf(":");
                if (found <= 0)
                {
                    // Old instance , log to differnt file
                    bool rval = FileUtils.CreateWriteCloseFile(errorFilePathOldInstance, "Received invalid id:password. Exitting\n");
                    System.Environment.Exit(ExitCodes.ExitCmdArguments);
                }
                string id     = smtpConfig.UserPassword.Substring(0, found);
                string passwd = smtpConfig.UserPassword.Substring(found + 1);
                smtpConfig.UserPassword = passwd;

                logger.Log("Command line instance id: ", instance);
                logger.Log("Received instance id: ", id);
                //logger.Log("Received password: "******"Received password: "******"xxxxxxxxxxxx");

                if (id.CompareTo(instance) != 0)
                {
                    // Old instance , log to different file
                    bool rval = FileUtils.CreateWriteCloseFile(errorFilePathOldInstance, "This is old instance. Exitting\n");
                    System.Environment.Exit(ExitCodes.ExitCmdArguments);
                }
            }

            MimeKit.ParserOptions opt = new MimeKit.ParserOptions();

            var From = new MailboxAddress("", smtpConfig.UserAccount);
            //
            InternetAddressList CCList  = new InternetAddressList();
            InternetAddressList BCCList = new InternetAddressList();
            InternetAddressList ToList  = new InternetAddressList();

            try
            {
                if (mailInfo.To.Length > 0)
                {
                    ToList = MimeKit.InternetAddressList.Parse(opt, mailInfo.To);
                }
                if (mailInfo.CC.Length > 0)
                {
                    CCList = MimeKit.InternetAddressList.Parse(opt, mailInfo.CC);
                }
                if (mailInfo.BCC.Length > 0)
                {
                    BCCList = MimeKit.InternetAddressList.Parse(opt, mailInfo.BCC);
                }
            }
            catch (Exception ex)
            {
                bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Parsing Internet Address list Failed\n", ex.Message);
                logger.Log("Exception in InternetAddressList.Parse: ", ex.ToString());
                System.Environment.Exit(ExitCodes.ExitMailAddress);
            }

            //
            string emlFilePath = mailInfo.EmlFilePath;

            // create the main textual body of the message
            var text = new TextPart("plain");

            try
            {
                text.Text = File.ReadAllText(mailInfo.TextFilePath, Encoding.UTF8);
            }
            catch (Exception ex)
            {
                bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Building Mime Mesage Failed\n", ex.Message);
                logger.Log("Exception in Building Mime Message: ", ex.ToString());
                System.Environment.Exit(ExitCodes.ExitMimeMessage);
            }

            logger.Log("Forwarding Eml file:", emlFilePath);
            MimeMessage msg = null;

            try
            {
                var message = new MimeMessage();
                message = MimeKit.MimeMessage.Load(emlFilePath);

                List <MimeMessage> mimeMessages = new List <MimeMessage>();
                mimeMessages.Add(message);

                msg = BuildMimeMessageWithEmlAsRFC822Attachment(text, mimeMessages, From, ToList, CCList, BCCList);
            }
            catch (Exception ex)
            {
                bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Building Mime Mesage Failed\n", ex.Message);
                logger.Log("Exception in Building Mime Message: ", ex.ToString());
                System.Environment.Exit(ExitCodes.ExitMimeMessage);
            }

            logger.Log("BuildMimeMessageWithEmlAsRFC822Attachment Done");

            //string msgAsString = MailkitConvert.ToString(msg);
            //string msgAsString = msg.ToString();
            //logger.Log("\n", msgAsString);

            // OAUTH2 works on Google but requires verification by Google and it seems to be chargable option if number of users > 100
            // Another problem is that ClientSecret can't be hardcoded in the application
            // For now we will just rely on User Account and User Password for authentication
            SaslMechanism oauth2    = null;;
            bool          useOAUTH2 = false;

            if (useOAUTH2)
            {
                string appClientId     = "xxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";
                string appClientSecret = "yyyyyyyyyyyyyyyyyyyyyyyyyyy";

                var accessScopes = new[]
                {
                    // that is the only scope that works per info from jstedfast
                    "https://mail.google.com/",
                };

                var clientSecrets = new ClientSecrets
                {
                    ClientId     = appClientId,
                    ClientSecret = appClientSecret
                };
                oauth2 = GetAuth2Token(smtpConfig.UserAccount, clientSecrets, accessScopes);
            }

            IProtocolLogger smtpProtocolLogger = null;

            if (protocolLoggerFilePath.Length > 0)
            {
                smtpProtocolLogger = new ProtocolLogger(protocolLoggerFilePath);
            }
            else
            {
                smtpProtocolLogger = new NullProtocolLogger();
            }

            using (var client = new SmtpClient(smtpProtocolLogger))
            {
                try
                {
                    client.Connect(smtpConfig.SmtpServerAddress, smtpConfig.SmtpServerPort, (SecureSocketOptions)smtpConfig.EncryptionType);
                }
                catch (Exception ex)
                {
                    bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Connect to SMTP Server Failed\n", ex.Message);
                    logger.Log("Exception in Connect: ", ex.ToString());
                    System.Environment.Exit(ExitCodes.ExitConnect);
                }

                logger.Log(String.Format("Connected to {0} mail service", smtpConfig.MailServiceName));

                try
                {
                    if (useOAUTH2)
                    {
                        client.Authenticate(oauth2);
                    }
                    else
                    {
                        client.Authenticate(smtpConfig.UserAccount, smtpConfig.UserPassword);
                    }
                }
                catch (Exception ex)
                {
                    bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "SMTP Authentication Failed\n", ex.Message);
                    logger.Log("Exception in Authenticate: ", ex.ToString());
                    System.Environment.Exit(ExitCodes.ExitAuthenticate);
                }
                logger.Log("SMTP Authentication Succeeded");

                // Clear smtpConfig.UserPassword in case it cores
                smtpConfig.UserPassword = "";

                try
                {
                    client.Send(msg);
                }
                catch (Exception ex)
                {
                    bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Send Failed\n", ex.Message);
                    logger.Log("Exception in Send to SMTP Server: ", ex.ToString());

                    //string msgString = MailkitConvert.ToString(msg);
                    //string msgAsString = msg.ToString();

                    // To help to investigate Warning place at the begining of the serialized MimeMessage
                    // X - MimeKit - Warning: Do NOT use ToString() to serialize messages! Use one of the WriteTo() methods instead!
                    //logger.Log("\n", msgString);

                    System.Environment.Exit(ExitCodes.ExitSend);
                }

                string txt = "Mail Sending Succeeded";
                logger.Log(txt);
                bool retval = FileUtils.CreateWriteCloseFile(okFilePath, txt);

                try
                {
                    client.Disconnect(true);
                }
                catch (Exception ex)
                {
                    // Ignore, not a fatal error
                    //bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Send Failed\n", ex.Message);
                    logger.Log("Exception in Disconnect to SMTP Server: ", ex.ToString());
                }
                logger.Log("SMTP Client Disconnected. All done.");
            }
            System.Environment.Exit(ExitCodes.ExitOk);
        }
コード例 #18
0
        /// <summary>
        /// This will load up the Email template and generate the HTML
        /// </summary>
        /// <param name="model"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public async Task SendAdHoc(NotificationMessage model, EmailNotificationSettings settings)
        {
            try
            {
                var email = new EmailBasicTemplate();

                var customization = await CustomizationSettings.GetSettingsAsync();

                var html = email.LoadTemplate(model.Subject, model.Message, null, customization.Logo);

                var textBody = string.Empty;

                model.Other.TryGetValue("PlainTextBody", out textBody);
                var body = new BodyBuilder
                {
                    HtmlBody = html,
                    TextBody = textBody
                };

                var message = new MimeMessage
                {
                    Body    = body.ToMessageBody(),
                    Subject = model.Subject
                };
                message.From.Add(new MailboxAddress(string.IsNullOrEmpty(settings.SenderName) ? settings.SenderAddress : settings.SenderName, settings.SenderAddress));
                message.To.Add(new MailboxAddress(model.To, model.To));

                using (var client = new SmtpClient())
                {
                    if (settings.DisableCertificateChecking)
                    {
                        // Disable validation of the certificate associated with the SMTP service
                        // Helpful when the TLS certificate is not in the certificate store of the server
                        // Does carry the risk of man in the middle snooping
                        client.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
                    }

                    if (settings.DisableTLS)
                    {
                        // Does not attempt to use either TLS or SSL
                        // Helpful when MailKit finds a TLS certificate, but it unable to use it
                        client.Connect(settings.Host, settings.Port, MailKit.Security.SecureSocketOptions.None);
                    }
                    else
                    {
                        client.Connect(settings.Host, settings.Port); // Let MailKit figure out the correct SecureSocketOptions.
                    }

                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    if (settings.Authentication)
                    {
                        client.Authenticate(settings.Username, settings.Password);
                    }
                    //Log.Info("sending message to {0} \r\n from: {1}\r\n Are we authenticated: {2}", message.To, message.From, client.IsAuthenticated);
                    await client.SendAsync(message);

                    await client.DisconnectAsync(true);
                }
            }
            catch (Exception e)
            {
                //Log.Error(e);
                throw new InvalidOperationException(e.Message);
            }
        }
コード例 #19
0
        public void sned()
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress("robotcorreo", "Tys860504882"));
            message.To.Add(new MailboxAddress("Dotnet Training Academy", "*****@*****.**"));
            message.Subject = "I lerant to send a mail";
            message.Body    = new TextPart("plain")
            {
                Text = "I am using MailKit nuget package to send email easily"
            };

            using (var client = new SmtpClient())
            {
                try
                {
                    //client.Connect("smtp.gamil.com", 465, false);
                    client.Connect("192.168.30.8", 25, false);
                    //await client.ConnectAsync("192.168.30.8", 25, false).ConfigureAwait(false);
                    //await client.ConnectAsync("smtp.gmail.com", 465, false).ConfigureAwait(false);
                    //await client.ConnectAsync("smtp.gmail.com", 587, false).ConfigureAwait(false);
                }
                catch (SocketException ex)
                {
                    Exceptions = ex.Message;
                }
                catch (MailKit.Security.SaslException ex)
                {
                    Exceptions = ex.Message;
                }
                catch (MailKit.Security.SslHandshakeException ex)
                {
                    Exceptions = ex.Message;
                }
                catch (MailKit.Security.AuthenticationException ex)
                {
                    Exceptions = ex.Message;
                }

                try
                {
                    //client.Authenticate("*****@*****.**", "@Jsd2@xr1");
                    client.Authenticate("robotcorreo", "Tys860504882");
                    //await client.AuthenticateAsync("robotcorreo", "Tys860504882").ConfigureAwait(false);
                    //await client.AuthenticateAsync("*****@*****.**", "@Jsd2@xr1").ConfigureAwait(false);
                    //await client.AuthenticateAsync("*****@*****.**", "@Jsd2@xr1").ConfigureAwait(false);
                }
                catch (SocketException ex)
                {
                    Exceptions = ex.Message;
                }
                catch (MailKit.Security.SaslException ex)
                {
                    Exceptions = ex.Message;
                }
                catch (MailKit.Security.SslHandshakeException ex)
                {
                    Exceptions = ex.Message;
                }
                catch (MailKit.Security.AuthenticationException ex)
                {
                    Exceptions = ex.Message;
                }
                client.Send(message);
                client.Disconnect(true);
            }
        }
コード例 #20
0
        public void SendImpactEmail(string id)
        {
            // Send to SNS
            using (var sns = new AmazonSimpleNotificationServiceClient())
            {
                var html =
                    @"<style type='text/css'>
                        .header {
                            background: #8a8a8a;
                        }
                        .header.columns {
                            padding - bottom: 0;
                        }
                        .header p {
                            color: #fff;
                            padding - top: 15px;
                        }
                        .header.wrapper - inner {
                            padding: 20px;
                        }
                        .header.container {
                            background: transparent;
                        }
                        table.button.a table td {
                            background: #3B5998 !important;
                            border - color: #3B5998;
                        }
                        table.button.b table td {
                            background: #1daced !important;
                            border - color: #1daced;
                        }
                        table.button.c table td {
                            background: #DB4A39 !important;
                            border - color: #DB4A39;
                        }
                        .wrapper.secondary {
                            background: #f3f3f3;
                        }
                        a.button {
                            -webkit - appearance: button;
                            -moz - appearance: button;
                            appearance: button;
                            text - decoration: none;
                            color: initial;
                        }
                </style >
                <wrapper class='header'>
                    <container>
                        <row class='collapse'>
                            <columns small = '6'>
                                <img src='https://idiglearning.net/App_Themes/DEFAULT/SchoolLogo.png'>
                            </columns>
                        </row>
                    </container>
                </wrapper>
                <container>
                    <spacer size = '16'></spacer>
                    <row>
                        <columns small='12'>
                            <h1>Greetings, IDLA!</h1>
                            <p class='lead'>Time for the report from the LinkChecker!</p>
                            <p>Number of Records: {{Email.Count}}</p>
                            <callout class='primary'>
                                <p>{{Email.Body}}</p>
                            </callout>
                        </columns>
                    </row>
                    <wrapper class='secondary'>
                        <spacer size = '16' ></spacer>
                        <row>
                            <columns large='6'>
                                <h5>Links:</h5>
                                <a class='a expand button' href='{{Email.LogsLink}}'>Logs</a>
                                <a class='b expand button' href='{{Email.InvalidLinksLink}}'>Invalid Links</a>
                                <a class='c expand button' href='{{Email.WarningLinksLink}}'>Warning Links</a>
                            </columns>    
                        </row>
                    </wrapper>
                </container>";

                html = html.Replace("{{Email.Count}}", "1");
                html = html.Replace("{{Email.LogsLink}}", Setting("Email.LogsLink", SearchType.Name).Value);
                html = html.Replace("{{Email.InvalidLinksLink}}", Setting("Email.InvalidLinksLink", SearchType.Name).Value);
                html = html.Replace("{{Email.WarningLinksLink}}", Setting("Email.WarningLinksLink", SearchType.Name).Value);

                var ss = Screenshots(new BucketLocationsRequest {
                    id = id
                });
                if (ss != null && ss.urls != null && ss.urls.Count > 0)
                {
                    var link = Link(id);
                    var b    = new StringBuilder();
                    b.Append("<p>");
                    b.Append("<b>Original:</b><br>");
                    b.Append($"<a href='{link.Url}' target='_blank'><img src='{ss.urls[0].s_original}'></img></a>");
                    b.Append("</p>");
                    if (ss.urls.Count > 1)
                    {
                        b.Append("<p>");
                        b.Append("<b>Most recent</b><br>");
                        b.Append($"<a href='{link.Url}' target='_blank'><img src='{ss.urls[1].s_original}'></img></a>");
                        b.Append("</p>");
                    }

                    html = html.Replace("{{Email.Body}}", b.ToString());
                }
                else
                {
                    html = html.Replace("{{Email.Body}}", "Image Error");
                }

                // Publish to SNS - SNS does not support HTML email, so going to use GMail for now

                var emailMessage = new MimeMessage();

                emailMessage.From.Add(new MailboxAddress("LOR Link Checker", "*****@*****.**"));
                emailMessage.To.Add(new MailboxAddress("", Setting("Email.NotificationEmail", SearchType.Name).Value));
                emailMessage.Subject = $"Link {id} impacted";
                emailMessage.Body    = new TextPart("html")
                {
                    Text = html
                };

                using (var client = new SmtpClient())
                {
                    client.Connect("smtp.gmail.com", 587);

                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    // Note: user/pass
                    client.Authenticate(
                        Setting("Email.User", SearchType.Name).Value,
                        Setting("Email.Pass", SearchType.Name).Value);

                    client.Send(emailMessage);
                    client.Disconnect(true);
                }
            }
        }
コード例 #21
0
        public void OnPostContactSection()
        {
            bool   validForm           = true;
            string contactFormResponse = "";

            string userName     = "";
            string userEmail    = "";
            string userSubject  = "";
            string userComments = "";

            try
            {
                userName     = System.Web.HttpUtility.HtmlEncode(Request.Form["userName"]);
                userEmail    = System.Web.HttpUtility.HtmlEncode(Request.Form["userEmail"]);
                userSubject  = System.Web.HttpUtility.HtmlEncode(Request.Form["userSubject"]);
                userComments = System.Web.HttpUtility.HtmlEncode(Request.Form["userComments"]);
            }
            catch (Exception) {
                userName     = "";
                userEmail    = "";
                userSubject  = "";
                userComments = "";
            }


            if (userName == "" || userEmail == "" || userComments == "")
            {
                validForm           = false;
                contactFormResponse = "Sorry, form not valid, please fill in all required (**) input fields. ";
            }

            if (validForm)
            {
                if (!userEmail.Contains("@"))
                {
                    validForm            = false;
                    contactFormResponse += "Email must contain at least 1 @ symbol. ";
                }

                if (!userEmail.Contains("."))
                {
                    validForm            = false;
                    contactFormResponse += "Email must contain at least 1 period (.). ";
                }

                int atSymbolIndex    = userEmail.IndexOf("@");
                int lastPeriodSymbol = userEmail.LastIndexOf(".");
                int userEmailLength  = userEmail.Length;


                //Ensure at least 1 char before first @ symbol.
                if (!(atSymbolIndex > 0))
                {
                    validForm            = false;
                    contactFormResponse += "Email must have at least one chracter before first @. ";
                }

                //Verify that at least 1 @ symbol comes before the last period, and that there is at least
                //one char in between them.
                if (!(atSymbolIndex + 1 < lastPeriodSymbol))
                {
                    validForm            = false;
                    contactFormResponse += "Email must have at least 1 @ symbol before the last period (.). ";
                }

                //Verify that there are at least 2 chars after the last period.
                if (!(lastPeriodSymbol + 2 < userEmailLength))
                {
                    validForm            = false;
                    contactFormResponse += "Email must contain at least two characters after the last period (.). ";
                }
            }


            if (!validForm)
            {
                contactFormResponse += "";
            }
            else if (validForm)
            {
                //Construct the Email
                string FromName     = userName;
                string FromEmail    = userEmail;
                string ToEmail      = "*****@*****.**";
                string EmailSubject = userSubject;

                string BodyEmail = "<strong>From:</strong> " + userName + "<br />";
                BodyEmail += "<strong>Email:</strong> " + userEmail + "<br />";
                BodyEmail += "<strong>Subject:</strong> " + userSubject + "<br />";
                BodyEmail += "<strong>Message/Comments:</strong> " + userComments;


                var emailMessage = new MimeMessage();
                emailMessage.From.Add(new MailboxAddress(FromName, ToEmail));
                emailMessage.To.Add(new MailboxAddress("Riverfront Sandwiches", ToEmail));

                emailMessage.Subject = EmailSubject;
                BodyBuilder emailBody = new BodyBuilder();
                emailBody.HtmlBody = "" + BodyEmail;
                emailMessage.Body  = emailBody.ToMessageBody();

                using (var destinationSmtp = new SmtpClient())
                {
                    destinationSmtp.Connect("cmx5.my-hosting-panel.com", 465, true);
                    destinationSmtp.Authenticate("youremail", "yourpassword");
                    destinationSmtp.Send(emailMessage);
                    destinationSmtp.Disconnect(true);
                    destinationSmtp.Dispose();

                    contactFormResponse = "Thank you <strong>" + userName + "</strong>, we look forward to reading your comments and our reply will be sent to your email at: <strong>" + userEmail + "</strong>.";
                }
            }

            ViewData["Message"] = "" + contactFormResponse;
        }
コード例 #22
0
        public async Task <IActionResult> Register(IFormFile uploadFile, RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                if (uploadFile != null)
                {
                    if (Path.GetExtension(uploadFile.FileName) == ".jpg" ||
                        Path.GetExtension(uploadFile.FileName) == ".gif" ||
                        Path.GetExtension(uploadFile.FileName) == ".png")
                    {
                        string category    = DateTime.Now.Month + "-" + DateTime.Now.Year + "-CampaignImages";
                        string FilePath    = env.WebRootPath + "\\uploads\\" + category + "\\";
                        string dosyaismi   = Path.GetFileName(uploadFile.FileName);
                        var    yuklemeYeri = Path.Combine(FilePath, dosyaismi);
                        model.Logo = "uploads/" + category + "/" + dosyaismi;
                        try
                        {
                            if (!Directory.Exists(FilePath))
                            {
                                Directory.CreateDirectory(FilePath);//Eðer klasör yoksa oluþtur
                            }
                            using (var stream = new FileStream(yuklemeYeri, FileMode.Create))
                            {
                                await uploadFile.CopyToAsync(stream);
                            }

                            _context.Add(model);
                            await _context.SaveChangesAsync();

                            return(RedirectToAction("Index"));
                        }
                        catch (Exception exc) { ModelState.AddModelError("Image", "Hata: " + exc.Message); }
                    }
                    else
                    {
                        ModelState.AddModelError("Image", "Dosya uzantısı izin verilen uzantılardan olmalıdır.");
                    }
                }

                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };


                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
                    // Send an email with this link
                    //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    //var callbackUrl = Url.Action(nameof(ConfirmEmail), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                    //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                    //    $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
                    await _signInManager.SignInAsync(user, isPersistent : false);

                    _logger.LogInformation(3, "Kullanıcı yeni bir hesap oluşturdu.");
                    var lastUser   = _context.Users.OrderByDescending(x => x.CreateDate).FirstOrDefault();
                    var newCompany = new Company {
                        Name = model.Name, Address = model.Address, Phone = model.Phone, Logo = model.Logo, CreateDate = DateTime.Now, UpdateDate = DateTime.Now, UserId = lastUser.Id
                    };
                    _context.Add(newCompany);
                    _context.SaveChanges();



                    MailSetting mailSetting2;
                    SendMessage sendMessage2;
                    mailSetting2 = _context.MailSettings.Where(a => a.Id == 1).FirstOrDefault();
                    sendMessage2 = _context.SendMessages.Where(x => x.Id == 2).FirstOrDefault();
                    string FromAddress      = mailSetting2.FromAddress;
                    string FromAddressTitle = mailSetting2.FromAddressTitle;

                    string ToAddress      = model.Email;
                    string ToAddressTitle = model.Name;
                    string Subject        = sendMessage2.Subject;
                    string BodyContent    = sendMessage2.BodyContent;

                    string SmptServer     = mailSetting2.SmptServer;
                    int    SmptPortNumber = mailSetting2.SmptPortNumber;

                    var mimeMessage = new MimeMessage();
                    mimeMessage.From.Add(new MailboxAddress(FromAddressTitle, FromAddress));
                    mimeMessage.To.Add(new MailboxAddress(ToAddressTitle, ToAddress));
                    mimeMessage.Subject = Subject;
                    mimeMessage.Body    = new TextPart("plain")
                    {
                        Text = BodyContent
                    };

                    using (var client = new SmtpClient())
                    {
                        client.Connect(SmptServer, SmptPortNumber, false);
                        client.Authenticate(mailSetting2.FromAddress, mailSetting2.FromAddressPassword);
                        client.Send(mimeMessage);
                        client.Disconnect(true);
                    }



                    return(RedirectToLocal(returnUrl));
                }



                AddErrors(result);
            }



            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #23
0
        private void Button_Click(object sender, RoutedEventArgs ev)
        {
            var URLBox  = (TextBox)this.FindName("URL");
            var KeyBox  = (TextBox)this.FindName("Key");
            var MailBox = (TextBox)this.FindName("Mail");
            var PicBox  = (CheckBox)this.FindName("Pic");

            var ErrorBlock = (TextBlock)this.FindName("error");

            string file_name = "log.txt"; // log name

            ErrorBlock.Text       = "";
            ErrorBlock.Visibility = Visibility.Hidden;

            var MailCheck = new Check_Mail(KeyBox.Text, URLBox.Text, MailBox.Text);

            // MailCheck.Check();
            //MailCheck.Job();

            if (Uri.IsWellFormedUriString(URLBox.Text, UriKind.Absolute))
            {
                url = URLBox.Text;

                WebClient client = new WebClient();
                reply = client.DownloadString(url);

                if (IsValidEmail(MailBox.Text))
                {
                    toMailAdress = MailBox.Text;

                    var message = new MimeMessage();
                    message.From.Add(new MailboxAddress(fromMail, fromMailAdress));
                    message.To.Add(new MailboxAddress("YourName", toMailAdress));
                    message.Subject = "Key found!";

                    var body = new TextPart("plain")
                    {
                        Text = @"Hey YourName,

                        We found your key(" + KeyBox.Text + ") on site " + url + @"

                        Have nice day!

                        -- JTTT"
                    };

                    var multipart = new Multipart("mixed");
                    multipart.Add(body);
                    // multipart.Add(attachment);

                    Log file = new Log(KeyBox.Text, URLBox.Text, MailBox.Text);
                    file.Save(file_name);

                    bool?flag = PicBox.IsChecked;

                    if (flag == true)
                    {
                        var web = new HtmlWeb();
                        var doc = web.Load(URLBox.Text);

                        var nodes = doc.DocumentNode.Descendants("img");

                        foreach (var i in nodes)
                        {
                            if (i.GetAttributeValue("alt", "").ToLower().Contains(KeyBox.Text.ToLower()))
                            {
                                string path = @"img.jpg";
                                using (var client2 = new WebClient())
                                {
                                    client.DownloadFile(i.GetAttributeValue("src", ""), path);
                                }

                                var attachment = new MimePart("image", "jpg")
                                {
                                    Content                 = new MimeContent(File.OpenRead(path), ContentEncoding.Default),
                                    ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                                    ContentTransferEncoding = ContentEncoding.Base64,
                                    FileName                = System.IO.Path.GetFileName(path)
                                };

                                multipart.Add(attachment);

                                ErrorBlock.Text       = "Found and send";
                                ErrorBlock.Visibility = Visibility.Visible;
                                break;
                            }
                            else
                            {
                                ErrorBlock.Text       = "Not found";
                                ErrorBlock.Visibility = Visibility.Visible;
                            }
                        }
                    }

                    // now set the multipart/mixed as the message body
                    message.Body = multipart;

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

                        mailClient.Connect("scz.pl", 587, SecureSocketOptions.Auto);

                        mailClient.Authenticate(fromMailAdress, "Amadeusz");

                        mailClient.Send(message);
                        mailClient.Disconnect(true);
                    }
                }
                else
                {
                    ErrorBlock.Text       = "Check Email";
                    ErrorBlock.Visibility = Visibility.Visible;

                    Log log = new Log(KeyBox.Text, URLBox.Text, "***Wrong URL: " + MailBox.Text);
                    log.Save(file_name);
                }
            }
            else
            {
                ErrorBlock.Text       = "Check URL";
                ErrorBlock.Visibility = Visibility.Visible;

                Log log = new Log(KeyBox.Text, "***Wrong URL:  " + URLBox.Text, MailBox.Text);
                log.Save(file_name);
            }
        }