Поделиться через


Практическое руководство. Копирование сообщения электронной почты с помощью настраиваемой команды меню

Обновлен: Ноябрь 2007

Применение

Сведения, приведенные в данном разделе, относятся только к указанным проектам Visual Studio Tools for Office и версиям Microsoft Office.

Тип проекта

  • Проекты уровня приложения

Версия Microsoft Office

  • Outlook 2003

  • Outlook 2007

Дополнительные сведения см. в разделе Доступность функций по типам приложений и проектов.

В данном примере демонстрируется создание команды Копировать в папку "Пикник" в контекстном меню элемента электронной почты, если в поле Subject сообщения электронной почты есть текст Пикник. Если пользователь выбирает команду Копировать в папку "Пикник", код создает копию сообщения электронной почты и перемещает ее в папку Пикник.

Пример

Dim WithEvents explorer As Outlook.Explorer = Nothing
Const FOLDER_NAME As String = "Picnic"
Dim selectedItems As New System.Collections.ArrayList()

Private Sub ThisAddIn_Startup(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles Me.Startup
    explorer = Me.Application.Explorers.Application.ActiveExplorer
    AddHandler explorer.SelectionChange, _
    AddressOf explorer_SelectionChange
End Sub

Private Sub explorer_SelectionChange() _
    Handles explorer.SelectionChange

    selectedItems.Clear()

    For Each selectedItems As Object In explorer.Selection

        Dim mailItem As Outlook.MailItem = _
            TryCast(selectedItems, Outlook.MailItem)

        If (mailItem IsNot Nothing) Then
            If mailItem.Subject.Contains(FOLDER_NAME) Then
                Dim newAction As Outlook.Action = _
                mailItem.Actions(String.Format _
                ("Copy to {0} Folder", FOLDER_NAME))
                If (newAction Is Nothing) Then
                    newAction = mailItem.Actions.Add()
                    newAction.Name = String.Format _
                        ("Copy to {0} Folder", FOLDER_NAME)
                    newAction.ShowOn = _
                        Outlook.OlActionShowOn.olMenu
                    newAction.Enabled = True
                    mailItem.Save()
                End If
                AddHandler mailItem.CustomAction, _
                    AddressOf mailItem_CustomAction
            End If
        End If
    Next
End Sub

Private Sub mailItem_CustomAction(ByVal Action As Object, _
    ByVal Response As Object, ByRef Cancel As Boolean)
    Try
        Dim mailAction As Outlook.Action = _
            CType(Action, Outlook.Action)

        ' Get the current selection from the explorer and 
        ' copy it to the FOLDER_NAME folder 
        Select Case mailAction.Name
            Case String.Format("Copy to {0} Folder", FOLDER_NAME)
                Dim mailItem As Outlook.MailItem = _
                    TryCast(explorer.Selection(1),  _
                    Outlook.MailItem)
                Dim mailItemCopy As Outlook.MailItem = _
                TryCast(mailItem.Copy, Outlook.MailItem)

                Dim inbox As Outlook.MAPIFolder = _
                    Me.Application.GetNamespace("MAPI"). _
                    GetDefaultFolder( _
                    Outlook.OlDefaultFolders.olFolderInbox)

                Dim folder As Outlook.MAPIFolder = Nothing

                ' If the folder does not exist, create it.
                Try
                    folder = inbox.Folders(FOLDER_NAME)
                Catch ex As  _
                    System.Runtime.InteropServices.COMException
                    '  This exception is thrown 
                    '  when the folder is not found.
                Catch ex As Exception
                    MessageBox.Show(ex.Message)
                End Try

                If (folder Is Nothing) Then
                    folder = inbox.Folders.Add(FOLDER_NAME, _
                        Outlook.OlDefaultFolders.olFolderInbox)
                End If

                mailItemCopy.Move(folder)
                ' Do not display the inspector object.
                Cancel = True
        End Select
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub
Outlook.Explorer explorer = null;
private const string FOLDER_NAME = "Picnic";

System.Collections.ArrayList selectedItems = new
    System.Collections.ArrayList();

private void ThisAddIn_Startup(object sender,
    System.EventArgs e)
{
    explorer = this.Application.Explorers.Application.ActiveExplorer();
    explorer.SelectionChange += new Outlook.
        ExplorerEvents_10_SelectionChangeEventHandler
        (explorer_SelectionChange);
}

void explorer_SelectionChange()
{
    selectedItems.Clear();

    foreach (object selectedItem in explorer.Selection)
    {
        Outlook.MailItem mailItem = selectedItem as Outlook.MailItem;

        if (mailItem != null)
        {
            if (mailItem.Subject.Contains(FOLDER_NAME))
            {
                Outlook.Action newAction = mailItem.Actions[
                    string.Format("Copy to {0} Folder", FOLDER_NAME)];

                if (newAction == null)
                {
                    newAction = mailItem.Actions.Add();
                    newAction.Name = string.Format
                        ("Copy to {0} Folder", FOLDER_NAME);
                    newAction.ShowOn =
                        Outlook.OlActionShowOn.olMenu;
                    newAction.Enabled = true;
                    mailItem.Save();
                }

                mailItem.CustomAction += new Outlook.
                    ItemEvents_10_CustomActionEventHandler
                    (mailItem_CustomAction);

                selectedItems.Add(mailItem);
            }
        }
    }
}

void mailItem_CustomAction(object Action, object Response,
    ref bool Cancel)
{
    try
    {
        Outlook.Action mailAction = (Outlook.Action)Action;
        // Get the current selection from the explorer and 
        // copy it to the FOLDER_NAME folder 
        switch (mailAction.Name)
        {
            case "Copy to " + FOLDER_NAME + " Folder":
                Outlook.MailItem mailItem =
                    explorer.Selection[1] as Outlook.MailItem;
                Outlook.MailItem mailItemCopy =
                    mailItem.Copy() as Outlook.MailItem;

                Outlook.MAPIFolder inbox =
                    this.Application.GetNamespace("MAPI").GetDefaultFolder
                    (Outlook.OlDefaultFolders.olFolderInbox);
                Outlook.MAPIFolder folder = null;

                // If the folder does not exist, Create it.
                try
                {
                    folder = inbox.Folders[FOLDER_NAME];
                }
                catch (System.Runtime.InteropServices.COMException)
                {
                    // This exception is thrown when the folder is not found.
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                if (folder == null)
                {
                    folder = inbox.Folders.Add(FOLDER_NAME,
                        Outlook.OlDefaultFolders.olFolderInbox);
                }

                mailItemCopy.Move(folder);
                // Do not display the inspector object.
                Cancel = true;
                break;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

См. также

Основные понятия

Работа с элементами почты

Приступая к программированию надстроек на уровне приложения