private static void _sendEmail(AsyncSendMailStatus status, MailTask mailTask)
        {
            try
            {
                var server = mailTask.BuildServer();
                var mail   = mailTask.BuildMail();
                var smtp   = new SmtpClient();

                // Add event handlers to current SmtpClient instance.
                smtp.OnAuthorized        += new SmtpClient.OnAuthorizedEventHandler(OnAuthorized);
                smtp.OnConnected         += new SmtpClient.OnConnectedEventHandler(OnConnected);
                smtp.OnSecuring          += new SmtpClient.OnSecuringEventHandler(OnSecuring);
                smtp.OnSendingDataStream +=
                    new SmtpClient.OnSendingDataStreamEventHandler(OnSendingDataStream);

                status.Status = "Connecting server ...";
                smtp.Tag      = status;
                smtp.SendMail(server, mail);

                status.Status   = "Completed";
                status.HasError = false;
                status.Progress = 100;
            }
            catch (Exception ep)
            {
                status.Status   = ep.Message;
                status.HasError = true;
                status.Progress = 100;
            }

            status.Completed = true;
        }
示例#2
0
        private ActionResult _syncSendMail(MailTask mailTask)
        {
            var OauthWrapper = _initOauthWrapper(mailTask.OauthProvider);

            ViewBag.TokenIsExisted = !string.IsNullOrEmpty(OauthWrapper.Provider.AccessToken);

            try
            {
                mailTask.AuthType = SmtpAuthType.XOAUTH2;
                mailTask.User     = OauthWrapper.Provider.UserEmail;
                mailTask.Password = OauthWrapper.Provider.AccessToken;
                mailTask.IsAuthenticationRequired = true;

                // always set From to authenticated user.
                mailTask.Sender = OauthWrapper.Provider.UserEmail;

                var smtp   = new SmtpClient();
                var server = mailTask.BuildServer();
                var mail   = mailTask.BuildMail();

                smtp.SendMail(server, mail);

                ViewBag.IsSyncSendSucceeded = true;
                ViewBag.SyncSendStatus      = "Message has been submitted to server successfully.";
            }
            catch (Exception ep)
            {
                ViewBag.IsSyncSendSucceeded = false;
                ViewBag.SyncSendStatus      = ep.Message;
            }

            mailTask.TaskId = Guid.NewGuid().ToString();
            return(_mailView(mailTask));
        }
示例#3
0
        public ActionResult AsyncSend(MailTask mailTask)
        {
            var OauthWrapper = _initOauthWrapper(mailTask.OauthProvider);

            if (OauthWrapper.IsAccessTokenExpired)
            {
                try
                {
                    OauthWrapper.RefreshAccessToken();
                }
                catch
                {
                    Services.AsyncSendMailService.PutErrorStatus(mailTask.TaskId, "Failed to refresh access token.");
                    return(Content(mailTask.TaskId));
                }
            }

            mailTask.AuthType = SmtpAuthType.XOAUTH2;
            mailTask.User     = OauthWrapper.Provider.UserEmail;
            mailTask.Password = OauthWrapper.Provider.AccessToken;
            mailTask.IsAuthenticationRequired = true;

            // always set From to authenticated user.
            mailTask.Sender = OauthWrapper.Provider.UserEmail;

            Services.AsyncSendMailService.CreateAsyncTask(mailTask);
            return(Content(mailTask.TaskId));
        }
        private void SendEmail(MailTask mailTask)
        {
            var recipientList = new InternetAddressList(mailTask.To.Split(";").Select(x => new MailboxAddress(x)));

            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(mailTask.From));
            message.To.AddRange(recipientList);
            message.Subject = mailTask.Subject;
            message.Body    = new TextPart("html")
            {
                Text = mailTask.Body
            };

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

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

                client.AuthenticationMechanisms.Remove("XOAUTH2");
                // Note: only needed if the SMTP server requires authentication
                client.Authenticate("*****@*****.**", "Sage@1234$");

                client.Send(message);
                client.Disconnect(true);
            }
        }
示例#5
0
        private ActionResult _doOauth(MailTask mailTask)
        {
            _setDefaultViewBagValue();

            var OauthWrapper = _initOauthWrapper(mailTask.OauthProvider);

            if (!string.IsNullOrEmpty(OauthWrapper.Provider.AccessToken))
            {
                if (!OauthWrapper.IsAccessTokenExpired)
                {
                    return(_syncSendMail(mailTask));
                }

                try
                {
                    OauthWrapper.RefreshAccessToken();
                    return(_syncSendMail(mailTask));
                }
                catch
                {
                    // "Failed to refresh access token, try to get a new access token ...";
                }
            }

            Services.TempMailTaskStore.PutTask(mailTask);
            return(Redirect(OauthWrapper.Provider.GetFullAuthUri() + "&state=" + mailTask.TaskId));
        }
        // GET: Mass
        public ActionResult Index()
        {
            var mailTask = new MailTask();

            mailTask.Subject = "Test email from ASP.NET MVC";
            mailTask.IsAuthenticationRequired = false;

            var body = new StringBuilder();

            body.Append("This sample demonstrates how to send multiple emails from ASP.NET MVC with thread pool.\r\n\r\n");
            body.Append("From: [$sender]\r\n");
            body.Append("To: [$rcpt]\r\n");
            body.Append("Subject: [$subject]\r\n\r\n");

            body.Append("Above sender, rcpt, subject values will be replaced by actual value based on each recipient.\r\n\r\n");
            body.Append("If no sever address was specified, the email will be delivered to the recipient's server directly.\r\n");
            body.Append("However, it is not recommended, because most email providers would reject your message due to anti-spam policy.\r\n");

            mailTask.TextBody = body.ToString();

            ViewBag.Port     = DropDownListData.PortList(mailTask.Port);
            ViewBag.Protocol = DropDownListData.ProtocolList(mailTask.Protocol);

            ViewBag.IsSyncSendSucceeded = false;
            ViewBag.SyncSendStatus      = string.Empty;

            return(View(mailTask));
        }
示例#7
0
        public void testAllLists()
        {
            MailTask mailTask = new MailTask();

            mailTask.Project = new Project();

            _tolist  = _emailAddress1;
            _cclist  = _emailAddress2;
            _bcclist = _emailAddress1;
            _subject = "Msg 5: Test to all addresses";
            _message = "Test message";

            try {
                mailTask.Mailhost    = _mailhost;
                mailTask.From        = _from;
                mailTask.ToList      = _tolist;
                mailTask.Subject     = _subject;
                mailTask.Message     = _message;
                mailTask.CcList      = _cclist;
                mailTask.BccList     = _bcclist;
                mailTask.Attachments = _attachments;
                mailTask.Files       = _files;

                mailTask.Execute();
            } catch (Exception e) {
                Assertion.Assert(_subject + ": " + e.Message, false);
            }
        }
示例#8
0
        public void testFilesAsBody()
        {
            MailTask mailTask = new MailTask();

            mailTask.Project = new Project();

            _tolist  = _emailAddress1;
            _subject = "Msg 6: Files for message";
            _message = "Test message";
            foreach (string fileName in _fileList)
            {
                _files += fileName + ";";
            }
            // add bogus entry
            _files += "BogusFile.txt";

            try {
                mailTask.Mailhost    = _mailhost;
                mailTask.From        = _from;
                mailTask.ToList      = _tolist;
                mailTask.Subject     = _subject;
                mailTask.Message     = _message;
                mailTask.CcList      = _cclist;
                mailTask.BccList     = _bcclist;
                mailTask.Attachments = _attachments;
                mailTask.Files       = _files;

                mailTask.Execute();
            } catch (Exception e) {
                Assertion.Assert(_subject + ": " + e.Message, false);
            }
        }
示例#9
0
        public void SendSimpleAsync(string host, int port, string userName, string password,
                                    string from, string to, string subject, string bodyString, bool isHtml, object userToken, Action <Exception, object> callback)
        {
            SmtpClient client = new SmtpClient(host, port);

            client.UseDefaultCredentials = false;
            client.Credentials           = new NetworkCredential(userName, password);

            MailMessage message = new MailMessage();

            message.From = new MailAddress(from);

            string[] toList = to.Split(new char[] { ';' });
            foreach (string item in toList)
            {
                message.To.Add(item);
            }

            message.Subject = subject;
            message.Body    = bodyString;

            MailTask task = userToken as MailTask;

            task.msg              = message;
            client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
            client.SendAsync(message, userToken);
        }
示例#10
0
        MailTask _buildDefaultTask()
        {
            var mailTask = new MailTask();

            mailTask.Subject = "Test email from ASP.NET MVC with XOAUTH2";
            mailTask.IsAuthenticationRequired = true;
            mailTask.AuthType        = SmtpAuthType.XOAUTH2;
            mailTask.Server          = "smtp.gmail.com";
            mailTask.Port            = 587;
            mailTask.OauthProvider   = OauthProvider.GoogleSmtpProvider;
            mailTask.IsSslConnection = true;
            mailTask.Sender          = "unspecified"; // will be replaced after oauth is completed.

            var body = new StringBuilder();

            body.Append("This sample demonstrates how to send email from ASP.NET MVC with XOAUTH2.\r\n\r\n");
            body.Append("Please apply for your Google/MS client_id and client_secret as introduced in OauthProvider.cs.\r\n");
            body.Append("If you got \"This app isn't verified\" information, please click \"advanced\" -> Go to ... for test.\r\n");

            mailTask.TextBody = body.ToString();

            _setDefaultViewBagValue();

            var OauthWrapper = _initOauthWrapper(mailTask.OauthProvider);

            ViewBag.TokenIsExisted = !string.IsNullOrEmpty(OauthWrapper.Provider.AccessToken);

            return(mailTask);
        }
        public void Start(MailTask mailTaskTemplate)
        {
            if (_trafficController == null)
            {
                _trafficController = new TrafficController();
            }

            string recipients = mailTaskTemplate.RecipientTo;

            mailTaskTemplate.RecipientTo = string.Empty;

            _recipientList = new AddressCollection(recipients);

            _status.TotalCount = _recipientList.Count;
            _status.Succeeded  = 0;
            _status.Failed     = 0;

            for (int recipientIndex = 0; recipientIndex < _recipientList.Count; recipientIndex++)
            {
                var mailTask = mailTaskTemplate.Copy();
                mailTask.RecipientTo = (_recipientList[recipientIndex] as MailAddress).ToString();
                while (!_submitMessage(recipientIndex, mailTask))
                {
                    Thread.Sleep(10);
                }
            }

            while (_threadCounter > 0 || !_status.Completed)
            {
                Thread.Sleep(50);
            }
        }
示例#12
0
 public static void PutTask(MailTask mailTask)
 {
     lock (_lock)
     {
         if (!_tasks.ContainsKey(mailTask.TaskId))
         {
             _tasks.Add(mailTask.TaskId, mailTask);
         }
     }
 }
        public ActionResult Index(MailTask mailTask)
        {
            ViewBag.Port     = DropDownListData.PortList(mailTask.Port);
            ViewBag.Protocol = DropDownListData.ProtocolList(mailTask.Protocol);

            if (ModelState.IsValid)
            {
                _syncSendMail(mailTask);
            }

            return(View(mailTask));
        }
        public static void CreateAsyncTask(MailTask mailTask)
        {
            lock (_lock)
            {
                AsyncSendMailStatus status = new AsyncSendMailStatus();
                status.TaskId = mailTask.TaskId;
                if (!_taskStatus.ContainsKey(mailTask.TaskId))
                {
                    _taskStatus.Add(mailTask.TaskId, status);

                    Task.Run(() =>
                    {
                        _sendEmail(status, mailTask);
                    });
                }
            }
        }
        void _syncSendMail(MailTask mailTask)
        {
            try
            {
                var smtp   = new SmtpClient();
                var server = mailTask.BuildServer();
                var mail   = mailTask.BuildMail();

                smtp.SendMail(server, mail);
                ViewBag.IsSyncSendSucceeded = true;
                ViewBag.SyncSendStatus      = "Message has been submitted to server successfully.";
            }
            catch (Exception ep)
            {
                ViewBag.IsSyncSendSucceeded = false;
                ViewBag.SyncSendStatus      = ep.Message;
            }
        }
示例#16
0
        public static void CreateAsyncTask(MailTask mailTask)
        {
            lock (_lock)
            {
                var status = new MassSendMailStatus();
                status.TaskId = mailTask.TaskId;
                if (!_threadPools.ContainsKey(mailTask.TaskId))
                {
                    MassSendThreadPool threadPool = new MassSendThreadPool();
                    _threadPools.Add(mailTask.TaskId, threadPool);

                    Task.Run(() =>
                    {
                        threadPool.Start(mailTask);
                    });
                }
            }
        }
示例#17
0
        public IActionResult SubmitMail([FromBody] MailDto mailDto)
        {
            var vendorId = HttpContext.Items.Where(x => x.Key == "VendorId").First().Value.ToString();

            var newMailTask = new MailTask()
            {
                From               = mailDto.From,
                To                 = string.Join(';', mailDto.To),
                Body               = mailDto.Body,
                Processed          = false,
                ProcessedTimestamp = null,
                ReceivedTimestamp  = DateTime.Now,
                Subject            = mailDto.Subject,
                ClientId           = mailDto.ClientId,
                VendorId           = Guid.Parse(vendorId)
            };

            _context.MailTasks.Add(newMailTask);
            _context.SaveChanges();

            string taskStatusUrl = $"api/communications/mail/status/{newMailTask.Id}";
            string taskCancelUrl = $"api/communications/mail/cancel/{newMailTask.Id}";

            var nestedPayload = new MailTaskSubmittedResultDto()
            {
                CancelUrl         = taskCancelUrl,
                StatusUrl         = taskStatusUrl,
                Processed         = newMailTask.Processed,
                ReceivedTimestamp = newMailTask.ReceivedTimestamp.ToString("yyyy-MM-dd hh:mm:ss fff"),
                TaskId            = newMailTask.Id.ToString(),
                VendorId          = newMailTask.VendorId.ToString()
            };

            Hangfire.BackgroundJob.Enqueue <MailHelper>(x => x.ProcessMailTask(newMailTask.Id));

            var payload = new ResponseObject <MailTaskSubmittedResultDto>()
            {
                Payload = nestedPayload,
                Success = true
            };

            return(Accepted(uri: taskStatusUrl, value: payload));
        }
示例#18
0
        public void SendSimpleAsyncCallback(string host, int port, string userName, string password,
                                            string from, string to, string subject, string bodyString, bool isHtml, object userToken, Action <Exception, object> callback)
        {
            SmtpClient client = new SmtpClient(host, port);
            {
                client.UseDefaultCredentials = false;
                client.Credentials           = new NetworkCredential(userName, password);

                MailMessage message = new MailMessage();
                {
                    message.From = new MailAddress(from);

                    string[] toList = to.Split(new char[] { ';' });
                    foreach (string item in toList)
                    {
                        message.To.Add(item);
                    }

                    message.Subject = subject;
                    message.Body    = bodyString;

                    MailTask task = userToken as MailTask;
                    task.msg = message;

                    client.SendCompleted += (s, e) =>
                    {
                        message.Dispose();
                        client.Dispose();
                        try
                        {
                            throw new ApplicationException("test ex");
                        }
                        finally
                        {
                            callback(e.Error, userToken);
                        }
                    };
                    //throw new ApplicationException("test ex");
                    client.SendAsync(message, userToken);
                }
            }
        }
示例#19
0
        void client_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            MailTask mailTask = e.UserState as MailTask;

            mailTask.msg.Dispose();
            SmtpClient client = sender as SmtpClient;

            client.Dispose();

            if (e.Error != null)
            {
            }

            Interlocked.Increment(ref FinishedCount);

            if (mailTask.totalCount == FinishedCount)
            {
                mailTask.ev.Set();
            }
        }
示例#20
0
        public static MailTask GetTask(string taskId)
        {
            MailTask task = null;

            if (string.IsNullOrEmpty(taskId))
            {
                return(task);
            }

            lock (_lock)
            {
                if (_tasks.ContainsKey(taskId))
                {
                    task = _tasks[taskId];
                    _tasks.Remove(taskId);
                }
            }

            return(task);
        }
        bool _submitMessage(int recipientIndex, MailTask mailTask)
        {
            if (!_trafficController.PrepareIncreaseConnection())
            {
                _trafficController.Rollback();
                return(false);
            }

            if (!_trafficController.PrepareIncreaseMessage())
            {
                _trafficController.Rollback();
                return(false);
            }

            SendMailThreadState state = new SendMailThreadState();

            state.Server = mailTask.BuildServer();
            state.Mail   = mailTask.BuildMail();

            state.Mail.TextBody = state.Mail.TextBody.Replace("[$sender]", state.Mail.From.ToString());
            state.Mail.TextBody = state.Mail.TextBody.Replace("[$rcpt]", state.Mail.To.ToString());
            state.Mail.TextBody = state.Mail.TextBody.Replace("[$subject]", state.Mail.Subject.ToString());

            // even you can add different attachment for different recipient here.
            state.RecipientIndex = recipientIndex;

            try
            {
                Interlocked.Increment(ref _threadCounter);
                ThreadPool.QueueUserWorkItem(this._sendThreadProc, state);
                _trafficController.Commit();

                return(true);
            }
            catch
            {
                Interlocked.Decrement(ref _threadCounter);
                _trafficController.Rollback();
                return(false);
            }
        }
示例#22
0
        // Please add http://localhost:54098/oauth/token to Authorized redirect URIs in your Google/MS Azure project.
        // to learn more detail, please refer to GoogleOauthProvider.cs
        public ActionResult Token(string code, string state)
        {
            _setDefaultViewBagValue();

            MailTask mailTask = Services.TempMailTaskStore.GetTask(state);

            if (mailTask == null)
            {
                mailTask = _buildDefaultTask();

                ViewBag.SyncSendStatus = "Specified mail task is not found in temporal storage, please try it again.";
                return(_mailView(mailTask));
            }

            var OauthWrapper = _initOauthWrapper(mailTask.OauthProvider);

            try
            {
                OauthWrapper.AuthorizationCode = code;
                OauthWrapper.RequestAccessTokenAndUserEmail();
            }
            catch (Exception ep)
            {
                ViewBag.SyncSendStatus = ep.Message;
                return(_mailView(mailTask));
            }

            if (mailTask.IsAsyncTask)
            {
                ViewBag.IsSyncSendSucceeded = true;
                ViewBag.SyncSendStatus      = "Oauth is completed, ready to send email.";

                // oauth is completed. back to view and invoke AutoAsyncSend.
                ViewBag.AutoAsyncSend  = true;
                ViewBag.TokenIsExisted = !string.IsNullOrEmpty(OauthWrapper.Provider.AccessToken);
                return(_mailView(mailTask));
            }

            return(_syncSendMail(mailTask));
        }
示例#23
0
        public ActionResult Index(MailTask mailTask)
        {
            _setDefaultViewBagValue();

            if (ModelState.IsValid)
            {
                try
                {
                    return(_doOauth(mailTask));
                }
                catch (Exception ep)
                {
                    ViewBag.SyncSendStatus = ep.Message;
                }

                return(_mailView(mailTask));
            }

            var OauthWrapper = _initOauthWrapper(mailTask.OauthProvider);

            ViewBag.TokenIsExisted = !string.IsNullOrEmpty(OauthWrapper.Provider.AccessToken);

            return(_mailView(mailTask));
        }
示例#24
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ISeedData seedData)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseSignalR((cfg) => {
                cfg.MapHub <NotificationHub>("/notifications");
            });

            app.UseMvc(routes =>
                       routes.MapRoute(
                           name: "WebAPI",
                           template: "api/{controller}/{action}/{id?}"
                           )
                       //.MapRoute(
                       //    name: "WebAPIForYear",
                       //    template: "api/foryear/{year:int}/{controller}/{action}/{id?}"
                       //)
                       );

            seedData.SeedCompanyData();
            seedData.SeedUserData();
            //var tmp1 = UnitOfWork.ContoShemeOptions;

            //seedData.PopulateData();

            // Create views
            BankView.CreateView();

            BusinessPartnerBankView.CreateView();
            BusinessPartnerByConstructionSiteView.CreateView();
            BusinessPartnerInstitutionView.CreateView();
            BusinessPartnerLocationView.CreateView();
            BusinessPartnerDocumentView.CreateView();
            BusinessPartnerNoteView.CreateView();
            BusinessPartnerOrganizationUnitView.CreateView();
            BusinessPartnerPhoneView.CreateView();
            BusinessPartnerView.CreateView();
            BusinessPartnerTypeView.CreateView();

            //CompanyView.CreateView(); //???

            //UserView.CreateView();

            InputInvoiceView.CreateView();
            InputInvoiceNoteView.CreateView();
            InputInvoiceDocumentView.CreateView();
            OutputInvoiceDocumentView.CreateView();
            OutputInvoiceView.CreateView();
            OutputInvoiceNoteView.CreateView();

            CountryView.CreateView();
            RegionView.CreateView();
            MunicipalityView.CreateView();
            CityView.CreateView();

            ProfessionView.CreateView();

            SectorView.CreateView();
            AgencyView.CreateView();

            TaxAdministrationView.CreateView();

            ToDoView.CreateView();

            EmployeeByBusinessPartnerView.CreateView();
            EmployeeByConstructionSiteView.CreateView();
            EmployeeCardView.CreateView();
            EmployeeView.CreateView();
            EmployeeDocumentView.CreateView();
            EmployeeItemView.CreateView();
            EmployeeLicenceView.CreateView();
            EmployeeNoteView.CreateView();
            EmployeeProfessionView.CreateView();
            FamilyMemberView.CreateView();
            LicenceTypeView.CreateView();

            PhysicalPersonView.CreateView();
            PhysicalPersonItemView.CreateView();
            PhysicalPersonNoteView.CreateView();
            PhysicalPersonLicenceView.CreateView();
            PhysicalPersonDocumentView.CreateView();
            PhysicalPersonCardView.CreateView();
            PhysicalPersonProfessionView.CreateView();

            ConstructionSiteCalculationView.CreateView();
            ConstructionSiteDocumentView.CreateView();
            ConstructionSiteNoteView.CreateView();
            ConstructionSiteView.CreateView();

            VatView.CreateView();

            ServiceDeliveryView.CreateView();
            DiscountView.CreateView();
            StatusView.CreateView();

            ShipmentView.CreateView();
            ShipmentDocumentView.CreateView();

            PhonebookView.CreateView();
            PhonebookDocumentView.CreateView();
            PhonebookNoteView.CreateView();
            PhonebookPhoneView.CreateView();

            InvoiceView.CreateView();
            InvoiceItemView.CreateView();

            CallCentarView.CreateView();

            CalendarAssignmentView.CreateView();

            EmployeeAttachmentView.CreateView();

            PhysicalPersonAttachmentView.CreateView();

            ToDoStatusView.CreateView();

            var mailingTime = new Config().GetConfiguration()["MailTime"];

            Console.WriteLine("Sending mails scheduled at: {0}\nCurrent time: {1}", mailingTime, DateTime.Now.ToString("HH:mm:ss"));

            Thread mailThread = new Thread(() => MailTask.SendMailTime(mailingTime));

            mailThread.IsBackground = true;
            mailThread.Start();
        }
 public ActionResult AsyncSend(MailTask mailTask)
 {
     Services.AsyncSendMailService.CreateAsyncTask(mailTask);
     return(Content(mailTask.TaskId));
 }
示例#26
0
 ActionResult _mailView(MailTask mailTask)
 {
     ViewBag.Port = DropDownListData.PortList(mailTask.Port);
     return(View("Index", mailTask));
 }
示例#27
0
 ActionResult _mailView(MailTask mailTask)
 {
     ViewBag.Port          = DropDownListData.PortList(mailTask.Port);
     ViewBag.OauthProvider = DropDownListData.OauthList(mailTask.OauthProvider);
     return(View("Index", mailTask));
 }