/// <summary> /// receive emails from IMAP /// </summary> public static List <EmailMessageModel> ReceiveEmailsFromIMAP(ServiceSettingsModel model) { try { List <EmailMessageModel> models = new List <EmailMessageModel>(); var client = new ImapClient(model.ImapSettings.Server, model.ImapSettings.Port, model.ImapSettings.UseSSL); if (client.Connect()) { if (client.Login(model.Credentials.UserName, model.Credentials.Password)) { // login successful List <string> lst = new List <string>(); foreach (var folder in client.Folders) { lst.Add(folder.Name); if (folder.Name.ToLower().Equals(model.ImapSettings.DefaultFolder.ToLower())) { folder.Messages.Download("ALL", MessageFetchMode.Full, Int32.MaxValue); foreach (var message in folder.Messages) { if (!message.Seen) { models.Add(new EmailMessageModel() { Body = message.Body.Text, DateTime = message.Date, ReceiverEmail = model.Credentials.UserName, SenderEmail = message.From.Address, Subject = message.Subject }); //message.Seen = true; } } } } } } else { return(null); } return(models); } catch (Exception) { return(null); } }
/// <summary> /// init default service settings /// </summary> /// <returns></returns> public static ServiceSettingsModel InitDefaultServiceSettings(string settingsPath) { try { XmlSerializer formatter = new XmlSerializer(typeof(ServiceSettingsModel)); ServiceSettingsModel model = new ServiceSettingsModel(); model.Credentials = new EmailCredentials() { UserName = "******", Password = "******" }; model.AdminCredentials = new EmailCredentials() { UserName = "******", Password = "******" }; model.AgentName = "FlexiCapture.Cloud Email Agent"; model.AgentEmail = "*****@*****.**"; //receive email params model.ImapSettings = new IMAPConnectionProtocolModel() { Server = "mail.netvix.by", Port = 143, DefaultFolder = "INBOX", UseSSL = false }; model.POP3Settings = new POPConnectionProtocolModel() { Server = "mail.netvix.by", Port = 110, UseSSL = false }; //send email params model.SMTPSettings = new IMAPConnectionProtocolModel() { Server = "mail.netvix.by", Port = 25, UseSSL = false }; using (FileStream fs = new FileStream(settingsPath, FileMode.OpenOrCreate)) { formatter.Serialize(fs, model); } return(model); } catch (Exception exception) { string innerException = exception.InnerException == null ? "" : exception.InnerException.Message; string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; LogHelper.AddLog("Error in method: " + methodName + "; Exception: " + exception.Message + " Innner Exception: " + innerException); return(null); } }
/// <summary> /// make timer procedure /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Timer_Elapsed(object sender, ElapsedEventArgs e) { try { Timer.Stop(); if (ServiceSettings == null) { SystemSettings = new SystemSettingsModel(); ServiceSettings = ServiceSettingHelper.InitServiceSettings(SystemSettings.SettingsPath); } ProcessorHelper.MakeProcessing(); Timer.Start(); } catch (Exception exception) { string innerException = exception.InnerException == null ? "" : exception.InnerException.Message; string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; LogHelper.AddLog("Error in method: " + methodName + "; Exception: " + exception.Message + " Innner Exception: " + innerException); } }
/// <summary> /// start service method /// </summary> /// <param name="args"></param> protected override void OnStart(string[] args) { try { Timer = new Timer(); Timer.Interval = 5000; Timer.Elapsed += Timer_Elapsed; SystemSettings = new SystemSettingsModel(); ServiceSettings = ServiceSettingHelper.InitServiceSettings(SystemSettings.SettingsPath); LogHelper.AddLog("Settings Path " + SystemSettings.SettingsPath); Timer.Start(); //ProcessorHelper.MakeProcessing(); LogHelper.AddLog("FCC Email Agent Service started"); } catch (Exception) { } }
/// <summary> /// test connections /// </summary> public static bool TestConnectionParams() { try { ServiceSettingsModel model = Program.Agent.ServiceSettings; switch (model.ReceiveType) { case ReceiveType.IMAP: return(ReceiveEmailsFromIMAP(model) != null); } return(false); } catch (Exception exception) { string innerException = exception.InnerException == null ? "" : exception.InnerException.Message; string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; LogHelper.AddLog("Error in method: " + methodName + "; Exception: " + exception.Message + " Innner Exception: " + innerException); return(false); } }
/// <summary> /// init default service settings /// </summary> private static ServiceSettingsModel LoadServiceSettings(string settingsPath) { try { XmlSerializer formatter = new XmlSerializer(typeof(ServiceSettingsModel)); ServiceSettingsModel model = new ServiceSettingsModel(); using (FileStream fs = new FileStream(settingsPath, FileMode.Open)) { model = formatter.Deserialize(fs) as ServiceSettingsModel; } return(model); } catch (Exception exception) { string innerException = exception.InnerException == null ? "" : exception.InnerException.Message; string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; LogHelper.AddLog("Error in method: " + methodName + "; Exception: " + exception.Message + " Innner Exception: " + innerException); return(null); } }
/// <summary> /// receive emails from IMAP /// </summary> public static void CreateTasksFromEmails(ServiceSettingsModel model, Assist assist, List <string> extensions, string uploadPath, string uploadFolder, int serviceId) { try { var client = new ImapClient(model.ImapSettings.Server, model.ImapSettings.Port, model.ImapSettings.UseSSL); if (client.Connect()) { if (client.Login(model.Credentials.UserName, model.Credentials.Password)) { // login successful List <string> lst = new List <string>(); foreach (var folder in client.Folders) { lst.Add(folder.Name); if (folder.Name.ToLower().Equals(model.ImapSettings.DefaultFolder.ToLower())) { folder.Messages.Download("ALL", MessageFetchMode.Full, Int32.MaxValue); //if (folder.Unseen>0) foreach (var message in folder.Messages) { if (!message.Seen) { assist.AddLog("Check not seen letter from: " + message.From); // check whether this email is active and user has email service assist.UserProfile = assist.CheckServiceAvailabilityByEmail(message.From.Address); if (assist.UserProfile != null && assist.UserProfile.Id > 0) { if (message.Body != null) { //change user profile } foreach (var attachment in message.Attachments) { var extension = Path.GetExtension(attachment.FileName); if (CheckExtensions(extensions, extension)) // check whether file extension is in the extensions list { var newNameGuid = Guid.NewGuid(); var uploadName = newNameGuid + extension; var localName = Path.Combine(uploadFolder, uploadName); var filePath = Path.Combine(uploadPath, uploadName); string originalFileName = attachment.FileName; attachment.Download(); attachment.Save(uploadPath, uploadName); assist.AddLog("Download file: " + uploadName); //add task to db var taskId = assist.AddTask(assist.UserProfile.UserId, serviceId); assist.AddLog("Add task: " + taskId); var md5 = assist.GetMD5HashFromFile(filePath); //add document var fileInfo = new FileInfo(filePath); assist.EmailSettings = assist.GetToEmailConversionSettings(assist.UserProfile.UserId); if (assist.EmailSettings != null) { var documentId = assist.AddDocument(taskId, fileInfo, originalFileName, newNameGuid, uploadName, localName, md5, 1, assist.EmailSettings.ResponseSettings.ShowJob); assist.Documents = assist.GetDocumentsByTaskId(taskId); string content = assist.ConvertProfileToRequestModel(assist.Documents, assist.UserProfile); assist.UpdateTaskProfile(taskId, content); } } } } else if (assist.UserProfile != null) { string text = ""; switch (assist.UserProfile.Id) { case 0: text = "DataCapture.Cloud received a conversion request form this e - mail address." + " This address is not currently registered with a valid account."; break; case -1: text = "DataCapture.Cloud received a conversion request form this e-mail address. " + "Subscription to E-mail Attachment Conversion Service is disabled."; break; case -2: text = "DataCapture.Cloud received a conversion request form this e-mail address. " + "Subscription to E-mail Attachment Conversion Service is disabled."; break; case -3: text = "DataCapture.Cloud received a conversion request form this e-mail address. " + "Viewer doesn't have rights to use E-mail Attachment Conversion Service."; break; default: break; } assist.SendEmailResponseFail(message.From.Address, text, ""); } message.Seen = true; } } } } } } } catch (Exception exception) { string innerException = exception.InnerException == null ? "" : exception.InnerException.Message; string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; assist.AddLog("Error in method: " + methodName + "; Exception: " + exception.Message + " Innner Exception: " + innerException); } }
/// <summary> /// make processing /// </summary> public static void MakeProcessing() { try { int serviceId = 4;// email attachment service id //getting available file extentions Assist assist = new Assist(); Assist serviceAssist = new Assist(); string serverPath = serviceAssist.GetSettingValueByName("MainPath"); string uploadFolder = serviceAssist.GetSettingValueByName("UploadFolder"); string uploadUrl = Path.Combine(serverPath, uploadFolder); List <string> extentions = assist.GetToAvailableFileExtensions(); // getting IMAP setttings string path = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "data/settings.xml"); if (File.Exists(path)) { ServiceSettingsModel settingsModel; XmlSerializer formatter = new XmlSerializer(typeof(ServiceSettingsModel)); ServiceSettingsModel model = new ServiceSettingsModel(); using (FileStream fs = new FileStream(path, FileMode.Open)) { settingsModel = formatter.Deserialize(fs) as ServiceSettingsModel; } //check tasks List <Tasks> notExecutedTasks = assist.GetToNotExecutedTasks(serviceId); //upload files foreach (var notExecutedTask in notExecutedTasks) { OcrRequestModel requestModel = JsonConvert.DeserializeObject <OcrRequestModel>(notExecutedTask.ProfileContent); if (requestModel.InputFiles != null && requestModel.InputFiles.Count > 0) { string extension = Path.GetExtension(requestModel.InputFiles[0].Name); if (extension != null && extension != ".zip" && extension != ".rar" && extension != ".7z") { TaskHelper.ExecuteTask(notExecutedTask); } } } //check statuses List <Tasks> processedTasks = assist.GetToProcessedTasks(serviceId); //download files foreach (var processedTask in processedTasks) { TaskHelper.CheckStateTask(processedTask); } EmailHelper.CreateTasksFromEmails(settingsModel, assist, extentions, uploadUrl, uploadFolder, serviceId); } else { throw new FileNotFoundException("File not found in " + path); } //update states } catch (Exception exception) { string innerException = exception.InnerException == null ? "" : exception.InnerException.Message; string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; LogHelper.AddLog("Error in method: " + methodName + "; Exception: " + exception.Message + " Innner Exception: " + innerException); } }