private void replyToMessage(EmailMessage message) { ResponseMessage rMessage; if (emailMessageSendType.Equals(emailMessageSendTypeOptions.replyAll)) { rMessage = message.CreateReply(true); } else { rMessage = message.CreateReply(false); } // Setup Recipients if (Recipients != null) { foreach (string recipient in Recipients) { rMessage.ToRecipients.Add(recipient); } } if (BCCRecipients != null) { foreach (string recipient in BCCRecipients) { rMessage.BccRecipients.Add(recipient); } } if (CCRecipients != null) { foreach (string recipient in CCRecipients) { rMessage.CcRecipients.Add(recipient); } } if (Subject != null) { rMessage.Subject = Subject; } if (Body != null) { MessageBody body = new MessageBody(bodyFormat, Body); rMessage.BodyPrefix = body; } if (RequestReadResponse.IsPresent) { rMessage.IsReadReceiptRequested = true; } if (RequestDeliveryReceipt.IsPresent) { rMessage.IsDeliveryReceiptRequested = true; } rMessage.SendAndSaveCopy(); }
private bool MakeResponseMessage(ResponseMessageType oResponseMessageType) { bool bRet = false; MessageBody oMessageBody = new MessageBody("----\r\n"); ResponseMessage oResponseMessage = null; string sWindowTitle = string.Empty; try { if (oResponseMessageType == ResponseMessageType.Reply) { _EmailMessage.Service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. oResponseMessage = _EmailMessage.CreateReply(false); sWindowTitle = "Reply Message"; } if (oResponseMessageType == ResponseMessageType.ReplyAll) { _EmailMessage.Service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. oResponseMessage = _EmailMessage.CreateReply(true); sWindowTitle = "Reply All Message"; } if (oResponseMessageType == ResponseMessageType.Forward) { _EmailMessage.Service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. oResponseMessage = _EmailMessage.CreateForward(); sWindowTitle = "Forward Message"; } //oResponseMessage.BodyPrefix = "===========\r\n"; // Save as drafts AND set as new current message. _EmailMessage.Service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. _EmailMessage = oResponseMessage.Save(WellKnownFolderName.Drafts); _EmailMessage.Service.ClientRequestId = Guid.NewGuid().ToString(); // Set a new GUID. _EmailMessage.Load(); SetFormFromMessage(_EmailMessage, true, true, false); bRet = true; } catch (Exception ex) { MessageBox.Show(ex.Message, "Error creating message"); bRet = false; } return(bRet); }
/// <summary> /// Send a reply over the original email. /// Reply format is HTML /// </summary> /// <param name="replyHtml">HTML of the contents</param> /// <param name="replyAll">true = Reply All; false = reply only to sender</param> public void Reply(string replyHtml, bool replyAll) { var reply = _message.CreateReply(replyAll); reply.BodyPrefix = new MessageBody(BodyType.HTML, replyHtml); reply.Send(); }
/// <summary> /// Reply to a single user. This method gets called from ReplyMail winform. /// </summary> /// <param name="message">Email Message OBJECT</param> /// <param name="index">Email position in the tree</param> /// <param name="service">EWS Current Service</param> /// <param name="bodyText">Message Text</param> /// <param name="subject">Message Original Subject</param> public static void Reply(EmailMessage message, Int32 index, ExchangeService service, String bodyText, String subject) { var replyWorker = new BackgroundWorker(); replyWorker.DoWork += (sender, args) => { bool replyToAll = false; ResponseMessage responseMessage = message.CreateReply(replyToAll); responseMessage.BodyPrefix = bodyText; responseMessage.Subject = subject; responseMessage.SendAndSaveCopy(); }; replyWorker.RunWorkerCompleted += (sender, args) => { if (args.Error != null) MessageBox.Show(args.Error.ToString()); ReplyMail.GlobalAccess.Invoke(new Action(() => { ReplyMail.GlobalAccess.mailSentPic.Visible = true; ReplyMail.GlobalAccess.MailSentTxt.Visible = true; ReplyMail.GlobalAccess.button2.Visible = true; })); }; replyWorker.RunWorkerAsync(); }
public void ReplyConversation(string from, string replyBody, string convID) { Conversation conv = GetConversationById(convID); EmailMessage lastMail = null; foreach (ItemId itemid in conv.ItemIds) { lastMail = GetMailByID(itemid); if (lastMail != null) { break; } } if (lastMail == null) { return; } ResponseMessage responseMsg = lastMail.CreateReply(true); //ResponseMessage responseMsg = lastMail.CreateReply(false); //responseMsg.ToRecipients.Add("*****@*****.**"); responseMsg.BodyPrefix = string.Format( "This reply was sent by <a href=\"https://msgorilla.cloudapp.net/profile/index?user={0}\">{0}</a>" + "on <a href=\"https://msgorilla.cloudapp.net/\">MSGorilla</a></br>" + "================================================================================</br>" + "{1}", from, replyBody ); //responseMsg.ToRecipients.Add("*****@*****.**"); responseMsg.SendAndSaveCopy(); }
public string ResponderCorreo(ExchangeService exchange, EmailMessage message, string asuntoContinuar, string mensaje) { try { ResponseMessage responseMessage = message.CreateReply(true); if (asuntoContinuar != "") { responseMessage.Subject = string.Format("{0} {1}", message.Subject, asuntoContinuar); } responseMessage.BodyPrefix = mensaje; //responseMessage.BccRecipients.Add("*****@*****.**"); responseMessage.SendAndSaveCopy(); return(""); } catch (Exception ex) { new Log().RegistrarEvento(Propiedades.Mensaje.CorreoErrorResponder); return(ex.Message.ToString()); } }
/// <summary> /// Processes the directory. /// </summary> public void ProcessDirectory() { long elapsedTime = 0; //// AuditId auditId = AuditId.PmseSync; //// string auditMethodName = "ProcessDirectory"; ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2); service.Credentials = new NetworkCredential(Utils.Configuration["Email"], Utils.Configuration["Passcode"]); service.Url = new Uri(Utils.Configuration["ExchangeURI"]); SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)); ItemView view = new ItemView(100); FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, searchFilter, view); foreach (Item item in findResults.Items.OrderBy(obj => obj.DateTimeReceived)) { this.stopWatch = new Stopwatch(); this.stopWatch.Start(); try { item.Load(); string replyMessage = string.Empty; bool signedEmail = false; if ((item.ItemClass == "IPM.Note.SMIME.MultipartSigned" && item.LastModifiedName == "*****@*****.**") || !Convert.ToBoolean(Utils.Configuration["CheckSignedEmail"])) { if (item.ItemClass == "IPM.Note.SMIME.MultipartSigned") { signedEmail = true; } List <PmseAssignment> listPD = new List <PmseAssignment>(); List <DTTDataAvailability> listDA = new List <DTTDataAvailability>(); if (item.HasAttachments) { if (item.Attachments.Count == 1) { foreach (Attachment fileAttachment in item.Attachments) { FileAttachment attachment = fileAttachment as FileAttachment; if (item.Subject.ToLower().Contains("unscheduled adjustment") || item.Subject.ToLower().Contains("pmse-wsd")) { var filePath = Path.Combine(Utils.GetLocalStorePath(), "Temp_File.csv"); attachment.Load(filePath); string fileName = this.ExtractFileNameFromSubject(item.Subject); bool result = false; string[] fileData = this.ParseSignedWSDFile(filePath, signedEmail); if (item.Subject.ToLower().Contains("unscheduled adjustment")) { result = this.ProcessUnscheduledAdjustments(fileData, fileName, out replyMessage); this.stopWatch.Stop(); elapsedTime = this.stopWatch.ElapsedMilliseconds; // File.Delete(filePath); if (result) { this.PmseSyncStatus(Constants.PmseSync, Constants.UnscheduledAdjustmentsTableName, this.stopWatch.Elapsed); } } else { result = this.ProcessWSDAssignmentFile(fileData, fileName, out replyMessage); this.stopWatch.Stop(); elapsedTime = this.stopWatch.ElapsedMilliseconds; // File.Delete(filePath); if (result) { this.PmseSyncStatus(Constants.PMSEAssignmentsTable, Constants.PMSEAssignmentsTable, this.stopWatch.Elapsed); } } string logMessage = string.Format("File {0} data has been successfully synchronized with WSDB. Synchronization Time:{1}", fileName, this.stopWatch.Elapsed); this.PmseAssignmentLogger.Log(TraceEventType.Information, LoggingMessageId.PmseSyncGenericMessage, logMessage); } else { replyMessage = Utils.Configuration["mailBodySubjectNotValid"]; } } } else { replyMessage = Utils.Configuration["mailBodyMoreThanOneAttachments"]; this.PmseAssignmentLogger.Log(TraceEventType.Information, LoggingMessageId.PmseSyncGenericMessage, replyMessage); } } else { replyMessage = Utils.Configuration["mailBodyAttachmentNotFound"]; this.PmseAssignmentLogger.Log(TraceEventType.Information, LoggingMessageId.PmseSyncGenericMessage, replyMessage); } } else { replyMessage = Utils.Configuration["mailBodyUnsignedMail"]; } EmailMessage message = EmailMessage.Bind(service, item.Id); ////bool replyToAll = false; ////ResponseMessage responseMessage = message.CreateReply(replyToAll); ////responseMessage.BodyPrefix = replyMessage; ////responseMessage.CcRecipients.Add(message.From.Address); ////responseMessage.SendAndSaveCopy(); bool replyToAll = false; ResponseMessage responseMessage = message.CreateReply(replyToAll); responseMessage.ToRecipients.Add(Utils.Configuration["ofcomEmailId"]); responseMessage.BodyPrefix = replyMessage; responseMessage.SendAndSaveCopy(); message.IsRead = true; message.Update(ConflictResolutionMode.AutoResolve); } catch (Exception ex) { this.PmseAssignmentLogger.Log(TraceEventType.Error, LoggingMessageId.PmseSyncGenericMessage, "Exception Occured :- " + ex.ToString()); continue; } } try { List <DynamicTableEntity> pmseSyncStatusDetails = this.PmseSync.FetchEntity <DynamicTableEntity>(Utils.GetRegionalTableName(Constants.PmseSyncStatusTableName), new { RowKey = Constants.UnscheduledAdjustmentsTableName }); if (pmseSyncStatusDetails.Count > 0) { // var lastSyncTime = pmseSyncStatusDetails[0].Timestamp.AddMinutes(Utils.Configuration["UnscheduledAdjustmentTimeMin"].ToInt32() + Utils.Configuration["AcceptableDelayInUnscheduledAdjustmentMin"].ToInt32()); // if (lastSyncTime < DateTimeOffset.Now) // { // this.PmseAssignmentLogger.Log(TraceEventType.Information, LoggingMessageId.PmseSyncGenericMessage, "Sending mail for unscheduled adjustments"); // EmailMessage message1 = new EmailMessage(service); // message1.From = Utils.Configuration["Email"]; // message1.ToRecipients.Add(Utils.Configuration["ofcomEmailId"]); // message1.Subject = Utils.Configuration["mailSubjectUnscheduledMailNotFound"]; // message1.Body = Utils.Configuration["mailBodyUnscheduledMailNotFound"]; // message1.SendAndSaveCopy(); // this.PmseAssignmentLogger.Log(TraceEventType.Information, LoggingMessageId.PmseSyncGenericMessage, "Mail sent for unscheduled adjustments"); // } } } catch (Exception ex) { this.PmseAssignmentLogger.Log(TraceEventType.Error, LoggingMessageId.PmseSyncGenericMessage, string.Format("Some exception occured while sending mail for unscheduled adjustments - {0}", ex.ToString())); } }
private GenResult EmailMessageFromMessage( StoredContact sender, StoredContact recipient, Storage.Message msg) { GenResult res = new GenResult(); try { EmailAddress em = Contact.Bind(this.service, new ItemId(sender.UniqId)) .EmailAddresses[EmailAddressKey.EmailAddress1]; EmailMessage newMsg = new EmailMessage(this.service) { From = em, Sender = em, Body = new MessageBody(msg.BodyHtml), Subject = msg.Subject }; newMsg.Save(WellKnownFolderName.Drafts); foreach (object obj in msg.Attachments) { Storage.Attachment attach = obj as Storage.Attachment; if (attach == null) { continue; } newMsg.Attachments.AddFileAttachment(attach.FileName, attach.Data); } this.FillAdresses(ref newMsg, recipient.Email); res.msg = newMsg; // делаем ли форвард if (RndTrueFalse()) { newMsg.Update(ConflictResolutionMode.AlwaysOverwrite); ResponseMessage respMsg = newMsg.CreateForward(); respMsg.BodyPrefix = @"test body prefix for forward message"; this.FillAdressesForResponse(ref respMsg, this.RndRecipMail()); respMsg.Save(WellKnownFolderName.Drafts); res.response = respMsg; } // делаем ли реплай if (RndTrueFalse()) { /*newMsg.ReplyTo.Add(_RndRecipMail()); * if (_RndTrueFalse()) * { * newMsg.ReplyTo.Add(_RndRecipMail()); * } * * if (_RndTrueFalse()) */ { newMsg.Update(ConflictResolutionMode.AlwaysOverwrite); ResponseMessage replMsg = newMsg.CreateReply(RndTrueFalse()); replMsg.BodyPrefix = @"test body prefix for reply message"; this.FillAdressesForResponse(ref replMsg, recipient.Email); replMsg.Save(WellKnownFolderName.Drafts); res.reply = replMsg; } } } catch (Exception exc) { GenericLogger <Generator> .Error( LocalizibleStrings.ErrorCreateFromTemplate + msg.FileName, exc); } return(res); }
private static bool ProcessEmailAttachments(EmailMessage email, string mailboxMonitorAddress, FolderId moveMailFolderId, long savedMySQLMessageId) { if (email.Attachments.Count > 0) { foreach (var emailAttachment in email.Attachments.Where(a => a.Name.ToLower().EndsWith("lic"))) { if (emailAttachment is FileAttachment) { var emailFileAttachment = emailAttachment as FileAttachment; emailFileAttachment.Load(); var utfDecodedContent = Encoding.UTF8.GetString(emailFileAttachment.Content); if (utfDecodedContent.Contains("---")) { Atum.DAL.Managers.LoggingManager.WriteToLog("Processing Mail", "From", email.Sender.Address); MsSqlManager.SaveLogging(new DAL.Logging.LoggingInfo(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"), "Processing Mail", "From", email.Sender.Address)); Atum.DAL.Managers.LoggingManager.WriteToLog("Processing Mail", "Start of license block", "Found"); MsSqlManager.SaveLogging(new DAL.Logging.LoggingInfo(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"), "Processing Mail", "Start of license block", "Found")); var activatedLicenseFile = Atum.DAL.Licenses.OnlineCatalogLicenses.FromLicenseStream(utfDecodedContent); if (activatedLicenseFile.Count == 1) { LoggingManager.WriteToLog("Processing Mail", "License Object", "Processed"); MsSqlManager.SaveLogging(new DAL.Logging.LoggingInfo(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"), "Processing Mail", "License Object", "Processed")); //debug (use forwarding to monitor registration process) email.Forward(new MessageBody(BodyType.HTML, "Done?"), new EmailAddress[1] { mailboxMonitorAddress }); LoggingManager.WriteToLog("Processing Mail", "Forwarding with body", "Done"); MsSqlManager.SaveLogging(new DAL.Logging.LoggingInfo(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"), "Processing Mail", "Forwarding with body", "Done")); //prepare var emailReply = new StringBuilder(); if (email.Body.BodyType == BodyType.HTML) { emailReply.AppendLine("Dear customer, <br/><br/>Thank you for requesting an activation code.<br/><br/>"); } else { emailReply.AppendLine("Dear customer,"); emailReply.AppendLine("Thank you for requesting an activation code."); emailReply.AppendLine(); emailReply.AppendLine(); } //activate license activatedLicenseFile[0].Activated = true; activatedLicenseFile[0].ExpirationDate = DateTime.Now.AddYears(1); activatedLicenseFile[0].ActivationDate = DateTime.Now; activatedLicenseFile[0].LicenseType = Atum.DAL.Licenses.AvailableLicense.TypeOfLicense.StudioStandard; var emailFileAttachmentName = emailFileAttachment.Name; var emailFileAttachmentNameActivated = emailFileAttachment.Name.Substring(0, emailFileAttachment.Name.LastIndexOf(".")); emailFileAttachmentNameActivated += "-activated.lic"; var replyMessage = email.CreateReply(true); replyMessage.BodyPrefix = emailReply.ToString(); EmailMessage replyEmailMessage = replyMessage.Save(); replyEmailMessage.Attachments.AddFileAttachment(emailFileAttachmentNameActivated, Encoding.UTF8.GetBytes(activatedLicenseFile.ToLicenseRequest())); replyEmailMessage.Update(ConflictResolutionMode.AutoResolve); replyEmailMessage.Send(); LoggingManager.WriteToLog("Processing Mail", "Forwarded with body", "Done"); MsSqlManager.SaveLogging(new DAL.Logging.LoggingInfo(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"), "Processing Mail", "Forwarding with body", "Done")); //mark as read email.IsRead = true; email.Update(ConflictResolutionMode.AlwaysOverwrite); LoggingManager.WriteToLog("Processing Mail", "Email marked as", "Unread"); MsSqlManager.SaveLogging(new DAL.Logging.LoggingInfo(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"), "Processing Mail", "Email marked as", "Unread")); //save to database MsSqlManager.UpdateRAWMessageWithActivationCode(savedMySQLMessageId, activatedLicenseFile); //move mail to processed folder email.Move(moveMailFolderId); LoggingManager.WriteToLog("Processing Mail", "Email moved to", "Processed"); MsSqlManager.SaveLogging(new DAL.Logging.LoggingInfo(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"), "Processing Mail", "Email moved to", "Processed")); //save to path var atumLicenseFile = new AtumEmailLicenseRequest(email.Sender.Address, email.DateTimeReceived, activatedLicenseFile[0]); atumLicenseFile.Save(); LoggingManager.WriteToLog("Processing Mail", "Email moved to", "Processed"); MsSqlManager.SaveLogging(new DAL.Logging.LoggingInfo(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"), "Processing Mail", "Email moved to", "Processed")); } } } } return(true); } return(false); }
/// <summary> /// Shared Mail logic for replying to a mail /// </summary> /// <param name="context"></param> protected override void Execute(CodeActivityContext context) { // ****************** getting the input values ************************ ExchangeService objExchangeService = ObjExchangeService.Get(context); Item mail = Mail.Get(context); string body = Body.Get(context); bool isBodyHTML = IsBodyHTML.Get(context); //string recipientEmail = RecipientEmail.Get(context); string cc = Cc.Get(context); string bcc = Bcc.Get(context); string sender = Sender.Get(context); string[] attachments = Attachments.Get(context); bool isReplyAll = ReplyAll.Get(context); //******** Sending mail Logic ****** EmailMessage email = EmailMessage.Bind(objExchangeService, mail.Id, new PropertySet(ItemSchema.Attachments)); ResponseMessage responseMessage = email.CreateReply(isReplyAll); //Check for if body is a HTML content if (isBodyHTML) { responseMessage.BodyPrefix = new MessageBody(BodyType.HTML, body); } else { responseMessage.BodyPrefix = body; } //If CC is available if (cc != null && cc.Length > 0) { //Adding recipients to mail string[] recipientsCC = cc.Split(';'); foreach (string recipient in recipientsCC) { responseMessage.CcRecipients.Add(recipient); } } //If BCC is available if (bcc != null && bcc.Length > 0) { //Adding recipients to mail string[] recipientsBcc = bcc.Split(';'); foreach (string recipient in recipientsBcc) { responseMessage.BccRecipients.Add(recipient); } } //Check if attachment is available //If attachments if (attachments != null && attachments.Length > 0) { FolderView view = new FolderView(10000); view.PropertySet = new PropertySet(BasePropertySet.IdOnly); view.PropertySet.Add(FolderSchema.DisplayName); view.Traversal = FolderTraversal.Deep; Mailbox mailbox = new Mailbox(sender); FindFoldersResults findFolderResults = objExchangeService.FindFolders(new FolderId(WellKnownFolderName.MsgFolderRoot, mailbox), view); foreach (Folder folder in findFolderResults) { if (folder.DisplayName == "Sent Items") { //Adding attachments to reply mail EmailMessage reply = responseMessage.Save(folder.Id); foreach (string attachment in attachments) { reply.Attachments.AddFileAttachment(attachment); } reply.Update(ConflictResolutionMode.AlwaysOverwrite); //Sending mail and saving to sent Items reply.SendAndSaveCopy(folder.Id); } } } else { FolderView view = new FolderView(10000); view.PropertySet = new PropertySet(BasePropertySet.IdOnly); view.PropertySet.Add(FolderSchema.DisplayName); view.Traversal = FolderTraversal.Deep; Mailbox mailbox = new Mailbox(sender); FindFoldersResults findFolderResults = objExchangeService.FindFolders(new FolderId(WellKnownFolderName.MsgFolderRoot, mailbox), view); foreach (Folder folder in findFolderResults) { if (folder.DisplayName == "Sent Items") { responseMessage.SendAndSaveCopy(folder.Id); } } } }