123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227 |
- using InABox.Clients;
- using InABox.Core;
- using InABox.Reports;
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Net.Mail;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Controls;
- using System.Windows;
- using System.Windows.Forms;
- using System.Drawing;
- using InABox.WPF;
- using MessageBox = System.Windows.Forms.MessageBox;
- using Comal.Classes;
- using TextBox = System.Windows.Controls.TextBox;
- namespace PRSDesktop
- {
- public class EmailUtils
- {
- /// <summary>
- /// Creates and opens an email with the default email app - selected by the user.
- /// This method is for emails with a PDF attachment. Provide the file name and data.
- /// Optionally provide from, subject and body.
- /// If from is not provided, an attempt will be made to find the User's email address - if empty it will throw an error (cannot be empty)
- /// </summary>
- /// <param name="attachmentname"></param>
- /// <param name="attachmentdata"></param>
- /// <param name="from"></param>
- /// <param name="subject"></param>
- /// <param name="body"></param>
- public static void CreateEMLFile(string attachmentname, byte[] attachmentdata, string from = "", string subject = "", string body = "", string to = "")
- {
- var message = CreateMessage(from, subject, body, to);
- message = AddAttachment(message, attachmentname, attachmentdata);
- OpenEmail(message, attachmentname);
- }
- /// <summary>
- /// Creates and opens an email with the default email app - selected by the user.
- /// This method is for emails with no attachments.
- /// Optionally provide from, subject and body.
- /// If from is not provided, an attempt will be made to find the User's email address - if empty it will throw an error (cannot be empty)
- /// </summary>
- /// <param name="from"></param>
- /// <param name="subject"></param>
- /// <param name="body"></param>
- public static void CreateEMLFile(string from = "", string subject = "", string body = "")
- {
- var message = CreateMessage(from, subject, body);
- OpenEmail(message, "Message from " + from);
- }
- private static void OpenEmail(MailMessage message, string name)
- {
- var filename = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(name, ".eml"));
- using (var filestream = File.Open(filename, FileMode.Create))
- {
- var binaryWriter = new BinaryWriter(filestream);
- //Write the Unsent header to the file so the mail client knows this mail must be presented in "New message" mode
- binaryWriter.Write(Encoding.UTF8.GetBytes("X-Unsent: 1" + Environment.NewLine));
- var assembly = typeof(SmtpClient).Assembly;
- var mailWriterType = assembly.GetType("System.Net.Mail.MailWriter")!;
- // Get reflection info for MailWriter contructor
- var mailWriterConstructor =
- mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(Stream), typeof(bool) }, null)!;
- // Construct MailWriter object with our FileStream
- var mailWriter = mailWriterConstructor.Invoke(new object[] { filestream, true });
- // Get reflection info for Send() method on MailMessage
- var sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic)!;
- sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true, true }, null);
- // Finally get reflection info for Close() method on our MailWriter
- var closeMethod = mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic)!;
- // Call close method
- closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null);
- }
- // Open the file with the default associated application registered on the local machine
- Process.Start(new ProcessStartInfo(filename) { UseShellExecute = true });
- }
- private static MailMessage CreateMessage(string from, string subject, string body, string to = "")
- {
- if (string.IsNullOrWhiteSpace(to))
- to = "example@outlook.com.au";
- if (string.IsNullOrWhiteSpace(from))
- from = GetAddressFromUser();
- if (string.IsNullOrWhiteSpace(subject))
- subject = "Enter subject";
- if (string.IsNullOrWhiteSpace(body))
- body = "Enter message";
- var message = new MailMessage(from, to, subject, body);
- message.IsBodyHtml = false;
- return message;
- }
- private static string GetAddressFromUser()
- {
- CoreTable table = new Client<User>().Query(new Filter<User>(x => x.ID).IsEqualTo(ClientFactory.UserGuid)
- , new Columns<User>(x => x.EmailAddress));
- User user = table.Rows.FirstOrDefault().ToObject<User>();
- if (!string.IsNullOrWhiteSpace(user.EmailAddress))
- return user.EmailAddress;
- else
- MessageBox.Show("Current User Email Address is blank - please fill in (Human Resources -> User Accounts -> Choose your User -> Email Settings -> Email Address", "Error");
- return "";
- }
- private static MailMessage AddAttachment(MailMessage message, string attachmentname, byte[] attachmentdata)
- {
- var attachment = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(attachmentname, ".pdf"));
- File.WriteAllBytes(attachment, attachmentdata);
- message.Attachments.Add(new Attachment(attachment));
- return message;
- }
- public static IEnumerable<ReportExportDefinition> CreateTemplateDefinitions(DataModel model)
- {
- var templates = new Client<DataModelTemplate>().Query(new Filter<DataModelTemplate>(x => x.Model).IsEqualTo(model.Name)
- .And(x => x.Visible).IsEqualTo(true));
- if (templates.Rows.Any())
- {
- List<ReportExportDefinition> list = new List<ReportExportDefinition>();
- foreach (CoreRow row in templates.Rows)
- {
- Action<DataModel, byte[]> action = new Action<DataModel, byte[]>((model, data) =>
- {
- DoEmailAction(model, data, row.Get<DataModelTemplate, string>(x => x.Name));
- });
- list.Add(
- new ReportExportDefinition(
- "Email Report",
- ImageUtils.CreatePreviewWindowButtonContent(row.Get<DataModelTemplate, string>(x => x.Name),PRSDesktop.Resources.emailreport),
- ReportExportType.PDF,
- action));
- }
- return list;
- }
- else
- return new List<ReportExportDefinition>()
- {
- new ReportExportDefinition(
- "Email Report",
- ImageUtils.CreatePreviewWindowButtonContent("Email",PRSDesktop.Resources.emailreport),
- ReportExportType.PDF,
- DoEmailReport)
- };
- }
- private static void DoEmailAction(DataModel model, byte[] data, string templateName)
- {
- var template = new Client<DataModelTemplate>().Query(new Filter<DataModelTemplate>(x => x.Name).IsEqualTo(templateName)).Rows.FirstOrDefault();
- ParseTemplateAndCreateEmail(template, model, data);
- }
- private static void ParseTemplateAndCreateEmail(CoreRow row, DataModel model, byte[] data)
- {
- var to = DataModelUtils.ParseTemplate(model, row.Get<DataModelTemplate, string>(x => x.To)).Replace("\n", "").Replace("\r", "");
- var Subject = DataModelUtils.ParseTemplate(model, row.Get<DataModelTemplate, string>(x => x.Subject)).Replace("\n", "").Replace("\r", "");
- var attachmentName = DataModelUtils.ParseTemplate(model, row.Get<DataModelTemplate, string>(x => x.AttachmentName)).Replace("\n", "").Replace("\r", "");
- var body = DataModelUtils.ParseTemplate(model, row.Get<DataModelTemplate, string>(x => x.Template));
- if (string.IsNullOrWhiteSpace(attachmentName))
- attachmentName = model.Name;
- EmailUtils.CreateEMLFile(attachmentName, data, App.EmployeeEmail, Subject, body, to);
- }
- public static void DoEmailReport(DataModel model, byte[] data)
- {
- string attachmentName = DetermineName(model);
- EmailUtils.CreateEMLFile(attachmentName, data, App.EmployeeEmail, "Emailing report for " + attachmentName);
- }
- private static string DetermineName(DataModel model)
- {
- string title = model.Name;
- if (model.AsDictionary.ContainsKey(typeof(Requisition)))
- {
- CoreTable table = model.AsDictionary[typeof(Requisition)];
- title = title + " - " + table.Rows.FirstOrDefault().Get<Requisition, string>(x => x.Title);
- }
- else if (model.AsDictionary.ContainsKey(typeof(PurchaseOrder)))
- {
- title = "Purchase Order ";
- CoreTable table = model.AsDictionary[typeof(PurchaseOrder)];
- if (table.Rows.Count == 1)
- title = title + table.Rows.FirstOrDefault().Get<PurchaseOrder, string>(x => x.PONumber);
- else if (table.Rows.Count > 1)
- {
- foreach (CoreRow row in table.Rows)
- {
- title = title + row.Get<PurchaseOrder, string>(x => x.PONumber) + ", ";
- }
- title = title.Substring(0, title.Length - 2);
- }
- }
- return title;
- }
- }
- }
|