简体   繁体   中英

how to cancel sending a message from Outlook and close the form

I try to cancel sending the message from Outlook. I need get all fields from mailItem and close it without sending.

in my code i get an error - Unable to execute command Item.Close during the event Item.Send.

public partial class MyMainForm
{
    Outlook.Application oApp;
    Outlook.MailItem mailItem;
    System.Threading.Timer timer_CloseMail;

  private void Mail_in_outlook()
    {
        oApp = new Outlook.Application();
        mailItem = Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

        TimerCallback tm = new TimerCallback(CloseMail);
        timer_CloseMail = new Timer(tm);

        oApp.ItemSend += oApp_ItemSend;
        mailItem.DeleteAfterSubmit = true;

        mailItem.Display(true);

        // get mailItem.HTMLBody and other field....

    }

void oApp_ItemSend(object Item,ref bool Cancel)
    {
        Cancel = true;
        MailtimeTimer.Change(0, 0);
    }

private void CloseMail(object sender)
    {
        mailItem.Close(Outlook.OlInspectorClose.olDiscard);
    }

Some MAilItem methods (such as Send or Close) cannot be called in that event handler. You can use a timer (use the one from the Forms namespace since it runs on the same thread) and enable it in the ItemSEnd event. When the timer fires, disable it and call MailItem.Close - by that time you will be out o the ItemSent event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM