///<summary></summary>
		public FormEmailMessageEdit(EmailMessage messageCur){
			InitializeComponent();// Required for Windows Form Designer support
			Lan.F(this);
			MessageCur=messageCur.Copy();
			_patCur=Patients.GetPat(messageCur.PatNum);//we could just as easily pass this in.
			listAttachments.ContextMenu=contextMenuAttachments;
		}
Example #2
0
 ///<summary></summary>
 public FormEmailMessageEdit(EmailMessage messageCur)
 {
     InitializeComponent();// Required for Windows Form Designer support
     //PatNum=patNum;
     Lan.F(this);
     MessageCur=messageCur.Copy();
     listAttachments.ContextMenu=contextMenuAttachments;
 }
Example #3
0
 ///<summary></summary>
 public static void Delete(EmailMessage message)
 {
     if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
         Meth.GetVoid(MethodBase.GetCurrentMethod(),message);
         return;
     }
     if(message.EmailMessageNum==0){
         return;//this prevents deletion of all commlog entries of something goes wrong.
     }
     string command="DELETE FROM emailmessage WHERE EmailMessageNum="+POut.Long(message.EmailMessageNum);
     Db.NonQ(command);
 }
		///<summary></summary>
		public static void Update(EmailMessage message){
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				Meth.GetVoid(MethodBase.GetCurrentMethod(),message);
				return;
			}
			Crud.EmailMessageCrud.Update(message);
			//now, delete all attachments and recreate.
			string command="DELETE FROM emailattach WHERE EmailMessageNum="+POut.Long(message.EmailMessageNum);
			Db.NonQ(command);
			for(int i=0;i<message.Attachments.Count;i++) {
				message.Attachments[i].EmailMessageNum=message.EmailMessageNum;
				EmailAttaches.Insert(message.Attachments[i]);
			}
		}
Example #5
0
 ///<summary></summary>
 public static long Insert(EmailMessage message)
 {
     if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
         message.EmailMessageNum=Meth.GetLong(MethodBase.GetCurrentMethod(),message);
         return message.EmailMessageNum;
     }
     Crud.EmailMessageCrud.Insert(message);
     //now, insert all the attaches.
     for(int i=0;i<message.Attachments.Count;i++) {
         message.Attachments[i].EmailMessageNum=message.EmailMessageNum;
         EmailAttaches.Insert(message.Attachments[i]);
     }
     return message.EmailMessageNum;
 }
Example #6
0
		private void OnEmail_Click() {
			//this button item will be disabled if pat does not have email address
			if(!Security.IsAuthorized(Permissions.EmailSend)){
				return;
			}
			EmailMessage message=new EmailMessage();
			message.PatNum=CurPatNum;
			Patient pat=Patients.GetPat(CurPatNum);
			message.ToAddress=pat.Email;
			message.FromAddress=EmailAddresses.GetByClinic(pat.ClinicNum).SenderAddress;
			FormEmailMessageEdit FormE=new FormEmailMessageEdit(message);
			FormE.IsNew=true;
			FormE.ShowDialog();
			if(FormE.DialogResult==DialogResult.OK) {
				RefreshCurrentModule();
			}
		}
Example #7
0
		///<summary></summary>
		public FormEmailMessageEdit(EmailMessage emailMessage){
			InitializeComponent();// Required for Windows Form Designer support
			Lan.F(this);
			_emailMessage=emailMessage.Copy();
		}
Example #8
0
 /// <summary>Also displays the dialog for the email.  Must have already created and attached the pdf.  Returns false if it could not create the email.</summary>
 private bool CreateEmailMessage()
 {
     string attachPath=FormEmailMessageEdit.GetAttachPath();
     Random rnd=new Random();
     string fileName=DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()+rnd.Next(1000).ToString()+".pdf";
     string filePathAndName=ODFileUtils.CombinePaths(attachPath,fileName);
     if(!PrefC.UsingAtoZfolder){
         MsgBox.Show(this,"Could not create email because no AtoZ folder.");
         return false;
     }
     Patient pat=Patients.GetPat(StmtCur.PatNum);
     string oldPath=ODFileUtils.CombinePaths(ImageStore.GetPatientFolder(pat,ImageStore.GetPreferredAtoZpath()),Documents.GetByNum(StmtCur.DocNum).FileName);
     File.Copy(oldPath,filePathAndName);//
     //Process.Start(filePathAndName);
     EmailMessage message=new EmailMessage();
     message.PatNum=pat.PatNum;
     message.ToAddress=pat.Email;
     message.FromAddress=PrefC.GetString(PrefName.EmailSenderAddress);
     string str;
     str=PrefC.GetString(PrefName.BillingEmailSubject);
     str=str.Replace("[nameF]",pat.GetNameFirst());
     str=str.Replace("[nameFL]",pat.GetNameFL());
     str=str.Replace("[namePref]",pat.Preferred);
     str=str.Replace("[PatNum]",pat.PatNum.ToString());
     message.Subject=str;
     str=PrefC.GetString(PrefName.BillingEmailBodyText);
     str=str.Replace("[nameF]",pat.GetNameFirst());
     str=str.Replace("[nameFL]",pat.GetNameFL());
     str=str.Replace("[namePref]",pat.Preferred);
     str=str.Replace("[PatNum]",pat.PatNum.ToString());
     message.BodyText=str;
     EmailAttach attach=new EmailAttach();
     attach.DisplayedFileName="Statement.pdf";
     attach.ActualFileName=fileName;
     message.Attachments.Add(attach);
     FormEmailMessageEdit FormE=new FormEmailMessageEdit(message);
     FormE.IsNew=true;
     FormE.ShowDialog();
     if(FormE.DialogResult==DialogResult.OK){
         return true;
     }
     return false;
 }
Example #9
0
		private void ToolBarMainEmail_Click() {
			if(PrefC.GetBool(PrefName.FuchsOptionsOn)) {
				if(checkShowDiscount.Checked || checkShowIns.Checked) {
					if(MessageBox.Show(this,string.Format(Lan.g(this,"Do you want to remove insurance estimates and PPO discounts from e-mailed treatment plan?")),"Open Dental",MessageBoxButtons.YesNo,MessageBoxIcon.Question) != DialogResult.No) {
						checkShowDiscount.Checked=false;
						checkShowIns.Checked=false;
						FillMain();
					}
				}
			}
			PrepImageForPrinting();
			string attachPath=EmailMessages.GetEmailAttachPath();
			Random rnd=new Random();
			string fileName=DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()+rnd.Next(1000).ToString()+".pdf";
			string filePathAndName=ODFileUtils.CombinePaths(attachPath,fileName);
			MigraDoc.Rendering.PdfDocumentRenderer pdfRenderer=new MigraDoc.Rendering.PdfDocumentRenderer(true,PdfFontEmbedding.Always);
			pdfRenderer.Document=CreateDocument();
			pdfRenderer.RenderDocument();
			pdfRenderer.PdfDocument.Save(filePathAndName);
			//Process.Start(filePathAndName);
			EmailMessage message=new EmailMessage();
			message.PatNum=PatCur.PatNum;
			message.ToAddress=PatCur.Email;
			message.FromAddress=EmailAddresses.GetByClinic(PatCur.ClinicNum).SenderAddress;
			message.Subject=Lan.g(this,"Treatment Plan");
			EmailAttach attach=new EmailAttach();
			attach.DisplayedFileName="TreatmentPlan.pdf";
			attach.ActualFileName=fileName;
			message.Attachments.Add(attach);
			FormEmailMessageEdit FormE=new FormEmailMessageEdit(message);
			FormE.IsNew=true;
			FormE.ShowDialog();
			//if(FormE.DialogResult==DialogResult.OK) {
			//	RefreshCurrentModule();
			//}
		}
Example #10
0
 private void OnEmail_Click()
 {
     //this button item will be disabled if pat does not have email address
     EmailMessage message=new EmailMessage();
     message.PatNum=CurPatNum;
     Patient pat=Patients.GetPat(CurPatNum);
     message.ToAddress=pat.Email;
     message.FromAddress=PrefC.GetString(PrefName.EmailSenderAddress);
     FormEmailMessageEdit FormE=new FormEmailMessageEdit(message);
     FormE.IsNew=true;
     FormE.ShowDialog();
     if(FormE.DialogResult==DialogResult.OK) {
         RefreshCurrentModule();
     }
 }
Example #11
0
		///<summary>Can throw an exception if there is a permission issue saving the file.</summary>
		public static void CreateAttachmentFromText(EmailMessage emailMessage,string strAttachText,string strDisplayFileName) {
			//No need to check RemotingRole; no call to db.
			Random rnd=new Random();
			EmailAttach emailAttach;
			//create the attachment
			emailAttach=new EmailAttach();
			emailAttach.DisplayedFileName=strDisplayFileName;
			emailAttach.ActualFileName=DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()+rnd.Next(1000).ToString()+Path.GetExtension(strDisplayFileName);//To make unique.
			string strAttachFilePath=ODFileUtils.CombinePaths(EmailMessages.GetEmailAttachPath(),emailAttach.ActualFileName);
			File.WriteAllText(strAttachFilePath,strAttachText);
			emailMessage.Attachments.Add(emailAttach);
		}
Example #12
0
		private void butRefresh_Click(object sender,EventArgs e) {
			List<EmailAttach> listEmailAttachOld=_emailMessage.Attachments;
			Cursor=Cursors.WaitCursor;
			EmailAddress emailAddress=emailPreview.GetEmailAddress();
			try {
				_emailMessage=EmailMessages.ProcessRawEmailMessageIn(_emailMessage.RawEmailIn,_emailMessage.EmailMessageNum,emailAddress,false);
				EmailMessages.UpdateSentOrReceivedRead(_emailMessage);//Mark read, because we are already viewing the message within the current window.
				RefreshAll();
			}
			catch(Exception ex) {
				MessageBox.Show(Lan.g(this,"Refreshing failed.")+"\r\n"+ex.Message);
				Cursor=Cursors.Default;
				return;
			}
			Cursor=Cursors.Default;
			string attachPath=EmailAttaches.GetAttachPath();
			for(int i=0;i<listEmailAttachOld.Count;i++) {//For each old attachment, attempt to delete.  The new attachments were created with different names in ProcessRawEmailMessage().
				string filePath=ODFileUtils.CombinePaths(attachPath,listEmailAttachOld[i].ActualFileName);
				try {
					File.Delete(filePath);//Deleting old file. If it fails there was no file, or permission problems.
				}
				catch {
					//The file will take a little bit of extra hard drive space, but the file is not referened and cannot hurt anything.
				}
			}
		}
		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 butEmail_Click(object sender,EventArgs e) {
			if(gridMain.Rows.Count < 1){
        MessageBox.Show(Lan.g(this,"There are no Patients in the Recall 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.RecallStatusEmailed)==0){
				MsgBox.Show(this,"You need to set a status first in the Recall Setup window.");
				return;
			}
			if(gridMain.SelectedIndices.Length==0){
				ContactMethod cmeth;
				for(int i=0;i<table.Rows.Count;i++){
					cmeth=(ContactMethod)PIn.Long(table.Rows[i]["PreferRecallMethod"].ToString());
					if(cmeth!=ContactMethod.Email){
						continue;
					}
					if(table.Rows[i]["Email"].ToString()=="") {
						continue;
					}
					gridMain.SetSelected(i,true);
				}
				if(gridMain.SelectedIndices.Length==0){
					MsgBox.Show(this,"No patients of email type.");
					return;
				}
			}
			else{//deselect the ones that do not have email addresses specified
				int skipped=0;
				for(int i=gridMain.SelectedIndices.Length-1;i>=0;i--){
					if(table.Rows[gridMain.SelectedIndices[i]]["Email"].ToString()==""){
						skipped++;
						gridMain.SetSelected(gridMain.SelectedIndices[i],false);
					}
				}
				if(gridMain.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;
			List<long> recallNums=new List<long>();
      for(int i=0;i<gridMain.SelectedIndices.Length;i++){
        recallNums.Add(PIn.Long(table.Rows[gridMain.SelectedIndices[i]]["RecallNum"].ToString()));
      }
			RecallListSort sortBy=(RecallListSort)comboSort.SelectedIndex;
			addrTable=Recalls.GetAddrTable(recallNums,checkGroupFamilies.Checked,sortBy);
			EmailMessage message;
			string str="";
			string[] recallNumArray;
			string[] patNumArray;
			EmailAddress emailAddress;
			for(int i=0;i<addrTable.Rows.Count;i++){
				message=new EmailMessage();
				message.PatNum=PIn.Long(addrTable.Rows[i]["emailPatNum"].ToString());
				message.ToAddress=PIn.String(addrTable.Rows[i]["email"].ToString());//might be guarantor email
				emailAddress=EmailAddresses.GetByClinic(PIn.Long(addrTable.Rows[i]["ClinicNum"].ToString()));
				message.FromAddress=emailAddress.SenderAddress;
				if(addrTable.Rows[i]["numberOfReminders"].ToString()=="0") {
					message.Subject=PrefC.GetString(PrefName.RecallEmailSubject);
				}
				else if(addrTable.Rows[i]["numberOfReminders"].ToString()=="1") {
					message.Subject=PrefC.GetString(PrefName.RecallEmailSubject2);
				}
				else {
					message.Subject=PrefC.GetString(PrefName.RecallEmailSubject3);
				}
				//family
				if(checkGroupFamilies.Checked	&& addrTable.Rows[i]["famList"].ToString()!="") {
					if(addrTable.Rows[i]["numberOfReminders"].ToString()=="0") {
						str=PrefC.GetString(PrefName.RecallEmailFamMsg);
					}
					else if(addrTable.Rows[i]["numberOfReminders"].ToString()=="1") {
						str=PrefC.GetString(PrefName.RecallEmailFamMsg2);
					}
					else {
						str=PrefC.GetString(PrefName.RecallEmailFamMsg3);
					}
					str=str.Replace("[FamilyList]",addrTable.Rows[i]["famList"].ToString());
				}
				//single
				else {
					if(addrTable.Rows[i]["numberOfReminders"].ToString()=="0") {
						str=PrefC.GetString(PrefName.RecallEmailMessage);
					}
					else if(addrTable.Rows[i]["numberOfReminders"].ToString()=="1") {
						str=PrefC.GetString(PrefName.RecallEmailMessage2);
					}
					else {
						str=PrefC.GetString(PrefName.RecallEmailMessage3);
					}
					str=str.Replace("[DueDate]",PIn.Date(addrTable.Rows[i]["dateDue"].ToString()).ToShortDateString());
					str=str.Replace("[NameF]",addrTable.Rows[i]["patientNameF"].ToString());
					str=str.Replace("[NameFL]",addrTable.Rows[i]["patientNameFL"].ToString());
				}
				message.BodyText=str;
				try{
					EmailMessages.SendEmailUnsecure(message,emailAddress);
				}
				catch(Exception ex){
					Cursor=Cursors.Default;
					str=ex.Message+"\r\n";
					if(ex.GetType()==typeof(System.ArgumentException)){
						str+="Go to Setup, Recall.  The subject for an email may not be multiple lines.\r\n";
					}
					MessageBox.Show(str+"Patient:"+addrTable.Rows[i]["patientNameFL"].ToString());
					break;
				}
				message.MsgDateTime=DateTime.Now;
				message.SentOrReceived=EmailSentOrReceived.Sent;
				EmailMessages.Insert(message);
				recallNumArray=addrTable.Rows[i]["recallNums"].ToString().Split(',');
				patNumArray=addrTable.Rows[i]["patNums"].ToString().Split(',');
				for(int r=0;r<recallNumArray.Length;r++){
					Commlogs.InsertForRecall(PIn.Long(patNumArray[r]),CommItemMode.Email,PIn.Int(addrTable.Rows[i]["numberOfReminders"].ToString()),
						PrefC.GetLong(PrefName.RecallStatusEmailed));
					Recalls.UpdateStatus(PIn.Long(recallNumArray[r]),PrefC.GetLong(PrefName.RecallStatusEmailed));
				}
			}
			FillMain(null);
			Cursor=Cursors.Default;
		}
Example #15
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(PrefC.GetString(PrefName.EmailSMTPserver)=="") {
         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;
             }
             grid.SetSelected(i,true);
         }
         if(grid.SelectedIndices.Length==0) {
             MsgBox.Show(this,"No patients of email type.");
             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="";
     //Appointment apt;
     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.
         message.FromAddress=PrefC.GetString(PrefName.EmailSenderAddress);
         message.Subject=PrefC.GetString(PrefName.ConfirmEmailSubject);
         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 {
             FormEmailMessageEdit.SendEmail(message);
         }
         catch(Exception ex) {
             Cursor=Cursors.Default;
             MessageBox.Show(ex.Message+"\r\nPatient:"+table.Rows[grid.SelectedIndices[i]]["nameFL"].ToString());
             break;
         }
         message.MsgDateTime=DateTime.Now;
         message.SentOrReceived=CommSentOrReceived.Sent;
         EmailMessages.Insert(message);
         Appointments.SetConfirmed(PIn.Long(table.Rows[grid.SelectedIndices[i]]["AptNum"].ToString()),PrefC.GetLong(PrefName.ConfirmStatusEmailed));
     }
     FillMain();
     Cursor=Cursors.Default;
 }
Example #16
0
		/// <summary>This is used from wherever unencrypted email needs to be sent throughout the program.  If a message must be encrypted, then encrypt it before calling this function.
		///Surround with a try catch.</summary>
		public static void SendEmailUnsecure(EmailMessage emailMessage,EmailAddress emailAddress) {
			//No need to check RemotingRole; no call to db.
			SendEmailUnsecure(emailMessage,emailAddress,null);
		}
Example #17
0
		/// <summary>This is used from wherever email needs to be sent throughout the program.  If a message must be encrypted, then encrypt it before calling this function.  nameValueCollectionHeaders can be null.</summary>
		private static void SendEmailUnsecure(EmailMessage emailMessage,EmailAddress emailAddress,NameValueCollection nameValueCollectionHeaders,params AlternateView[] arrayAlternateViews) {
			//No need to check RemotingRole; no call to db.
			if(emailAddress.ServerPort==465) {//implicit
				//uses System.Web.Mail, which is marked as deprecated, but still supports implicit
				System.Web.Mail.MailMessage message=new System.Web.Mail.MailMessage();
				message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver",emailAddress.SMTPserver);
				message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport","465");
				message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing","2");//sendusing: cdoSendUsingPort, value 2, for sending the message using the network.
				message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate","1");//0=anonymous,1=clear text auth,2=context
				message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername",emailAddress.EmailUsername.Trim());
				message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword",emailAddress.EmailPassword);
				//if(PrefC.GetBool(PrefName.EmailUseSSL)) {
				message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl","true");//false was also tested and does not work
				message.From=emailMessage.FromAddress.Trim();
				message.To=emailMessage.ToAddress.Trim();
				message.Subject=Tidy(emailMessage.Subject);
				message.Body=Tidy(emailMessage.BodyText);
				//message.Cc=;
				//message.Bcc=;
				//message.UrlContentBase=;
				//message.UrlContentLocation=;
				message.BodyEncoding=System.Text.Encoding.UTF8;
				message.BodyFormat=System.Web.Mail.MailFormat.Text;//or .Html
				if(nameValueCollectionHeaders!=null) {
					string[] arrayHeaderKeys=nameValueCollectionHeaders.AllKeys;
					for(int i=0;i<arrayHeaderKeys.Length;i++) {//Needed for Direct Acks to work.
						message.Headers.Add(arrayHeaderKeys[i],nameValueCollectionHeaders[arrayHeaderKeys[i]]);
					}
				}
				//TODO: We need to add some kind of alternatve view or similar replacement for outgoing Direct messages to work with SSL. Write the body to a temporary file and attach with the correct mime type and name?
				string attachPath=EmailMessages.GetEmailAttachPath();
				System.Web.Mail.MailAttachment attach;
				//foreach (string sSubstr in sAttach.Split(delim)){
				for(int i=0;i<emailMessage.Attachments.Count;i++) {
					attach=new System.Web.Mail.MailAttachment(ODFileUtils.CombinePaths(attachPath,emailMessage.Attachments[i].ActualFileName));
					//no way to set displayed filename
					message.Attachments.Add(attach);
				}
				System.Web.Mail.SmtpMail.SmtpServer=emailAddress.SMTPserver+":465";//"smtp.gmail.com:465";
				System.Web.Mail.SmtpMail.Send(message);
			}
			else {//explicit default port 587 
				SmtpClient client=new SmtpClient(emailAddress.SMTPserver,emailAddress.ServerPort);
				//The default credentials are not used by default, according to: 
				//http://msdn2.microsoft.com/en-us/library/system.net.mail.smtpclient.usedefaultcredentials.aspx
				client.Credentials=new NetworkCredential(emailAddress.EmailUsername.Trim(),emailAddress.EmailPassword);
				client.DeliveryMethod=SmtpDeliveryMethod.Network;
				client.EnableSsl=emailAddress.UseSSL;
				client.Timeout=180000;//3 minutes
				MailMessage message=new MailMessage();
				message.From=new MailAddress(emailMessage.FromAddress.Trim());
				message.To.Add(emailMessage.ToAddress.Trim());
				message.Subject=Tidy(emailMessage.Subject);
				message.Body=Tidy(emailMessage.BodyText);
				message.IsBodyHtml=false;
				if(nameValueCollectionHeaders!=null) {
					message.Headers.Add(nameValueCollectionHeaders);//Needed for Direct Acks to work.
				}
				for(int i=0;i<arrayAlternateViews.Length;i++) {//Needed for Direct messages to be interpreted encrypted on the receiver's end.
					message.AlternateViews.Add(arrayAlternateViews[i]);
				}
				string attachPath=EmailMessages.GetEmailAttachPath();
				Attachment attach;
				for(int i=0;i<emailMessage.Attachments.Count;i++) {
					attach=new Attachment(ODFileUtils.CombinePaths(attachPath,emailMessage.Attachments[i].ActualFileName));
					//@"C:\OpenDentalData\EmailAttachments\1");
					attach.Name=emailMessage.Attachments[i].DisplayedFileName;
					//"canadian.gif";
					message.Attachments.Add(attach);
				}
				client.Send(message);
			}
		}
Example #18
0
		///<summary>Encrypts the message, verifies trust, locates the public encryption key for the To address (if already stored locally), etc.  emailMessage.  
		///Use this polymorphism when the attachments have already been saved to the email attachments folder in file form.  patNum can be 0.
		///Returns an empty string upon success, or an error string if there were errors.  It is possible that the email was sent to some trusted recipients and not sent to untrusted recipients (in which case there would be errors but some recipients would receive successfully).
		///Surround with a try catch.</summary>
		public static string SendEmailDirect(EmailMessage emailMessage,EmailAddress emailAddressFrom) {
			//No need to check RemotingRole; no call to db.
			emailMessage.FromAddress=emailAddressFrom.EmailUsername.Trim();//Cannot be emailAddressFrom.SenderAddress, or else will not find the correct encryption certificate.  Used in ConvertEmailMessageToMessage().
			//Start by converting the emailMessage to an unencrypted message using the Direct libraries. The email must be in this form to carry out encryption.
			Health.Direct.Common.Mail.Message msgUnencrypted=ConvertEmailMessageToMessage(emailMessage,true);
			Health.Direct.Agent.MessageEnvelope msgEnvelopeUnencrypted=new Health.Direct.Agent.MessageEnvelope(msgUnencrypted);
			Health.Direct.Agent.OutgoingMessage outMsgUnencrypted=new Health.Direct.Agent.OutgoingMessage(msgEnvelopeUnencrypted);
			string strErrors=SendEmailDirect(outMsgUnencrypted,emailAddressFrom);
			return strErrors;
		}
Example #19
0
		///<summary>Updates SentOrReceived and saves changes to db.  Better than using Update(), because does not delete and add attachments back into db.</summary>
		public static void UpdatePatNum(EmailMessage emailMessage) {
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				Meth.GetVoid(MethodBase.GetCurrentMethod(),emailMessage);
				return;
			}
			string command="UPDATE emailmessage SET PatNum="+POut.Long(emailMessage.PatNum)+" WHERE EmailMessageNum="+POut.Long(emailMessage.EmailMessageNum);
			Db.NonQ(command);
			if(emailMessage.Attachments==null) {
				return;
			}
			for(int i=0;i<emailMessage.Attachments.Count;i++) {
				EhrSummaryCcd ehrSummaryCcd=EhrSummaryCcds.GetOneForEmailAttach(emailMessage.Attachments[i].EmailAttachNum);
				if(ehrSummaryCcd!=null) {
					ehrSummaryCcd.PatNum=emailMessage.PatNum;
					EhrSummaryCcds.Update(ehrSummaryCcd);
				}
			}
		}
Example #20
0
		///<summary>This method is only for ehr testing purposes, and it always uses the hidden pref EHREmailToAddress to send to.  For privacy reasons, this cannot be used with production patient info.  AttachName should include extension.</summary>
		public static void SendTestUnsecure(string subjectAndBody,string attachName1,string attachContents1,string attachName2,string attachContents2) {
			//No need to check RemotingRole; no call to db.
			string strTo=PrefC.GetString(PrefName.EHREmailToAddress);
			if(strTo=="") {
				throw new ApplicationException("This feature cannot be used except in a test environment because email is not secure.");
			}
			EmailAddress emailAddressFrom=EmailAddresses.GetByClinic(0);
			EmailMessage emailMessage=new EmailMessage();
			emailMessage.FromAddress=emailAddressFrom.EmailUsername.Trim();
			emailMessage.ToAddress=strTo.Trim();
			emailMessage.Subject=subjectAndBody;
			emailMessage.BodyText=subjectAndBody;
			if(attachName1!="") {
				EmailAttach emailAttach=CreateAttachInAttachPath(attachName1,attachContents1);
				emailMessage.Attachments.Add(emailAttach);
			}
			if(attachName2!="") {
				EmailAttach emailAttach=CreateAttachInAttachPath(attachName2,attachContents2);
				emailMessage.Attachments.Add(emailAttach);
			}
			SendEmailUnsecure(emailMessage,emailAddressFrom);
			Insert(emailMessage);
		}
Example #21
0
 private void butSend_Click(object sender, System.EventArgs e)
 {
     if(gridBill.SelectedIndices.Length==0){
         MessageBox.Show(Lan.g(this,"Please select items first."));
         return;
     }
     labelPrinted.Text=Lan.g(this,"Printed=")+"0";
     labelEmailed.Text=Lan.g(this,"E-mailed=")+"0";
     labelSentElect.Text=Lan.g(this,"SentElect=")+"0";
     if(!MsgBox.Show(this,true,"Please be prepared to wait up to ten minutes while all the bills get processed.\r\nOnce complete, the pdf print preview will be launched in Adobe Reader.  You will print from that program.  Continue?")){
         return;
     }
     Cursor=Cursors.WaitCursor;
     isPrinting=true;
     FormRpStatement FormST=new FormRpStatement();
     Statement stmt;
     Random rnd;
     string fileName;
     string filePathAndName;
     string attachPath;
     EmailMessage message;
     EmailAttach attach;
     Family fam;
     Patient pat;
     string patFolder;
     int skipped=0;
     int emailed=0;
     int printed=0;
     int sentelect=0;
     //FormEmailMessageEdit FormEME=new FormEmailMessageEdit();
     //if(ImageStore.UpdatePatient == null){
     //	ImageStore.UpdatePatient = new FileStore.UpdatePatientDelegate(Patients.Update);
     //}
     //OpenDental.Imaging.ImageStoreBase imageStore;
     //Concat all the pdf's together to create one print job.
     //Also, if a statement is to be emailed, it does that here and does not attach it to the print job.
     //If something fails badly, it's no big deal, because we can click the radio button to see "sent" bills, and unsend them from there.
       PdfDocument outputDocument=new PdfDocument();
     PdfDocument inputDocument;
     PdfPage page;
     string savedPdfPath;
     PrintDocument pd=null;
     XmlWriterSettings xmlSettings=new XmlWriterSettings();
     xmlSettings.OmitXmlDeclaration=true;
     xmlSettings.Encoding=Encoding.UTF8;
     xmlSettings.Indent=true;
     xmlSettings.IndentChars="   ";
     StringBuilder strBuildElect=new StringBuilder();
     XmlWriter writerElect=XmlWriter.Create(strBuildElect,xmlSettings);
     //OpenDental.Bridges.Tesia_statements.GeneratePracticeInfo(writerElect);
     OpenDental.Bridges.EHG_statements.GeneratePracticeInfo(writerElect);
     DataSet dataSet;
     List<long> stateNumsElect=new List<long>();
     for(int i=0;i<gridBill.SelectedIndices.Length;i++){
         stmt=Statements.CreateObject(PIn.Long(table.Rows[gridBill.SelectedIndices[i]]["StatementNum"].ToString()));
         fam=Patients.GetFamily(stmt.PatNum);
         pat=fam.GetPatient(stmt.PatNum);
         patFolder=ImageStore.GetPatientFolder(pat,ImageStore.GetPreferredAtoZpath());
         dataSet=AccountModules.GetStatementDataSet(stmt);
         if(stmt.Mode_==StatementMode.Email){
             if(PrefC.GetString(PrefName.EmailSMTPserver)==""){
                 MsgBox.Show(this,"You need to enter an SMTP server name in e-mail setup before you can send e-mail.");
                 Cursor=Cursors.Default;
                 isPrinting=false;
                 //FillGrid();//automatic
                 return;
             }
             if(pat.Email==""){
                 skipped++;
                 continue;
             }
         }
         stmt.IsSent=true;
         stmt.DateSent=DateTime.Today;
         FormST.CreateStatementPdf(stmt,pat,fam,dataSet);
         if(stmt.DocNum==0){
             MsgBox.Show(this,"Failed to save PDF.  In Setup, DataPaths, please make sure the top radio button is checked.");
             Cursor=Cursors.Default;
             isPrinting=false;
             return;
         }
         //imageStore = OpenDental.Imaging.ImageStore.GetImageStore(pat);
         savedPdfPath=ImageStore.GetFilePath(Documents.GetByNum(stmt.DocNum),patFolder);
         if(stmt.Mode_==StatementMode.InPerson || stmt.Mode_==StatementMode.Mail){
             if(pd==null){
                 pd=new PrintDocument();
             }
             inputDocument=PdfReader.Open(savedPdfPath,PdfDocumentOpenMode.Import);
             for(int idx=0;idx<inputDocument.PageCount;idx++){
                 page=inputDocument.Pages[idx];
                 outputDocument.AddPage(page);
             }
             printed++;
             labelPrinted.Text=Lan.g(this,"Printed=")+printed.ToString();
             Application.DoEvents();
             Statements.MarkSent(stmt.StatementNum,stmt.DateSent);
         }
         if(stmt.Mode_==StatementMode.Email){
             attachPath=FormEmailMessageEdit.GetAttachPath();
             rnd=new Random();
             fileName=DateTime.Now.ToString("yyyyMMdd")+"_"+DateTime.Now.TimeOfDay.Ticks.ToString()+rnd.Next(1000).ToString()+".pdf";
             filePathAndName=ODFileUtils.CombinePaths(attachPath,fileName);
             File.Copy(savedPdfPath,filePathAndName);
             //Process.Start(filePathAndName);
             message=new EmailMessage();
             message.PatNum=pat.PatNum;
             message.ToAddress=pat.Email;
             message.FromAddress=PrefC.GetString(PrefName.EmailSenderAddress);
             string str;
             str=PrefC.GetString(PrefName.BillingEmailSubject);
             str=str.Replace("[nameF]",pat.GetNameFirst());
             str=str.Replace("[nameFL]",pat.GetNameFL());
             str=str.Replace("[namePref]",pat.Preferred);
             str=str.Replace("[PatNum]",pat.PatNum.ToString());
             message.Subject=str;
             str=PrefC.GetString(PrefName.BillingEmailBodyText);
             str=str.Replace("[nameF]",pat.GetNameFirst());
             str=str.Replace("[nameFL]",pat.GetNameFL());
             str=str.Replace("[namePref]",pat.Preferred);
             str=str.Replace("[PatNum]",pat.PatNum.ToString());
             message.BodyText=str;
             attach=new EmailAttach();
             attach.DisplayedFileName="Statement.pdf";
             attach.ActualFileName=fileName;
             message.Attachments.Add(attach);
             try{
                 FormEmailMessageEdit.SendEmail(message);
                 emailed++;
                 labelEmailed.Text=Lan.g(this,"E-mailed=")+emailed.ToString();
                 Application.DoEvents();
             }
             catch{
                 //Cursor=Cursors.Default;
                 //MessageBox.Show(ex.Message);
                 //return;
                 skipped++;
                 continue;
             }
             Statements.MarkSent(stmt.StatementNum,stmt.DateSent);
         }
         if(stmt.Mode_==StatementMode.Electronic) {
             stateNumsElect.Add(stmt.StatementNum);
             //OpenDental.Bridges.Tesia_statements.GenerateOneStatement(writerElect,stmt,pat,fam,dataSet);
             OpenDental.Bridges.EHG_statements.GenerateOneStatement(writerElect,stmt,pat,fam,dataSet);
             sentelect++;
             labelSentElect.Text=Lan.g(this,"SentElect=")+sentelect.ToString();
             Application.DoEvents();
             //do this later:
             //Statements.MarkSent(stmt.StatementNum,stmt.DateSent);
         }
     }
     //now print-------------------------------------------------------------------------------------
     if(pd!=null){
         string tempFileOutputDocument=Path.GetTempFileName()+".pdf";
         outputDocument.Save(tempFileOutputDocument);
         try{
             Process.Start(tempFileOutputDocument);
         }
         catch(Exception ex){
             MessageBox.Show(Lan.g(this,"Error: Please make sure Adobe Reader is installed.")+ex.Message);
         }
         //}
     }
     //finish up elect and send if needed------------------------------------------------------------
     if(sentelect>0) {
         //OpenDental.Bridges.Tesia_statements.GenerateWrapUp(writerElect);
         OpenDental.Bridges.EHG_statements.GenerateWrapUp(writerElect);
         writerElect.Close();
         try {
             //OpenDental.Bridges.Tesia_statements.Send(strBuildElect.ToString());
             OpenDental.Bridges.EHG_statements.Send(strBuildElect.ToString());
             //CodeBase.MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(strBuildElect.ToString());
             //msgbox.ShowDialog();
             //loop through all statements and mark sent
             for(int i=0;i<stateNumsElect.Count;i++) {
                 Statements.MarkSent(stateNumsElect[i],DateTime.Today);
             }
         }
         catch(Exception ex) {
             MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(ex.Message);
             msgbox.ShowDialog();
             //MessageBox.Show();
             sentelect=0;
             labelSentElect.Text=Lan.g(this,"SentElect=")+sentelect.ToString();
         }
     }
     else {
         writerElect.Close();
     }
     string msg="";
     if(skipped>0){
         msg+=Lan.g(this,"Skipped due to missing or bad email address: ")+skipped.ToString()+"\r\n";
     }
     msg+=Lan.g(this,"Printed: ")+printed.ToString()+"\r\n"
         +Lan.g(this,"E-mailed: ")+emailed.ToString()+"\r\n"
         +Lan.g(this,"SentElect: ")+sentelect.ToString();
     MessageBox.Show(msg);
     Cursor=Cursors.Default;
     isPrinting=false;
     FillGrid();//not automatic
 }
Example #22
0
		///<summary>Converts the Health.Direct.Common.Mail.Message into an OD EmailMessage.  The Direct library is used for both encrypted and unencrypted email.  Set hasAttachments to false to exclude attachments.</summary>
		private static EmailMessage ConvertMessageToEmailMessage(Health.Direct.Common.Mail.Message message,bool hasAttachments) {
			//No need to check RemotingRole; no call to db.
			EmailMessage emailMessage=new EmailMessage();
			emailMessage.FromAddress=message.FromValue.Trim();
			if(message.DateValue!=null) {//Is null when sending, but should not be null when receiving.
				//The received email message date must be in a very specific format and must match the RFC822 standard.  Is a required field for RFC822.  http://tools.ietf.org/html/rfc822
				//We need the received time from the server, so we can quickly identify messages which have already been downloaded and to avoid downloading duplicates.
				//Examples: "3 Dec 2013 17:10:37 -0800", "10 Dec 2013 17:10:37 -0800", "Tue, 5 Nov 2013 17:10:37 +0000 (UTC)", "Tue, 12 Nov 2013 17:10:37 +0000 (UTC)"
				if(message.DateValue.Contains(",")) {//The day-of-week, comma and following space are optional. Examples: "Tue, 3 Dec 2013 17:10:37 +0000", "Tue, 12 Nov 2013 17:10:37 +0000 (UTC)"
					try {
						emailMessage.MsgDateTime=DateTime.ParseExact(message.DateValue.Substring(0,31),"ddd, d MMM yyyy HH:mm:ss zzz",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
					}
					catch {
						emailMessage.MsgDateTime=DateTime.ParseExact(message.DateValue.Substring(0,30),"ddd, d MMM yyyy HH:mm:ss zzz",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
					}
				}
				else {//Examples: "3 Dec 2013 17:10:37 -0800", "12 Nov 2013 17:10:37 -0800 (UTC)"
					try {
						emailMessage.MsgDateTime=DateTime.ParseExact(message.DateValue.Substring(0,26),"d MMM yyyy HH:mm:ss zzz",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
					}
					catch {
						emailMessage.MsgDateTime=DateTime.ParseExact(message.DateValue.Substring(0,25),"d MMM yyyy HH:mm:ss zzz",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
					}
				}
			}
			else {//Sending the email.
				emailMessage.MsgDateTime=DateTime.Now;
			}
			emailMessage.Subject=Tidy(message.SubjectValue);
			emailMessage.ToAddress=message.ToValue.Trim();
			List<Health.Direct.Common.Mime.MimeEntity> listMimeParts=new List<Health.Direct.Common.Mime.MimeEntity>();//We want to treat one part and multiple part emails the same way below, so we make our own list.  If GetParts() is called when IsMultiPart is false, then an exception will be thrown by the Direct library.
			Health.Direct.Common.Mime.MimeEntity mimeEntity=null;
			try {
				mimeEntity=message.ExtractMimeEntity();
			}
			catch {
				emailMessage.BodyText=ProcessMimeTextPart(message.Body.Text);
				return emailMessage;
			}
			if(message.IsMultiPart) {
				foreach(Health.Direct.Common.Mime.MimeEntity mimePart in mimeEntity.GetParts()) {
					listMimeParts.Add(mimePart);
				}
			}
			else {//Single body part.
				listMimeParts.Add(mimeEntity);
			}
			List<Health.Direct.Common.Mime.MimeEntity> listMimeBodyTextParts=new List<Health.Direct.Common.Mime.MimeEntity>();
			List<Health.Direct.Common.Mime.MimeEntity> listMimeAttachParts=new List<Health.Direct.Common.Mime.MimeEntity>();
			for(int i=0;i<listMimeParts.Count;i++) {
				Health.Direct.Common.Mime.MimeEntity mimePart=listMimeParts[i];
				if(mimePart.ContentDisposition==null || !mimePart.ContentDisposition.ToLower().Contains("attachment")) {//Not an email attachment.  Treat as body text.
					listMimeBodyTextParts.Add(mimePart);
				}
				else {
					listMimeAttachParts.Add(mimePart);
				}
			}
			string strTextPartBoundary="";
			if(listMimeBodyTextParts.Count>1) {
				strTextPartBoundary=message.ParsedContentType.Boundary;
			}
			StringBuilder sbBodyText=new StringBuilder();
			for(int i=0;i<listMimeBodyTextParts.Count;i++) {
				if(strTextPartBoundary!="") {//For incoming Direct Ack messages.
					sbBodyText.Append("\r\n--"+strTextPartBoundary+"\r\n");
					sbBodyText.Append(listMimeBodyTextParts[i].ToString());//Includes not only the body text, but also content type and content disposition.
				}
				else {
					sbBodyText.Append(ProcessMimeTextPart(listMimeBodyTextParts[i].Body.Text));
				}
			}
			if(strTextPartBoundary!="") {
				sbBodyText.Append("\r\n--"+strTextPartBoundary+"--\r\n");
			}
			emailMessage.BodyText=sbBodyText.ToString();
			emailMessage.Attachments=new List<EmailAttach>();
			if(!hasAttachments) {
				return emailMessage;
			}
			for(int i=0;i<listMimeAttachParts.Count;i++) {
				Health.Direct.Common.Mime.MimeEntity mimePartAttach=listMimeAttachParts[i];
				string strAttachText=mimePartAttach.Body.Text;
				try {
					if(mimePartAttach.ContentTransferEncoding.ToLower().Contains("base64")) {
						strAttachText=Encoding.UTF8.GetString(Convert.FromBase64String(mimePartAttach.Body.Text));
					}
				}
				catch {
				}
				EmailAttach emailAttach=CreateAttachInAttachPath(mimePartAttach.ParsedContentType.Name,strAttachText);
				if(mimePartAttach.ParsedContentType.Name.ToLower()=="smime.p7m") {//encrypted attachment
					message.ContentType="application/pkcs7-mime; name=smime.p7m; boundary="+strTextPartBoundary+";";
				}
				emailMessage.Attachments.Add(emailAttach);//The attachment EmailMessageNum is set when the emailMessage is inserted/updated below.					
			}
			return emailMessage;
		}
Example #23
0
		private void butDecrypt_Click(object sender,EventArgs e) {
			if(!EmailMessages.IsAddressTrusted(_emailMessage.FromAddress)) {//Not trusted yet.
				string strTrustMessage=Lan.g(this,"The sender address must be added to your trusted addresses before you can decrypt the email")
					+". "+Lan.g(this,"Add")+" "+_emailMessage.FromAddress+" "+Lan.g(this,"to trusted addresses")+"?";
				if(MessageBox.Show(strTrustMessage,"",MessageBoxButtons.OKCancel)==DialogResult.OK) {
					Cursor=Cursors.WaitCursor;
					EmailMessages.TryAddTrustDirect(_emailMessage.FromAddress);
					Cursor=Cursors.Default;
					if(!EmailMessages.IsAddressTrusted(_emailMessage.FromAddress)) {
						MsgBox.Show(this,"Failed to trust sender because a valid certificate could not be located.");
						return;
					}
				}
				else {
					MsgBox.Show(this,"Cannot decrypt message from untrusted sender.");
					return;
				}
			}
			Cursor=Cursors.WaitCursor;
			EmailAddress emailAddress=emailPreview.GetEmailAddress();
			try {
				_emailMessage=EmailMessages.ProcessRawEmailMessageIn(_emailMessage.BodyText,_emailMessage.EmailMessageNum,emailAddress,true);//If decryption is successful, sets status to ReceivedDirect.
				//The Direct message was decrypted.
				EmailMessages.UpdateSentOrReceivedRead(_emailMessage);//Mark read, because we are already viewing the message within the current window.					
				RefreshAll();
			}
			catch(Exception ex) {
				MessageBox.Show(Lan.g(this,"Decryption failed.")+"\r\n"+ex.Message);
				//Error=InvalidEncryption: means that someone used the wrong certificate when sending the email to this inbox, and we tried to decrypt with a different certificate.
				//Error=NoTrustedRecipients: means the sender is not added to the trust anchors in mmc.
			}
			Cursor=Cursors.Default;
		}
Example #24
0
		///<summary>Updates SentOrReceived and saves changes to db.  Better than using Update(), because does not delete and add attachments back into db.</summary>
		public static void UpdateSentOrReceivedRead(EmailMessage emailMessage) {
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				Meth.GetVoid(MethodBase.GetCurrentMethod(),emailMessage);
				return;
			}
			EmailSentOrReceived sentOrReceived=emailMessage.SentOrReceived;
			if(emailMessage.SentOrReceived==EmailSentOrReceived.Received) {
				sentOrReceived=EmailSentOrReceived.Read;
			}
			else if(emailMessage.SentOrReceived==EmailSentOrReceived.WebMailReceived) {
				sentOrReceived=EmailSentOrReceived.WebMailRecdRead;
			}
			else if(emailMessage.SentOrReceived==EmailSentOrReceived.ReceivedDirect) {
				sentOrReceived=EmailSentOrReceived.ReadDirect;
			}
			if(sentOrReceived==emailMessage.SentOrReceived) {
				return;//Nothing to do.
			}
			string command="UPDATE emailmessage SET SentOrReceived="+POut.Int((int)sentOrReceived)+" WHERE EmailMessageNum="+POut.Long(emailMessage.EmailMessageNum);
			Db.NonQ(command);
		}
Example #25
0
File: EhrCCD.cs Project: mnisl/OD
		public static bool HasCcdEmailAttachment(EmailMessage emailMessage) {
			if(emailMessage.Attachments==null) {
				return false;
			}
			for(int i=0;i<emailMessage.Attachments.Count;i++) {
				if(EhrCCD.IsCcdEmailAttachment(emailMessage.Attachments[i])) {
					return true;
				}
			}
			return false;
		}
Example #26
0
		///<summary>Converts our internal EmailMessage object to a Direct message object.  Used for outgoing email.  Wraps the message.</summary>
		private static Health.Direct.Common.Mail.Message ConvertEmailMessageToMessage(EmailMessage emailMessage,bool hasAttachments) {
			//No need to check RemotingRole; no call to db.
			//We need to use emailAddressFrom.Username instead of emailAddressFrom.SenderAddress, because of how strict encryption is for matching the name to the certificate.
			Health.Direct.Common.Mail.Message message=new Health.Direct.Common.Mail.Message(emailMessage.ToAddress.Trim(),emailMessage.FromAddress.Trim());
			string subject=Tidy(emailMessage.Subject);
			if(subject!="") {
				Health.Direct.Common.Mime.Header headerSubject=new Health.Direct.Common.Mime.Header("Subject",subject);
				message.Headers.Add(headerSubject);
			}
			//The Transport Testing Tool (TTT) complained when we sent a message that was not wrapped.
			//It appears that wrapped messages are preferred when sending a message, although support for incoming wrapped messages is optional (unwrapped is required).  We support both unwrapped and wrapped.
			//Specifically, the tool looks for the headers Orig-Date and Message-Id after the message is decrypted, so we need to include these two headers before encrypting an outgoing email.
			//The message date must be in a very specific format and must match the RFC822 standard.  Is a required field for RFC822.  http://tools.ietf.org/html/rfc822
			string strOrigDate=DateTime.Now.ToString("ddd, dd MMM yyyy HH:mm:ss zzz");//Example: "Tue, 12 Nov 2013 17:10:37 +08:00", which has an extra colon in the Zulu offset.
			strOrigDate=strOrigDate.Remove(strOrigDate.LastIndexOf(':'),1);//Remove the colon from the Zulu offset, as required by the RFC 822 message format.
			message.Date=new Health.Direct.Common.Mime.Header("Date",strOrigDate);//http://tools.ietf.org/html/rfc5322#section-3.6.1
			message.AssignMessageID();//http://tools.ietf.org/html/rfc5322#section-3.6.4
			string strBoundry="";
			List<Health.Direct.Common.Mime.MimeEntity> listMimeParts=new List<Health.Direct.Common.Mime.MimeEntity>();
			string bodyText=Tidy(emailMessage.BodyText);
			if(bodyText.Trim().Length>4 && bodyText.Trim().StartsWith("--") && bodyText.Trim().EndsWith("--")) {//The body text is multi-part.
				strBoundry=bodyText.Trim().Split(new string[] { "\r\n","\r","\n" },StringSplitOptions.None)[0];
				string[] arrayBodyTextParts=bodyText.Trim().TrimEnd('-').Split(new string[] { strBoundry },StringSplitOptions.RemoveEmptyEntries);
				for(int i=0;i<arrayBodyTextParts.Length;i++) {
					Health.Direct.Common.Mime.MimeEntity mimeEntityBodyText=new Health.Direct.Common.Mime.MimeEntity(arrayBodyTextParts[i]);
					mimeEntityBodyText.ContentType="text/plain;";
					listMimeParts.Add(mimeEntityBodyText);
				}
			}
			else {
				Health.Direct.Common.Mime.MimeEntity mimeEntityBodyText=new Health.Direct.Common.Mime.MimeEntity(bodyText);
				mimeEntityBodyText.ContentType="text/plain;";
				listMimeParts.Add(mimeEntityBodyText);
			}
			if(hasAttachments && emailMessage.Attachments!=null && emailMessage.Attachments.Count>0) {
				string strAttachPath=GetEmailAttachPath();
				for(int i=0;i<emailMessage.Attachments.Count;i++) {
					string strAttachFileName=emailMessage.Attachments[i].DisplayedFileName;
					string strAttachFile=ODFileUtils.CombinePaths(strAttachPath,emailMessage.Attachments[i].ActualFileName);
					string strAttachText=File.ReadAllText(strAttachFile);
					Health.Direct.Common.Mime.MimeEntity mimeEntityAttach=new Health.Direct.Common.Mime.MimeEntity(Convert.ToBase64String(Encoding.UTF8.GetBytes(strAttachText)));
					mimeEntityAttach.ContentDisposition="attachment;";
					mimeEntityAttach.ContentTransferEncoding="base64;";
					if(Path.GetExtension(emailMessage.Attachments[i].ActualFileName).ToLower()==".xml" || Path.GetExtension(emailMessage.Attachments[i].ActualFileName).ToLower()==".xsl") {
						mimeEntityAttach.ContentType="text/xml;";
					}
					else {
						mimeEntityAttach.ContentType="text/plain;";
					}
					mimeEntityAttach.ContentType+=" name="+strAttachFileName+";";
					listMimeParts.Add(mimeEntityAttach);
				}
			}
			if(strBoundry=="") {
				strBoundry=CodeBase.MiscUtils.CreateRandomAlphaNumericString(32);
			}
			if(listMimeParts.Count==1) {//Single body part
				message.Body=listMimeParts[0].Body;
			}
			else if(listMimeParts.Count>1) {//multiple body parts
				message.SetParts(listMimeParts,"multipart/mixed; boundary="+strBoundry+";");
			}
			return message;
		}
Example #27
0
 private void menuEmail_Click(object sender,System.EventArgs e)
 {
     if(((MenuItem)sender).Tag==null){
         return;
     }
     LabelSingle label=new LabelSingle();
     if(((MenuItem)sender).Tag.GetType()==typeof(Referral)) {
         Referral refer=(Referral)((MenuItem)sender).Tag;
         if(refer.EMail==""){
             return;
             //MsgBox.Show(this,"");
         }
         EmailMessage message=new EmailMessage();
         message.PatNum=CurPatNum;
         Patient pat=Patients.GetPat(CurPatNum);
         message.ToAddress=refer.EMail;//pat.Email;
         message.FromAddress=PrefC.GetString(PrefName.EmailSenderAddress);
         message.Subject=Lan.g(this,"RE: ")+pat.GetNameFL();
         FormEmailMessageEdit FormE=new FormEmailMessageEdit(message);
         FormE.IsNew=true;
         FormE.ShowDialog();
         if(FormE.DialogResult==DialogResult.OK) {
             RefreshCurrentModule();
         }
     }
 }
		private void butSendEmail_Click(object sender,EventArgs e) {
			FormReferralsPatient FormRP=new FormReferralsPatient();
			FormRP.PatNum=PatCur.PatNum;
			FormRP.IsSelectionMode=true;
			if(FormRP.ShowDialog()==DialogResult.Cancel) {
				MessageBox.Show("Summary of Care not exported.");
				return;
			}
			string ccd="";
			try {
				ccd=EhrCCD.GenerateSummaryOfCare(PatCur);
			}
			catch(Exception ex) {
				MessageBox.Show(ex.Message);
				return;
			}
			Cursor=Cursors.WaitCursor;
			EmailAddress emailAddressFrom=EmailAddresses.GetByClinic(0);//Default for clinic/practice.
			EmailMessage emailMessage=new EmailMessage();
			emailMessage.PatNum=PatCur.PatNum;
			emailMessage.MsgDateTime=DateTime.Now;
			emailMessage.SentOrReceived=EmailSentOrReceived.Neither;//To force FormEmailMessageEdit into "compose" mode.
			emailMessage.FromAddress=emailAddressFrom.EmailUsername;//Cannot be emailAddressFrom.SenderAddress, because it would cause encryption to fail.
			emailMessage.ToAddress="";//User must set inside of FormEmailMessageEdit
			emailMessage.Subject="Summary of Care";
			emailMessage.BodyText="Summary of Care";
			try {
				EmailMessages.CreateAttachmentFromText(emailMessage,ccd,"ccd.xml");
				EmailMessages.CreateAttachmentFromText(emailMessage,FormEHR.GetEhrResource("CCD"),"ccd.xsl");
			}
			catch(Exception ex) {
				Cursor=Cursors.Default;
				MessageBox.Show(ex.Message);
				return;
			}
			EmailMessages.Insert(emailMessage);
			FormEmailMessageEdit formE=new FormEmailMessageEdit(emailMessage);
			if(formE.ShowDialog()==DialogResult.OK) {
				EhrMeasureEvent newMeasureEvent=new EhrMeasureEvent();
				newMeasureEvent.DateTEvent=DateTime.Now;
				newMeasureEvent.EventType=EhrMeasureEventType.SummaryOfCareProvidedToDr;
				newMeasureEvent.PatNum=PatCur.PatNum;
				long fkey=EhrMeasureEvents.Insert(newMeasureEvent);
				newMeasureEvent=new EhrMeasureEvent();
				newMeasureEvent.DateTEvent=DateTime.Now;
				newMeasureEvent.FKey=fkey;
				newMeasureEvent.EventType=EhrMeasureEventType.SummaryOfCareProvidedToDrElectronic;
				newMeasureEvent.PatNum=PatCur.PatNum;
				newMeasureEvent.FKey=FormRP.RefAttachNum;//Can be 0 if user didn't pick a referral for some reason.
				EhrMeasureEvents.Insert(newMeasureEvent);
				FillGridSent();
			}
			Cursor=Cursors.Default;
		}
Example #29
0
		///<summary>Returns an email message for the patient based on the statement passed in.</summary>
		public static EmailMessage GetEmailMessageForStatement(Statement stmt,Patient pat) {
			//No need to check RemotingRole; no call to db.
			EmailMessage message=new EmailMessage();
			message.PatNum=pat.PatNum;
			message.ToAddress=pat.Email;
			message.FromAddress=EmailAddresses.GetByClinic(pat.ClinicNum).SenderAddress;
			string str;
			if(stmt.EmailSubject!=null && stmt.EmailSubject!="") {
				str=stmt.EmailSubject;//Set str to the email subject if one was already set.
			}
			else {//Subject was not set.  Set str to the default billing email subject.
				str=PrefC.GetString(PrefName.BillingEmailSubject);
			}
			message.Subject=Statements.ReplaceVarsForEmail(str,pat);
			if(stmt.EmailBody!=null && stmt.EmailBody!="") {
				str=stmt.EmailBody;//Set str to the email body if one was already set.
			}
			else {//Body was not set.  Set str to the default billing email body text.
				str=PrefC.GetString(PrefName.BillingEmailBodyText);
			}
			message.BodyText=Statements.ReplaceVarsForEmail(str,pat);
			return message;
		}
Example #30
0
		private void butSendEmail_Click(object sender,EventArgs e) {
			if(!Security.IsAuthorized(Permissions.EmailSend)) {
				return;
			}
			//Generate the CCD first so that any validation errors are apparent and up front.
			//It is better to not let the user waste their time creating a referral if there is a basic validation issue with the CCD generation.
			string ccd="";
			try {
				ccd=EhrCCD.GenerateSummaryOfCare(PatCur);
			}
			catch(Exception ex) {
				MessageBox.Show(ex.Message);
				return;
			}
			FormReferralsPatient FormRP=new FormReferralsPatient();
			FormRP.PatNum=PatCur.PatNum;
			FormRP.IsSelectionMode=true;
			if(FormRP.ShowDialog()==DialogResult.Cancel) {
				MessageBox.Show("Summary of Care not exported.");
				return;
			}
			Cursor=Cursors.WaitCursor;
			EmailAddress emailAddressFrom=EmailAddresses.GetByClinic(0);//Default for clinic/practice.
			EmailMessage emailMessage=new EmailMessage();
			emailMessage.PatNum=PatCur.PatNum;
			emailMessage.MsgDateTime=DateTime.Now;
			emailMessage.SentOrReceived=EmailSentOrReceived.Neither;//To force FormEmailMessageEdit into "compose" mode.
			emailMessage.FromAddress=emailAddressFrom.EmailUsername;//Cannot be emailAddressFrom.SenderAddress, because it would cause encryption to fail.
			emailMessage.ToAddress="";//User must set inside of FormEmailMessageEdit
			emailMessage.Subject="Summary of Care";
			emailMessage.BodyText="Summary of Care";
			try {
				emailMessage.Attachments.Add(EmailAttaches.CreateAttach("ccd.xml",Encoding.UTF8.GetBytes(ccd)));
				emailMessage.Attachments.Add(EmailAttaches.CreateAttach("ccd.xsl",Encoding.UTF8.GetBytes(FormEHR.GetEhrResource("CCD"))));
			}
			catch(Exception ex) {
				Cursor=Cursors.Default;
				MessageBox.Show(ex.Message);
				return;
			}
			EmailMessages.Insert(emailMessage);
			FormEmailMessageEdit formE=new FormEmailMessageEdit(emailMessage);
			if(formE.ShowDialog()==DialogResult.OK) {
				EhrMeasureEvent newMeasureEvent=new EhrMeasureEvent();
				newMeasureEvent.DateTEvent=DateTime.Now;
				newMeasureEvent.EventType=EhrMeasureEventType.SummaryOfCareProvidedToDr;
				newMeasureEvent.PatNum=PatCur.PatNum;
				newMeasureEvent.FKey=FormRP.RefAttachNum;//Can be 0 if user didn't pick a referral for some reason.
				EhrMeasureEvents.Insert(newMeasureEvent);
				newMeasureEvent=new EhrMeasureEvent();
				newMeasureEvent.DateTEvent=DateTime.Now;
				newMeasureEvent.EventType=EhrMeasureEventType.SummaryOfCareProvidedToDrElectronic;
				newMeasureEvent.PatNum=PatCur.PatNum;
				newMeasureEvent.FKey=FormRP.RefAttachNum;//Can be 0 if user didn't pick a referral for some reason.
				EhrMeasureEvents.Insert(newMeasureEvent);
				FillGridSent();
			}
			Cursor=Cursors.Default;
		}