private void FillComboEmail()
        {
            _listEmailAddresses = EmailAddresses.GetDeepCopy();          //Does not include user specific email addresses.
            List <Clinic> listClinicsAll = Clinics.GetDeepCopy();

            _listEmailAddresses.RemoveAll(x => listClinicsAll.Any(y => x.EmailAddressNum == y.EmailAddressNum));          //Exclude any email addresses that are associated to a clinic.
            //Exclude default practice email address.
            _listEmailAddresses.RemoveAll(x => x.EmailAddressNum == PrefC.GetLong(PrefName.EmailDefaultAddressNum));
            //Exclude web mail notification email address.
            _listEmailAddresses.RemoveAll(x => x.EmailAddressNum == PrefC.GetLong(PrefName.EmailNotifyAddressNum));
            comboEmailFrom.Items.Add(Lan.g(this, "Practice/Clinic"));           //default
            comboEmailFrom.SelectedIndex = 0;
            textFromAddress.Text         = EmailAddresses.GetByClinic(Clinics.ClinicNum).EmailUsername;
            //Add all email addresses which are not associated to a user, a clinic, or either of the default email addresses.
            for (int i = 0; i < _listEmailAddresses.Count; i++)
            {
                comboEmailFrom.Items.Add(_listEmailAddresses[i].EmailUsername);
            }
            //Add user specific email address if present.
            EmailAddress emailAddressMe = EmailAddresses.GetForUser(Security.CurUser.UserNum);            //can be null

            if (emailAddressMe != null)
            {
                _listEmailAddresses.Insert(0, emailAddressMe);
                comboEmailFrom.Items.Insert(1, Lan.g(this, "Me") + " <" + emailAddressMe.EmailUsername + ">");        //Just below Practice/Clinic
                comboEmailFrom.SelectedIndex = 1;
                textFromAddress.Text         = emailAddressMe.EmailUsername;
            }
        }
Exemple #2
0
        ///<summary>Gets new messages from email inbox, as well as older messages from the db. Also fills the grid.</summary>
        private int GetMessages()
        {
            AddressInbox = EmailAddresses.GetByClinic(0); //Default for clinic/practice.
            Cursor       = Cursors.WaitCursor;
            FillGridEmailMessages();                      //Show what is in db.
            Cursor = Cursors.Default;
            if (AddressInbox.Pop3ServerIncoming == "")    //Email address not setup.
            {
                Text         = "Email Inbox";
                AddressInbox = null;
                //todo: Message Box is too instrusive, move this to a status label.
                //MsgBox.Show(this,"Default email address has not been setup completely.");
                return(0);
            }
            Text = "Email Inbox for " + AddressInbox.EmailUsername;
            Application.DoEvents();                                                                         //So that something is showing while the page is loading.
            if (!CodeBase.ODEnvironment.IdIsThisComputer(PrefC.GetString(PrefName.EmailInboxComputerName))) //This is not the computer to get new messages from.
            {
                return(0);
            }
            if (PrefC.GetString(PrefName.EmailInboxComputerName) == "")
            {
                MsgBox.Show(this, "Computer name to fetch new email from has not been setup.");
                return(0);
            }
            Cursor = Cursors.WaitCursor;
            int emailMessagesTotalCount = 0;

            Text = "Email Inbox for " + AddressInbox.EmailUsername + " - Fetching new email...";
            try {
                bool hasMoreEmail = true;
                while (hasMoreEmail)
                {
                    List <EmailMessage> emailMessages = EmailMessages.ReceiveFromInbox(1, AddressInbox);
                    emailMessagesTotalCount += emailMessages.Count;
                    if (emailMessages.Count == 0)
                    {
                        hasMoreEmail = false;
                    }
                    else                       //Show messages as they are downloaded, to indicate to the user that the program is still processing.
                    {
                        FillGridEmailMessages();
                        Application.DoEvents();
                    }
                }
            }
            catch (Exception ex) {
                MessageBox.Show(Lan.g(this, "Error retrieving email messages") + ": " + ex.Message);
            }
            finally {
                Text = "Email Inbox for " + AddressInbox.EmailUsername;
            }
            Text = "Email Inbox for " + AddressInbox.EmailUsername + " - Resending any acknowledgments which previously failed...";
            EmailMessages.SendOldestUnsentAck(AddressInbox);
            Text   = "Email Inbox for " + AddressInbox.EmailUsername;
            Cursor = Cursors.Default;
            return(emailMessagesTotalCount);
        }
		private void LoadSig() {
			if(!_isComposing || !_isSigningEnabled) {
				return;
			}
			EmailAddress emailAddressDefault=EmailAddresses.GetByClinic(ClinicNum);
			if(emailAddressDefault!=null) {//Must have a default emailaddress to be allowed to set a signature/cert.  Presumably 
				EmailAddress emailAddressSelected=null;
				if(TryGetFromEmailAddress(out emailAddressSelected)==FromAddressMatchResult.Failed) {
					return;
				}
				SetSig(EmailMessages.GetCertFromPrivateStore(emailAddressSelected.EmailUsername));
			}
		}
		public void LoadEmailAddresses(long clinicNum) {
      //emails to include: 
      //1. Default Practice/Clinic
      //2. Me
      //3. All other email addresses not tied to a user
      _listEmailAddresses=new List<EmailAddress>();
      EmailAddress emailAddressDefault=EmailAddresses.GetByClinic(clinicNum);
      EmailAddress emailAddressMe=EmailAddresses.GetForUser(Security.CurUser.UserNum);
      if(emailAddressDefault!=null) {
        _listEmailAddresses.Add(emailAddressDefault);
      }
      if(emailAddressMe!=null) {
        _listEmailAddresses.Add(emailAddressMe);
      }
			foreach(EmailAddress emailCur in EmailAddresses.GetDeepCopy()) {
        if((emailAddressDefault!=null && emailCur.EmailUsername==emailAddressDefault.EmailUsername)
          || (emailAddressMe!=null && emailCur.EmailUsername==emailAddressMe.EmailUsername)) {
          continue;
        }
        _listEmailAddresses.Add(emailCur);
      }
		}
        private void butPrint_Click(object sender, EventArgs e)
        {
            if (!TryToSaveData())
            {
                return;
            }
            SheetCur = Sheets.GetSheet(SheetCur.SheetNum);
            //whether this is a new sheet, or one pulled from the database,
            //it will have the extra parameter we are looking for.
            //A new sheet will also have a PatNum parameter which we will ignore.
            FormSheetOutputFormat FormS = new FormSheetOutputFormat();

            if (SheetCur.SheetType == SheetTypeEnum.ReferralSlip ||
                SheetCur.SheetType == SheetTypeEnum.ReferralLetter)
            {
                FormS.PaperCopies = 2;
            }
            else
            {
                FormS.PaperCopies = 1;
            }
            if (SheetCur.PatNum != 0 &&
                SheetCur.SheetType != SheetTypeEnum.DepositSlip)
            {
                Patient pat = Patients.GetPat(SheetCur.PatNum);
                if (SheetCur.SheetType == SheetTypeEnum.LabSlip)
                {
                    FormS.IsForLab = true;                  //Changes label to "E-mail to Lab:"
                }
                else if (pat.Email != "")
                {
                    FormS.EmailPatOrLabAddress = pat.Email;
                    //No need to email to a patient for sheet types: LabelPatient (0), LabelCarrier (1), LabelReferral (2), ReferralSlip (3), LabelAppointment (4), Rx (5), Consent (6), ReferralLetter (8), ExamSheet (13), DepositSlip (14)
                    //The data is too private to email unencrypted for sheet types: PatientForm (9), RoutingSlip (10), MedicalHistory (11), LabSlip (12)
                    //A patient might want email for the following sheet types and the data is not very private: PatientLetter (7)
                    if (SheetCur.SheetType == SheetTypeEnum.PatientLetter)
                    {
                        //This just defines the default selection. The user can manually change selections in FormSheetOutputFormat.
                        FormS.EmailPatOrLab = true;
                        FormS.PaperCopies--;
                    }
                }
            }
            Referral referral = null;

            if (SheetCur.SheetType == SheetTypeEnum.ReferralSlip ||
                SheetCur.SheetType == SheetTypeEnum.ReferralLetter)
            {
                FormS.Email2Visible = true;
                SheetParameter parameter = SheetParameter.GetParamByName(SheetCur.Parameters, "ReferralNum");
                if (parameter == null)              //it can be null sometimes because of old bug in db.
                {
                    FormS.Email2Visible = false;    //prevents trying to attach email to nonexistent referral.
                }
                else
                {
                    long referralNum = PIn.Long(parameter.ParamValue.ToString());
                    referral = Referrals.GetReferral(referralNum);
                    if (referral.EMail != "")
                    {
                        FormS.Email2Address = referral.EMail;
                        FormS.Email2        = true;
                        FormS.PaperCopies--;
                    }
                }
            }
            else
            {
                FormS.Email2Visible = false;
            }
            FormS.ShowDialog();
            if (FormS.DialogResult != DialogResult.OK)
            {
                return;
            }
            if (FormS.PaperCopies > 0)
            {
                SheetPrinting.Print(SheetCur, FormS.PaperCopies, RxIsControlled);
            }
            EmailMessage message;
            Random       rnd        = new Random();
            string       attachPath = EmailMessages.GetEmailAttachPath();
            string       fileName;
            string       filePathAndName;
            EmailAddress emailAddress;
            Patient      patCur = Patients.GetPat(SheetCur.PatNum);

            if (patCur == null)
            {
                emailAddress = EmailAddresses.GetByClinic(0);
            }
            else
            {
                emailAddress = EmailAddresses.GetByClinic(patCur.ClinicNum);
            }
            //Graphics g=this.CreateGraphics();
            if (FormS.EmailPatOrLab)
            {
                fileName        = DateTime.Now.ToString("yyyyMMdd") + "_" + DateTime.Now.TimeOfDay.Ticks.ToString() + rnd.Next(1000).ToString() + ".pdf";
                filePathAndName = ODFileUtils.CombinePaths(attachPath, fileName);
                SheetPrinting.CreatePdf(SheetCur, filePathAndName);
                //Process.Start(filePathAndName);
                message             = new EmailMessage();
                message.PatNum      = SheetCur.PatNum;
                message.ToAddress   = FormS.EmailPatOrLabAddress;
                message.FromAddress = emailAddress.SenderAddress;              //Can be blank just as it could with the old pref.
                message.Subject     = SheetCur.Description.ToString();         //this could be improved
                EmailAttach attach        = new EmailAttach();
                string      shortFileName = Regex.Replace(SheetCur.Description.ToString(), @"[^\w'@-_()&]", "");
                attach.DisplayedFileName = shortFileName + ".pdf";
                attach.ActualFileName    = fileName;
                message.Attachments.Add(attach);
                FormEmailMessageEdit FormE = new FormEmailMessageEdit(message);
                FormE.IsNew = true;
                FormE.ShowDialog();
            }
            if ((SheetCur.SheetType == SheetTypeEnum.ReferralSlip ||
                 SheetCur.SheetType == SheetTypeEnum.ReferralLetter) &&
                FormS.Email2)
            {
                //email referral
                fileName        = DateTime.Now.ToString("yyyyMMdd") + "_" + DateTime.Now.TimeOfDay.Ticks.ToString() + rnd.Next(1000).ToString() + ".pdf";
                filePathAndName = ODFileUtils.CombinePaths(attachPath, fileName);
                SheetPrinting.CreatePdf(SheetCur, filePathAndName);
                //Process.Start(filePathAndName);
                message             = new EmailMessage();
                message.PatNum      = SheetCur.PatNum;
                message.ToAddress   = FormS.Email2Address;
                message.FromAddress = emailAddress.SenderAddress;                                         //Can be blank just as it could with the old pref.
                message.Subject     = Lan.g(this, "RE: ") + Patients.GetLim(SheetCur.PatNum).GetNameLF(); //works even if patnum invalid
                //SheetCur.Description.ToString()+" to "+Referrals.GetNameFL(referral.ReferralNum);//this could be improved
                EmailAttach attach        = new EmailAttach();
                string      shortFileName = Regex.Replace(SheetCur.Description.ToString(), @"[^\w,'@-_()&]", "");
                attach.DisplayedFileName = shortFileName + ".pdf";
                attach.ActualFileName    = fileName;
                message.Attachments.Add(attach);
                FormEmailMessageEdit FormE = new FormEmailMessageEdit(message);
                FormE.IsNew = true;
                FormE.ShowDialog();
            }
            //g.Dispose();
            DialogResult = DialogResult.OK;
        }
Exemple #6
0
		private void butEmail_Click(object sender,EventArgs e) {
			if(grid.Rows.Count==0) {
				MsgBox.Show(this,"There are no Patients in the table.  Must have at least one.");
				return;
			}
			if(!EmailAddresses.ExistsValidEmail()) {
				MsgBox.Show(this,"You need to enter an SMTP server name in e-mail setup before you can send e-mail.");
				return;
			}
			if(PrefC.GetLong(PrefName.ConfirmStatusEmailed)==0) {
				MsgBox.Show(this,"You need to set a status first for confirmation e-mails in the Recall Setup window.");
				return;
			}
			if(grid.SelectedIndices.Length==0) {
				ContactMethod cmeth;
				for(int i=0;i<Table.Rows.Count;i++) {
					cmeth=(ContactMethod)PIn.Int(Table.Rows[i]["PreferConfirmMethod"].ToString());
					if(cmeth!=ContactMethod.Email) {
						continue;
					}
					if(Table.Rows[i]["confirmed"].ToString()==DefC.GetName(DefCat.ApptConfirmed,PrefC.GetLong(PrefName.ConfirmStatusEmailed))) {//Already confirmed by email
						continue;
					}
					if(Table.Rows[i]["email"].ToString()=="") {
						continue;
					}
					grid.SetSelected(i,true);
				}
				if(grid.SelectedIndices.Length==0) {
					MsgBox.Show(this,"Confirmations have been sent to all patients of email type who also have an email address entered.");
					return;
				}
			}
			else {//deselect the ones that do not have email addresses specified
				int skipped=0;
				for(int i=grid.SelectedIndices.Length-1;i>=0;i--) {
					if(Table.Rows[grid.SelectedIndices[i]]["email"].ToString()=="") {
						skipped++;
						grid.SetSelected(grid.SelectedIndices[i],false);
					}
				}
				if(grid.SelectedIndices.Length==0) {
					MsgBox.Show(this,"None of the selected patients had email addresses entered.");
					return;
				}
				if(skipped>0) {
					MessageBox.Show(Lan.g(this,"Selected patients skipped due to missing email addresses: ")+skipped.ToString());
				}
			}
			if(!MsgBox.Show(this,MsgBoxButtons.YesNo,"Send email to all of the selected patients?")) {
				return;
			}
			Cursor=Cursors.WaitCursor;
			EmailMessage message;
			string str="";
			List<long> patNumsSelected=new List<long>();
			List<long> patNumsFailed=new List<long>();
			EmailAddress emailAddress;
			for(int i=0;i<grid.SelectedIndices.Length;i++){
				message=new EmailMessage();
				message.PatNum=PIn.Long(Table.Rows[grid.SelectedIndices[i]]["PatNum"].ToString());
				message.ToAddress=Table.Rows[grid.SelectedIndices[i]]["email"].ToString();//Could be guarantor email.
				emailAddress=EmailAddresses.GetByClinic(PIn.Long(Table.Rows[grid.SelectedIndices[i]]["ClinicNum"].ToString()));
				message.FromAddress=emailAddress.SenderAddress;				
				message.Subject=PrefC.GetString(PrefName.ConfirmEmailSubject);
				patNumsSelected.Add(message.PatNum);
				str=PrefC.GetString(PrefName.ConfirmEmailMessage);
				str=str.Replace("[NameF]",Table.Rows[grid.SelectedIndices[i]]["nameF"].ToString());
				str=str.Replace("[NameFL]",Table.Rows[grid.SelectedIndices[i]]["nameFL"].ToString());
				str=str.Replace("[date]",((DateTime)Table.Rows[grid.SelectedIndices[i]]["AptDateTime"]).ToShortDateString());
				str=str.Replace("[time]",((DateTime)Table.Rows[grid.SelectedIndices[i]]["AptDateTime"]).ToShortTimeString());
				message.BodyText=str;
				try {
					EmailMessages.SendEmailUnsecure(message,emailAddress);
				}
				catch {
					patNumsFailed.Add(message.PatNum);
					continue;
				}
				message.MsgDateTime=DateTime.Now;
				message.SentOrReceived=EmailSentOrReceived.Sent;
				EmailMessages.Insert(message);
				Appointments.SetConfirmed(PIn.Long(Table.Rows[grid.SelectedIndices[i]]["AptNum"].ToString()),PrefC.GetLong(PrefName.ConfirmStatusEmailed));
			}
			Cursor=Cursors.Default;
			if(patNumsFailed.Count==grid.SelectedIndices.Length){ //all failed
				//no need to refresh
				MsgBox.Show(this,"All emails failed. Possibly due to invalid email addresses, a loss of connectivity, or a firewall blocking communication.");//msg: all failed
				return;
			}
			else if(patNumsFailed.Count>0){//if some failed
				FillMain();
				//reselect only the failed ones
				for(int i=0;i<Table.Rows.Count;i++) { //table.Rows.Count=grid.Rows.Count
					long patNum=PIn.Long(Table.Rows[i]["PatNum"].ToString());
					if(patNumsFailed.Contains(patNum)) {
						grid.SetSelected(i,true);
					}
				}
				MsgBox.Show(this,"Some emails failed to send.");
				return;
			}
			//none failed
			FillMain();
			//reselect the original list 
			for(int i=0;i<Table.Rows.Count;i++) {
				long patNum=PIn.Long(Table.Rows[i]["PatNum"].ToString());
				if(patNumsSelected.Contains(patNum)) {
					grid.SetSelected(i,true);
				}
			}
		}
        private void FillComboEmail()
        {
            //emails to include:
            //1. Default Practice/Clinic
            //2. Me
            //3. All other email addresses not tied to a user
            _listEmailAddresses = new List <EmailAddress>();
            EmailAddress emailAddressDefault = EmailAddresses.GetByClinic(ClinicNum);
            EmailAddress emailAddressMe      = EmailAddresses.GetForUser(Security.CurUser.UserNum);

            if (emailAddressDefault != null)
            {
                _listEmailAddresses.Add(emailAddressDefault);
            }
            if (emailAddressMe != null)
            {
                _listEmailAddresses.Add(emailAddressMe);
            }
            foreach (EmailAddress emailCur in EmailAddresses.GetDeepCopy())
            {
                if ((emailAddressDefault != null && emailCur.EmailUsername == emailAddressDefault.EmailUsername) ||
                    (emailAddressMe != null && emailCur.EmailUsername == emailAddressMe.EmailUsername))
                {
                    continue;
                }
                _listEmailAddresses.Add(emailCur);
            }
            _listEmailAddresses.ForEach(x => {
                if (emailAddressDefault != null && x.EmailUsername == emailAddressDefault.EmailUsername)
                {
                    comboEmailFrom.Items.Add(Lan.g(this, "Practice/Clinic") + " <" + x.EmailUsername + ">");
                }
                else if (emailAddressMe != null && x.EmailUsername == emailAddressMe.EmailUsername)
                {
                    comboEmailFrom.Items.Add(Lan.g(this, "Me") + " <" + x.EmailUsername + ">");
                }
                else
                {
                    comboEmailFrom.Items.Add(x.EmailUsername);
                }
            });
            for (int i = 0; i < _listEmailAddresses.Count; i++)
            {
                //Sending email address should be set before loading this control.  This is the best approach to matching email account.
                if (EmailAddressPreview != null)
                {
                    if (_listEmailAddresses[i].EmailAddressNum == EmailAddressPreview.EmailAddressNum)
                    {
                        comboEmailFrom.SelectedIndex = i;
                        break;                        //Found the right emailaddress, no need to look further.
                    }
                }
                else                  //Less reliable, but works in most email account setups.
                {
                    string senderAddress = _listEmailAddresses[i].SenderAddress.Trim().ToLower();
                    string emailUserName = _listEmailAddresses[i].EmailUsername.Trim().ToLower();
                    string fromAddress   = _emailMessage.FromAddress.Trim().ToLower();
                    if ((senderAddress != "" && fromAddress.Contains(senderAddress)) ||
                        (emailUserName != "" && fromAddress.Contains(emailUserName)) ||
                        (fromAddress != "" && (emailUserName.Contains(fromAddress) || senderAddress.Contains(fromAddress))))
                    {
                        comboEmailFrom.SelectedIndex = i;
                        break;                        //Found an emailaddress that is probably right, best to stop here as opposed to finding another potential match.
                    }
                }
            }
            if (!_isComposing || !_isSigningEnabled)
            {
                return;
            }
            if (emailAddressDefault != null)
            {
                SetSig(EmailMessages.GetCertFromPrivateStore(GetOutgoingEmailAddress().EmailUsername));
            }
        }
        ///<summary></summary>
        private void butSend_Click(object sender, System.EventArgs e)
        {
            if (comboEmailFrom.SelectedIndex < 0)
            {
                MessageBox.Show("Select an email address to send from first.");
            }
            EmailAddress emailAddress;

            if (comboEmailFrom.SelectedIndex == 0)                                    //clinic/practice default
            {
                emailAddress = EmailAddresses.GetByClinic(Clinics.ClinicNum);         //practice or clinic.
            }
            else                                                                      //me or static email address
            {
                emailAddress = _listEmailAddresses[comboEmailFrom.SelectedIndex - 1]; //-1 to account for predefined "Clinic/Practice" and items in combobox
            }
            if (emailAddress == null)
            {
                MessageBox.Show("Unable to find email address.");
                return;
            }
            if (string.IsNullOrWhiteSpace(textFromAddress.Text))
            {
                MsgBox.Show(this, "Please enter a sender address.");
                return;
            }
            if (_listJobEmails.All(x => !x.IsSend))
            {
                MsgBox.Show(this, "Please select at least one recipient.");
                return;
            }
            if (emailAddress.SMTPserver == "")
            {
                MsgBox.Show(this, "The email address in email setup must have an SMTP server.");
                return;
            }
            if (string.IsNullOrEmpty(textVersions.Text))
            {
                if (MessageBox.Show("No version specified, continue?", "", MessageBoxButtons.YesNoCancel) != DialogResult.Yes)
                {
                    return;
                }
            }
            if (string.IsNullOrEmpty(textDescriptions.Text))
            {
                if (MessageBox.Show("No description specified, continue?", "", MessageBoxButtons.YesNoCancel) != DialogResult.Yes)
                {
                    return;
                }
            }
            if (string.IsNullOrEmpty(textSubject.Text))
            {
                if (MessageBox.Show("No subject specified, continue?", "", MessageBoxButtons.YesNoCancel) != DialogResult.Yes)
                {
                    return;
                }
            }
            StringBuilder sb = new StringBuilder();

            Cursor = Cursors.WaitCursor;
            string template = PrefC.GetString(PrefName.JobManagerDefaultEmail);

            foreach (Jobs.JobEmail je in _listJobEmails)
            {
                if (!je.IsSend)
                {
                    continue;
                }
#if DEBUG
                je.EmailAddress = "*****@*****.**";              //send all emails to Ryan for debugging.
#endif
                EmailMessage emailMessage = GetJobEmailMessage(je);
                try {
                    EmailMessages.SendEmailUnsecure(emailMessage, emailAddress);
                    emailMessage.SentOrReceived = EmailSentOrReceived.Sent;
                    EmailMessages.Insert(emailMessage);
                    je.StatusMsg = "Sent";
                    je.IsSend    = false;
                }
                catch (Exception ex) {
                    je.StatusMsg = ex.Message;
                    sb.AppendLine(ex.Message + "\r\n");
                }
            }
            Cursor         = Cursors.Default;
            _isSent        = true;
            butSend.Text   = "Resend";
            butCancel.Text = "Close";
            if (!string.IsNullOrEmpty(sb.ToString()))
            {
                MsgBoxCopyPaste msgBox = new MsgBoxCopyPaste("The following errors occurred while sending emails:\r\n" + sb.ToString());
                msgBox.ShowDialog();
            }
            FillGridRecipients();
        }
Exemple #9
0
        private void FillComboEmail()
        {
            //emails to include:
            //1. Default Practice/Clinic
            //2. Me
            //3. All other email addresses not tied to a user
            _listEmailAddresses = new List <EmailAddress>();
            EmailAddress emailAddressDefault = EmailAddresses.GetByClinic(ClinicNum);
            EmailAddress emailAddressMe      = EmailAddresses.GetForUser(Security.CurUser.UserNum);

            if (emailAddressDefault != null)
            {
                _listEmailAddresses.Add(emailAddressDefault);
            }
            if (emailAddressMe != null)
            {
                _listEmailAddresses.Add(emailAddressMe);
            }
            foreach (EmailAddress emailCur in EmailAddresses.GetDeepCopy())
            {
                if ((emailAddressDefault != null && emailCur.EmailUsername == emailAddressDefault.EmailUsername) ||
                    (emailAddressMe != null && emailCur.EmailUsername == emailAddressMe.EmailUsername))
                {
                    continue;
                }
                _listEmailAddresses.Add(emailCur);
            }
            _listEmailAddresses.ForEach(x => {
                if (emailAddressDefault != null && x.EmailUsername == emailAddressDefault.EmailUsername)
                {
                    comboEmailFrom.Items.Add(Lan.g(this, "Practice/Clinic") + " <" + x.EmailUsername + ">");
                }
                else if (emailAddressMe != null && x.EmailUsername == emailAddressMe.EmailUsername)
                {
                    comboEmailFrom.Items.Add(Lan.g(this, "Me") + " <" + x.EmailUsername + ">");
                }
                else
                {
                    comboEmailFrom.Items.Add(x.EmailUsername);
                }
            });
            //not perfect. Tries to guess what the selected combobox item should be based on the current text in FromAddress.
            for (int i = 0; i < _listEmailAddresses.Count; i++)
            {
                string senderAddress = _listEmailAddresses[i].SenderAddress.Trim().ToLower();
                string emailUserName = _listEmailAddresses[i].EmailUsername.Trim().ToLower();
                string fromAddress   = _emailMessage.FromAddress.Trim().ToLower();
                if ((senderAddress != "" && fromAddress.Contains(senderAddress)) ||
                    (emailUserName != "" && fromAddress.Contains(emailUserName)) ||
                    (fromAddress != "" && (emailUserName.Contains(fromAddress) || senderAddress.Contains(fromAddress))))
                {
                    comboEmailFrom.SelectedIndex = i;
                }
            }
            if (!_isComposing || !_isSigningEnabled)
            {
                return;
            }
            if (emailAddressDefault != null)
            {
                SetSig(EmailMessages.GetCertFromPrivateStore(GetOutgoingEmailAddress().EmailUsername));
            }
        }
        private void VerifyInputs()
        {
            AllowSendMessages();
            long    priProvNum = 0;
            long    patNumSubj = _patNum;
            string  notificationSubject;
            string  notificationBodyNoUrl;
            string  notificationURL;
            Family  family = null;
            Patient patCur = Patients.GetPat(_patNum);

            comboRegardingPatient.Items.Clear();
            if (patCur == null)
            {
                BlockSendSecureMessage("Patient is invalid.");
                _listPatients = null;
            }
            else
            {
                family      = Patients.GetFamily(_patNum);
                textTo.Text = patCur.GetNameFL();
                Provider priProv = Providers.GetProv(patCur.PriProv);
                if (priProv == null)
                {
                    BlockSendSecureMessage("Invalid primary provider for this patient.");
                }
                else
                {
                    priProvNum = priProv.ProvNum;
                    Provider userODProv = Providers.GetProv(Security.CurUser.ProvNum);
                    if (userODProv == null)
                    {
                        BlockSendSecureMessage("Not logged in as valid provider. Login as patient's primary provider to send message.");
                    }
                    else if (userODProv.ProvNum != priProv.ProvNum)
                    {
                        BlockSendSecureMessage("The patient's primary provider does not match the provider attached to the user currently logged in. Login as patient's primary provider to send message.");
                    }
                    else
                    {
                        textFrom.Text = priProv.GetFormalName();
                    }
                }
                if (patCur.Email == "")
                {
                    BlockSendNotificationMessage("Missing patient email. Setup patient email using Family module.");
                }
                if (patCur.OnlinePassword == "")
                {
                    BlockSendNotificationMessage("Patient has not been given online access. Setup patient online access using Family module.");
                }
            }
            //We are replying to an existing message so verify that the provider linked to this message matches our currently logged in provider.
            //This is because web mail communications will be visible in the patients Chart Module.
            if (_replyToEmailMessageNum > 0)
            {
                EmailMessage replyToEmailMessage = EmailMessages.GetOne(_replyToEmailMessageNum);
                if (replyToEmailMessage == null)
                {
                    MsgBox.Show(this, "Invalid input email message");
                    DialogResult = DialogResult.Abort;                    //nothing to show so abort, caller should be waiting for abort to determine if message should be marked read
                    return;
                }
                textSubject.Text = replyToEmailMessage.Subject;
                if (replyToEmailMessage.Subject.IndexOf("RE:") != 0)
                {
                    textSubject.Text = "RE: " + textSubject.Text;
                }
                patNumSubj = replyToEmailMessage.PatNumSubj;
                Patient patRegarding = Patients.GetOnePat(family.ListPats, patNumSubj);
                textBody.Text = "\r\n\r\n-----" + Lan.g(this, "Original Message") + "-----\r\n"
                                + (patRegarding == null ? "" : (Lan.g(this, "Regarding Patient") + ": " + patRegarding.GetNameFL() + "\r\n"))
                                + Lan.g(this, "From") + ": " + replyToEmailMessage.FromAddress + "\r\n"
                                + Lan.g(this, "Sent") + ": " + replyToEmailMessage.MsgDateTime.ToShortDateString() + " " + replyToEmailMessage.MsgDateTime.ToShortTimeString() + "\r\n"
                                + Lan.g(this, "To") + ": " + replyToEmailMessage.ToAddress + "\r\n"
                                + Lan.g(this, "Subject") + ": " + replyToEmailMessage.Subject
                                + "\r\n\r\n" + replyToEmailMessage.BodyText;
            }
            if (patCur == null || family == null)
            {
                BlockSendSecureMessage("Patient's family not setup propertly. Make sure guarantor is valid.");
            }
            else
            {
                _listPatients = new List <Patient>();
                bool isGuar = patCur.Guarantor == patCur.PatNum;
                for (int i = 0; i < family.ListPats.Length; i++)
                {
                    Patient patFamilyMember = family.ListPats[i];
                    if (isGuar || patFamilyMember.PatNum == patNumSubj)
                    {
                        _listPatients.Add(patFamilyMember);
                        comboRegardingPatient.Items.Add(patFamilyMember.GetNameFL());
                        if (patFamilyMember.PatNum == patNumSubj)
                        {
                            comboRegardingPatient.SelectedIndex = (comboRegardingPatient.Items.Count - 1);
                        }
                    }
                }
            }
            notificationSubject   = PrefC.GetString(PrefName.PatientPortalNotifySubject);
            notificationBodyNoUrl = PrefC.GetString(PrefName.PatientPortalNotifyBody);
            notificationURL       = PrefC.GetString(PrefName.PatientPortalURL);
            _emailAddressSender   = EmailAddresses.GetByClinic(0);        //Default for clinic/practice.
            if (_emailAddressSender == null)
            {
                BlockSendNotificationMessage("Practice email is not setup properly. Setup practice email in setup.");
            }
            if (notificationSubject == "")
            {
                BlockSendNotificationMessage("Missing notification email subject. Create a subject in setup.");
            }
            if (notificationBodyNoUrl == "")
            {
                BlockSendNotificationMessage("Missing notification email body. Create a body in setup.");
            }
            if (_allowSendSecureMessage)
            {
                _secureMessage                = new EmailMessage();
                _secureMessage.FromAddress    = textFrom.Text;
                _secureMessage.ToAddress      = textTo.Text;
                _secureMessage.PatNum         = patCur.PatNum;
                _secureMessage.SentOrReceived = EmailSentOrReceived.WebMailSent;                //this is secure so mark as webmail sent
                _secureMessage.ProvNumWebMail = priProvNum;
            }
            if (_allowSendNotificationMessage)
            {
                _insecureMessage                = new EmailMessage();
                _insecureMessage.FromAddress    = _emailAddressSender.SenderAddress;
                _insecureMessage.ToAddress      = patCur.Email;
                _insecureMessage.PatNum         = patCur.PatNum;
                _insecureMessage.Subject        = notificationSubject;
                _insecureMessage.BodyText       = notificationBodyNoUrl.Replace("[URL]", notificationURL);
                _insecureMessage.SentOrReceived = EmailSentOrReceived.Sent;               //this is not secure so just mark as regular sent
            }
            if (_allowSendSecureMessage && _allowSendNotificationMessage)
            {
                labelNotification.Text = Lan.g(this, "Notification email will be sent to patient") + ": " + patCur.Email;
            }
        }