I’m trying to create an add-in which will save selected emails in msg format. I have a custom toolbar with a button. The button opens a form, and on the form you can select the location you want the emails to be saved to. The problem occures when I try to save the emails. I get an error “System.NullReferenceException: Object reference not set to an instance of an object at button4_Click” (button4 starts the process). I’ve tried several methods – non of them worked 🙁 Now I1m stuck and can’t do much, although I know that the problem is with the Outlook.Mailitem declaration (it can’t be null or something like that). I would really appreciate your help with this.
(I’m using Win XP, Outlook 2007, .NET framework 3.5 and language is C#.)
The code is:
private void button4_Click(object sender, EventArgs e)
{
Outlook.NameSpace _nameSpace = Globals.ThisAddIn.Application.GetNamespace(“MAPI”);
Outlook.MAPIFolder _mapiFolder = _nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
Outlook.Explorer _currentExplorer = Globals.ThisAddIn.Application.ActiveExplorer();
Outlook.MailItem _mailItem = _mapiFolder.Items as Outlook.MailItem;
string saveToFolder = comboBox1.Text;
//string _subject = _mailItem.Subject.ToString();
bool exists = Directory.Exists(saveToFolder);
try
{
Outlook.Selection _selection = _currentExplorer.Selection;
for (int i = 1; i <= _selection.Count; i++)
{
Object selObj = _mapiFolder.Items[i];
if (selObj is Outlook.MailItem && _mailItem != null)
{
if (exists == true)
{
_mailItem.SaveAs(saveToFolder, Outlook.OlSaveAsType.olMSG);
MessageBox.Show("you have " + _selection.Count + " items selected and your folder exists! Email saved!");
}
else if (exists == false)
{
System.IO.Directory.CreateDirectory(saveToFolder);
_mailItem.SaveAs(saveToFolder, Outlook.OlSaveAsType.olMSG);
MessageBox.Show("you have " + _selection.Count + " items selected and your folder was created successfully. Email saved!");
}
}
}
}
catch (NullReferenceException ex)//(Exception ex)
{
MessageBox.Show("Error: " + ex);
}
}