1

I am creating a outlook 2013 add-on with C# and Visual Studio 2012 and I want to get the attachment file from the current (open) mail window when a button clicked and save it to a local directory.

Is there any example for this action?

Thank you.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150

1 Answers1

3

First you would need to get the object of the current mail item. After that you can just loop through the .Attachments of the mail item and save them with .SaveAsFile(filePath).

var _thisApp = this.Application;
Outlook.MailItem _email;

// Get current email
if(_thisApp.ActiveWindow() is Outlook.Inspector)
{
    Outlook.Inspector insp = _thisApp.ActiveWindow() as Outlook.Inspector;
    _email = insp.CurrentItem as Outlook.MailItem;
}
else if(_thisApp.AcitveWindow() is Outlook.Explorer)
{
    Outlook.Explorer exp = _thisApp.ActiveExplorer();
    if(exp.Selection.Count > 0)
        _email = exp.Selection[1] as Outlook.MailItem;
}

// Loop through the attachments
foreach(Outlook.Attachment attachment in _email.Attachments)
{
    // Some other stuff
    string filePath = @"C:\Saved Attachments\" + attachment.FileName;
    attachment.SaveAsFile(filePath);
}

EDIT: Sample to retrieve this.Application

private Outlook.Application _thisApp;
private Outlook.Inspectors _inspectors;

// Function in ThisAddin.cs 
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    _thisApp = this.Application;
    _inspectors = _thisApp.Inspectors;
    _inspectors.NewInspector +=
    new Microsoft.Office.Interop.Outlook.InspectorsEvents_NewInspectorEventHandler(Inspectors_NewInspector);
}
Natzely
  • 706
  • 2
  • 8
  • 27
  • I am getting a error for the line : var _thisApp = this.Application; does not contain a definition for 'Application' and no extension method..... –  Apr 03 '15 at 11:00
  • @Mantis `this.Application` should be accessible in the ThisAddin.cs. If you are trying to retrieve it from a different location, you could use `Globals.ThisAddin.Application`, though I would suggest you only access it through public methods in ThisAddin.cs. – Natzely Apr 04 '15 at 15:05