/// <summary> /// This method forwards emails according to the parameters /// </summary> /// <param name="operation">argument for MailForward</param> /// <returns>true if processed successfully, false otherwise</returns> private bool MailForward(MailSimOperationsMailForward operation) { var parsedOp = ParseOperation(operation, operation.Folder, operation.MailSubjectToForward); return(parsedOp.Iterate((indexToForward, mails) => { IMailItem mailToForward = mails[indexToForward].Forward(); Log.Out(Log.Severity.Info, operation.OperationName, "Subject: {0}", mailToForward.Subject); mailToForward.Body = BuildBody(operation.ForwardBody) + mailToForward.Body; Log.Out(Log.Severity.Info, operation.OperationName, "Body: {0}", mailToForward.Body); if (!AddRecipients(mailToForward, operation)) { return false; } AddAttachments(mailToForward, operation); mailToForward.Send(); return true; })); }
/// <summary> /// Responding event handler. Checks if a send-as address must be specified. /// </summary> /// <param name="mail"></param> /// <param name="response"></param> private void MailEvents_Respond(IMailItem mail, IMailItem response) { Logger.Instance.Trace(this, "Responding to mail, checking"); using (IStore store = mail.GetStore()) { ZPushAccount zpush = Watcher.Accounts.GetAccount(store); Logger.Instance.Trace(this, "Checking ZPush: {0}", zpush); if (zpush == null) { return; } // Check if the containing folder is a shared folder using (IFolder parent = mail.Parent) using (IRecipient recip = FindSendAsSender(zpush, parent)) { if (recip == null || !recip.IsResolved) { return; } // Set the sender Logger.Instance.Trace(this, "Sending as: {0}", recip.Address); using (IAddressEntry address = recip.GetAddressEntry()) { response.SetSender(address); } } } }
public void Init(IOutlookApplication application, IMailItem mailItem) { this._application = application; this.mailItem = mailItem; String accountAddress = application.GetPrimarySmtpAddresses().FirstOrDefault() ?? ""; //PPOLService.PsnNoteAPIService local = new PPOLService.PsnNoteAPIService(); this.body = mailItem.HTMLBody; this.subject = mailItem.Subject; var mItem = mailItem; if (mItem.SenderEmailAddress != null && !mItem.SenderEmailAddress.Equals("")) { if (mItem.Sent) { fromName = mItem.SenderEmailAddress; // string fromAddr = ""; if (!fromName.Contains('@')) { string findAddress = ""; foreach (var contact in _application.FindContactsByEmailDisplayName(fromName)) { using (contact) { foreach (var emailAddress in contact.EmailAddresses) { findAddress = emailAddress; if (!string.IsNullOrEmpty(findAddress)) { break; } } } if (!string.IsNullOrEmpty(findAddress)) { break; } } fromName = findAddress; } } else { fromName = mItem.GetRecipientAddresses().FirstOrDefault(); } bccAddressList = accountAddress + "$" + fromName; } else { bccAddressList = accountAddress; } // MessageBox.Show(String.Format(bccAddressList)); toAddress = string.Join(";", mItem.GetRecipientAddresses()); }
private void MailEvents_ItemSend(IMailItem item, ref bool cancel) { bool?wantReport = (bool?)item.GetProperty(OutlookConstants.PR_ORIGINATOR_DELIVERY_REPORT_REQUESTED); if (wantReport == true) { Logger.Instance.Trace(this, "Delivery receipt request: {0}", item.EntryID); item.SetProperty(Constants.ZPUSH_RECEIPT_REQUESTS, Constants.ZPUSH_RECEIPT_REQUEST_DELIVERY); } }
private void AddAttachments(IMailItem mail, dynamic operation) { List <string> attachments = GetAttachments(operation.OperationName, operation.Attachments); foreach (string attmt in attachments) { Log.Out(Log.Severity.Info, operation.OperationName, "Attachment: {0}", attmt); mail.AddAttachment(attmt); } }
public ActionResult Notify(string id, string mailId) { IDefect defect = Service.Get(id); IMailItem itemRead = Mail.Get(ServiceFactory.Get <IItemFactory>().GetNew <IMailItem>(mailId)); Mail.Flag(itemRead); ServiceFactory.Get <IItemFactory>().MergeTo(itemRead, defect); return(View(new DefectViewModel(defect))); }
/// <summary> /// Constructs the ReplyFlags object from the mail's categories, if present. /// If the category is present, it is removed. Changes are not saved, so this will have to be done explicitly. /// If no category is present, null is returned. /// </summary> /// <param name="item"></param> /// <returns></returns> public static ReplyFlags FromCategory(IMailItem item, bool updateCategories = true) { string[] categories = item.AttrCategories; if (categories == null || categories.Length == 0) { return(null); } // See if we have the z-push reply header for (int i = 0; i < categories.Length; ++i) { string category = categories[i]; // This test will be invoked on every change, so do a quick test first if (category.StartsWith(Constants.ZPUSH_REPLY_CATEGORY_PREFIX)) { string suffix = category.Substring(Constants.ZPUSH_REPLY_CATEGORY_PREFIX.Length); Match match = Constants.ZPUSH_REPLY_CATEGORY_REGEX.Match(suffix); if (match.Success) { try { string dateString = match.Groups[2].Value; // Parse the state Verb verb = VerbFromString(match.Groups[1].Value); // Parse the date DateTime date = DateTime.Parse(dateString).ToUniversalTime(); // Remove the category if (updateCategories) { var categoriesList = new List <string>(categories); categoriesList.RemoveAt(i); item.AttrCategories = categoriesList.ToArray(); } // Return the flags return(new ReplyFlags(item, verb, date)); } catch (System.Exception e) { // Ignore any exception Logger.Instance.Error(typeof(ReplyFlags), "Exception while parsing reply category: {0}", e); } } } } return(null); }
public ActionResult ArchiveDefect(DefectViewModel model) { if (!ModelState.IsValid) { return(View(model)); } IMailItem itemRead = Mail.Get(ServiceFactory.Get <IItemFactory>().GetNew <IMailItem>(model.IMailItemUniqueId)); Mail.Complete(itemRead); return(RedirectToAction("Index", "Convert")); }
public void InsertDefect() { IMailItem mailItem = ServiceFactory.Get <IItemFactory>().GetNew <IMailItem>(); IDefect defect = ServiceFactory.Get <IItemFactory>().GetNewDefect(mailItem); service.Save(defect); var collection = service.GetAllDefects(); Assert.IsNotNull(collection); CollectionAssert.AllItemsAreInstancesOfType(collection, typeof(IDefect)); Assert.IsTrue(collection.Any(item => item.DefectID.Equals(defect.DefectID))); }
public IDefect GetNewDefect(IMailItem itemRead) { SubjectMetaData data = new SubjectMetaData(itemRead.Subject); string agency = data.DecodeCodCompany + " " + data.Agency.ToString().PadLeft(4, '0'); IDefect defect = GetNewDefect(null, agency: agency, defectID: data.Id); defect.Title = data.Title; defect.Description = HttpUtility.UrlDecode(itemRead.Content); defect.IMailItemUniqueId = itemRead.UniqueId; return(defect); }
private void CheckBCC(IMailItem mail) { // If the item already has a BCC, assume it's correct if (!string.IsNullOrEmpty(mail.BCC)) { return; } // Grab the transport headers string headers = (string)mail.GetProperty(OutlookConstants.PR_TRANSPORT_MESSAGE_HEADERS); if (string.IsNullOrEmpty(headers)) { return; } // Check if there's a bcc header Match match = RE_BCC.Match(headers); if (match.Groups.Count < 2) { return; } string bcc = match.Groups[1].Value; if (string.IsNullOrEmpty(bcc)) { return; } // Add the recipient string decoded = bcc.DecodeQuotedPrintable(); try { using (IRecipients recipients = mail.Recipients) { foreach (string entry in decoded.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None)) { using (IRecipient recip = CreateRecipient(recipients, entry)) { recip.Type = MailRecipientType.BCC; } } } } finally { mail.Save(); } }
private void OnRead(IMailItem mail) { try { if (Read != null && mail != null) { Read(mail); } } catch (System.Exception e) { Logger.Instance.Error(this, "OnRead: {0}", e); } }
/// <summary> /// Tries to save the changes we just made /// </summary> /// <param name="mailItem"></param> /// <returns></returns> public static bool SaveChanges(IMailItem mailItem) { // Pointer to IUnknown Interface var IUnknown = IntPtr.Zero; // Pointer to IMAPIProp Interface var IMAPIProp = IntPtr.Zero; // if we have no MAPIObject everything is senseless... if (mailItem == null) { return(false); } try { // We can pass NULL here as parameter, so we do it. MAPIInitialize(IntPtr.Zero); // retrive the IUnknon Interface from our MAPIObject comming from Outlook. IUnknown = Marshal.GetIUnknownForObject(mailItem.MAPIOBJECT); // create a Guid that we pass to retreive the IMAPIProp Interface. var guidIMAPIProp = new Guid(IID_IMAPIProp); // try to retrieve the IMAPIProp interface from IMessage Interface, everything else is sensless. if (Marshal.QueryInterface(IUnknown, ref guidIMAPIProp, out IMAPIProp) != 0) { return(false); } var mapiProp = (IMAPIProp)Marshal.GetTypedObjectForIUnknown(IUnknown, typeof(IMAPIProp)); return(mapiProp.SaveChanges(KEEP_OPEN_READWRITE) == 0); } catch (Exception ex) { Log.Error().WriteLine(ex); return(false); } finally { // cleanup all references to COM Objects if (IMAPIProp != IntPtr.Zero) { Marshal.Release(IMAPIProp); } //if (IMessage != IntPtr.Zero) Marshal.Release(IMessage); if (IUnknown != IntPtr.Zero) { Marshal.Release(IUnknown); } } }
/// <summary> /// https://msdn.microsoft.com/en-us/library/office/cc842307.aspx /// </summary> public void Flag(IMailItem model) { EmailMessage message = GetEmailMessage(model, ItemSchema.Flag); if (Version < ExchangeVersion.Exchange2013) { message.SetExtendedProperty(PidTagFlagStatus, (short)MailFlag.Flagged); } else { message.Flag.FlagStatus = ItemFlagStatus.Flagged; } message.Update(ConflictResolutionMode.AutoResolve); }
public ActionResult Archive(MailItem model) { if (!ModelState.IsValid) { return(View(model)); } IMailItem itemRead = Mail.Get(model); Mail.Complete(itemRead); return(RedirectToAction("Index", "Convert") .Success("Mail archivied: " + itemRead.Subject)); }
public void ExecuteAttach(AttachKind objType, IMailItem mItem) { try { AttachWorkerBase worker; switch (objType) { case AttachKind.Contact: worker = new AttachWorkerContact(); break; case AttachKind.Organization: worker = new AttachWorkerOrganization(); break; default: throw new NotImplementedException(objType.ToString()); } worker.Init(_application, mItem); var result = worker.ExecuteAttach(); switch (result.Code) { case AttachmentResultCode.NotFound: if (worker.CreateNewObject(result.Message)) { worker.OnAfterSuccessfulAttach(); result = worker.ExecuteAttach(); } break; case AttachmentResultCode.Error: MessageBox.Show(string.IsNullOrWhiteSpace(result.Message) ? "Error" : result.Message, "PPOL", MessageBoxButtons.OK, MessageBoxIcon.Error); break; default: if (!string.IsNullOrWhiteSpace(result.Message)) { MessageBox.Show(result.Message, "PPOL", MessageBoxButtons.OK, MessageBoxIcon.Information); } break; } } catch (Exception ex) { ClassFactory.Instance.ConnectionProblem(ex); } }
public IAttachment GetAsAttachment(IMailItem model) { EmailMessage message = GetEmailMessage(model); string title = message.Subject; message.Load(new PropertySet(ItemSchema.MimeContent)); using (MemoryStream ms = new MemoryStream()) { MimeContent mc = message.MimeContent; ms.Write(mc.Content, 0, mc.Content.Length); return(Factory.ToAttachment(title, ms.ToArray())); } }
public IMailItem GetCurrentInspectorItem() { IMailItem mi = null; try { var inspector = _app.ActiveInspector(); if (inspector != null) { mi = GetItemByInspector(inspector); Marshal.ReleaseComObject(inspector); } } catch { } return(mi); }
// TODO: Figure out how to implement this public void AddAttachment(IMailItem mailItem) { #if false var itemProvider = mailItem as MailItemProvider; var itemAttachment = new ItemAttachment { Item = new Item { Id = itemProvider.Handle.Id }, Name = "Item Attachment!!!", }; Util.PostAsync <ItemAttachment>(Uri + "/attachments", itemAttachment).Wait(); #endif }
private void MailEvents_Respond(IMailItem mail, IMailItem response) { Logger.Instance.Trace(this, "Responding to mail, checking"); using (IStore store = mail.GetStore()) { ZPushAccount zpush = Watcher.Accounts.GetAccount(store); Logger.Instance.Trace(this, "Checking ZPush: {0}", zpush); if (zpush != null) { // Check if the containing folder is a shared folder using (IFolder parent = mail.Parent) { Logger.Instance.Trace(this, "Checking, Parent folder: {0}", parent.Name); SharedFolder shared = _sharedFolders.GetSharedFolder(parent); if (shared != null) { Logger.Instance.Trace(this, "Checking, Shared folder: {0}, flags={1}", shared, shared?.Flags); } else { Logger.Instance.Trace(this, "Not a shared folder"); } if (shared != null && shared.FlagSendAsOwner) { Logger.Instance.Trace(this, "Checking, Shared folder owner: {0}", shared.Store.UserName); // It's a shared folder, use the owner as the sender if possible using (IRecipient recip = FindSendAsSender(zpush, shared.Store)) { Logger.Instance.Trace(this, "Checking, Shared folder owner recipient: {0}", recip.Name); if (recip != null && recip.IsResolved) { Logger.Instance.Trace(this, "Sending as: {0}", recip.Address); using (IAddressEntry address = recip.GetAddressEntry()) { response.SetSender(address); } } else { Logger.Instance.Error(this, "Unable to resolve sender: {0}", shared.Store.UserName); } } } } } } }
public IDefect LookFor(IMailItem mailItem) { IDefect result = null; IMailItem mail = Mail.Get(mailItem); string subject = Factory.GetSubject(mail); using (TfsTeamProjectCollection service = Service) { WorkItemStore workItemStore = service.GetService <WorkItemStore>(); WorkItemCollection workItems = GetWorkItemByTitle(workItemStore, subject); result = ToDefectItemCollection(workItems).FirstOrDefault(); } return(result); }
EmailMessage GetEmailMessage(IMailItem model, params PropertyDefinitionBase[] additionalProperties) { if (additionalProperties == null) { additionalProperties = new PropertyDefinitionBase[] { ItemSchema.Attachments, ItemSchema.Body, ItemSchema.Categories, ItemSchema.Flag, ItemSchema.Importance, ItemSchema.ConversationId } } ; PropertySet prop = new PropertySet(BasePropertySet.FirstClassProperties, additionalProperties); return(EmailMessage.Bind(Service, new ItemId(model.UniqueId))); }
private void SetReplyFlag(IMailItem mail, IMailItem response, Verb verb) { if (!UpdateOutgoing) { return; } string id = (string)mail.GetProperty(OutlookConstants.PR_ZPUSH_MESSAGE_ID); using (IFolder folder = mail.Parent) { string folderId = (string)folder.GetProperty(OutlookConstants.PR_ZPUSH_SYNC_ID); string value = ReplyFlags.VerbToExchange(verb) + "/" + id + "/" + folderId; Logger.Instance.Trace(this, "Reply header: {0}", value); response.SetProperty(Constants.ZPUSH_REPLY_HEADER, value); } }
// TODO: Figure out how to implement this public void AddAttachment(IMailItem mailItem) { #if false var itemProvider = mailItem as MailItemProvider; var msgFetcher = _outlookClient.Me.Messages.GetById(_message.Id); var itemAttachment = new ItemAttachment { Item = itemProvider.Handle as Message, Name = "Item Attachment!!!", }; Util.Synchronize(async() => await msgFetcher.Attachments.AddAttachmentAsync(itemAttachment)); #endif }
public ActionResult Create(string id, string mailId) { IMailItem model = Mail.Get(ServiceFactory.Get <IItemFactory>().GetNew <IMailItem>(HttpUtility.UrlDecode(mailId))); IDefect defect = Service.LookFor(model); if (defect == null) { IMailItem itemRead = Mail.Get(model); Mail.Flag(itemRead); defect = ServiceFactory.Get <IItemFactory>().GetNewDefect(itemRead); return(View(new DefectViewModel(defect))); } else { return(RedirectToAction("Notify", "Defect", new { id = defect.Id, mailId = model.UniqueId })); } }
/// <summary> /// This method sends mail according to the parameter /// </summary> /// <param name="operation">parameters for MailSend</param> /// <returns>true if processed successfully, false otherwise</returns> private bool MailSend(MailSimOperationsMailSend operation) { int iterations = GetIterationCount(operation.Count); if (iterations < 1) { Log.Out(Log.Severity.Error, operation.OperationName, "Count is less than the minimum allowed value", iterations); return(false); } for (int count = 1; count <= iterations; count++) { try { // generates a new email IMailItem mail = olMailStore.NewMailItem(); mail.Subject = DateTime.Now.ToString() + " - "; mail.Subject += (string.IsNullOrEmpty(operation.Subject)) ? DefaultSubject : operation.Subject; Log.Out(Log.Severity.Info, operation.OperationName, "Subject: {0}", mail.Subject); mail.Body = BuildBody(operation.Body); Log.Out(Log.Severity.Info, operation.OperationName, "Body: {0}", mail.Body); if (!AddRecipients(mail, operation)) { return(false); } AddAttachments(mail, operation); mail.Send(); } catch (Exception ex) { Log.Out(Log.Severity.Error, operation.OperationName, "Exception encountered\n" + ex); return(false); } SleepOrStop(operation.OperationName, operation.Sleep); } return(true); }
private bool AddRecipients(IMailItem mail, dynamic operation) { List <string> recipients = GetRecipients(operation.OperationName, operation.RecipientType, operation.Recipients); if (recipients == null) { Log.Out(Log.Severity.Error, operation.OperationName, "Recipient is not specified, skipping operation"); return(false); } // Add all recipients foreach (string recpt in recipients) { Log.Out(Log.Severity.Info, operation.OperationName, "Recipient: {0}", recpt); mail.AddRecipient(recpt); } return(true); }
/// <summary> /// This method gets called when an event is triggered by the monitored folder. /// </summary> /// <param name="Item">Item corresponding to the event</param> public static void FolderMonitorEvent(object Item) { if (Item == null) { Log.Out(Log.Severity.Info, eventString, "Unknown event received"); return; } // Only processing the MailItem if (Item is IMailItem) { IMailItem mail = (IMailItem)Item; Log.Out(Log.Severity.Info, eventString, "New item from {0} with subject \"{1}\"!!", mail.SenderName, mail.Subject); } else { Log.Out(Log.Severity.Info, eventString, "Event received but with unknown type " + Item.GetType().ToString()); } }
private void MailEvents_ItemSend(IMailItem item, ref bool cancel) { using (IStore store = item.GetStore()) { ZPushAccount zpush = Watcher.Accounts.GetAccount(store); if (zpush != null) { string address = item.SenderEmailAddress; if (address != null && address != zpush.Account.SmtpAddress) { Logger.Instance.Trace(this, "SendAs: {0}: {1}", address, item.SenderName); item.SetProperty(Constants.ZPUSH_SEND_AS, address); if (item.SenderName != null) { item.SetProperty(Constants.ZPUSH_SEND_AS_NAME, item.SenderName); } } } } }
/// <summary> /// This method replies email according to the parameters /// </summary> /// <param name="operation">parameters for MailReply</param> /// <returns>true if processed successfully, false otherwise</returns> private bool MailReply(MailSimOperationsMailReply operation) { var parsedOp = ParseOperation(operation, operation.Folder, operation.MailSubjectToReply); return(parsedOp.Iterate((indexToReply, mails) => { IMailItem mailToReply = mails[indexToReply].Reply(operation.ReplyAll); Log.Out(Log.Severity.Info, operation.OperationName, "Subject: {0}", mailToReply.Subject); mailToReply.Body = BuildBody(operation.ReplyBody) + mailToReply.Body; Log.Out(Log.Severity.Info, operation.OperationName, "Body: {0}", mailToReply.Body); // process the attachment AddAttachments(mailToReply, operation); mailToReply.Send(); return true; })); }
public void AddAttachment(IMailItem mailItem) { var provider = mailItem as MailItemProviderOM; _mailItem.Attachments.Add(provider.Handle); }
// TODO: Figure out how to implement this public void AddAttachment(IMailItem mailItem) { #if false var itemProvider = mailItem as MailItemProvider; var msgFetcher = _outlookClient.Me.Messages.GetById(_message.Id); var itemAttachment = new ItemAttachment { Item = itemProvider.Handle as Message, Name = "Item Attachment!!!", }; Util.Synchronize(async () => await msgFetcher.Attachments.AddAttachmentAsync(itemAttachment)); #endif }
private void AddAttachments(IMailItem mail, dynamic operation) { var attachments = GetAttachments(operation); foreach (string attmt in attachments) { Log.Out(Log.Severity.Info, operation.OperationName, "Attachment: {0}", attmt); mail.AddAttachment(attmt); } }
/// <summary> /// This method gets called when an event is triggered by the monitored folder. /// </summary> /// <param name="Item">Item corresponding to the event</param> public static void FolderEvent(IMailItem mail) { Console.WriteLine("\nEvent: New item from {0} with subject \"{1}\"!!\n", mail.SenderName, mail.Subject); }
// TODO: Figure out how to implement this public void AddAttachment(IMailItem mailItem) { #if false var itemProvider = mailItem as MailItemProvider; var itemAttachment = new ItemAttachment { Item = new Item { Id = itemProvider.Handle.Id }, Name = "Item Attachment!!!", }; Util.PostAsync<ItemAttachment>(Uri + "/attachments", itemAttachment).Wait(); #endif }
private bool AddRecipients(IMailItem mail, dynamic operation) { var recipients = GetRecipients(operation); if (recipients == null) { Log.Out(Log.Severity.Error, operation.OperationName, "Recipients are not specified, skipping operation"); return false; } // Add all recipients foreach (string recpt in recipients) { Log.Out(Log.Severity.Info, operation.OperationName, "Recipient: {0}", recpt); mail.AddRecipient(recpt); } return true; }