Search code examples
c#vstooutlook-addinemail-attachments

VSTO C# custom form if i forget add attachment to email


When I press a custom button on my form, I need to check if the user has forgotten to add an attachment, otherwise the msbox must appear and stop sending the e-mail until the attachment is inserted.

public partial class AddItemsForm : Form
    {
        public AddItemsForm()
        {
            InitializeComponent();
        }
        private void Btn_send_Click(object sender, EventArgs e)
        {
        // If Attachment.Add() = false
        // show msgox
        }

UPDATE I

form.cs

    private DialogResult GetAttachmentsInfo(MailItem mailItem)
    {
        StringBuilder attachmentInfo = new StringBuilder();
        Attachments mailAttachments = mailItem.Attachments;
        if (mailItem.Attachments.Count == 0)
        {
            return MessageBox.Show(" ", " ", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
        } else {
            return DialogResult.OK;
        }
    }

 private void Btn_send_Click(object sender, EventArgs e)
    {
        GetAttachmentsInfo(mailItem);
    }

Error in Outlook after press the button : Object reference not set to an instance of an object.

any ideas ?

UPDATE II error

Object reference not set to an instance of an object.


************** Exception Text **************
System.NullReferenceException: Object reference not set to an instance of an object.
   at OutlookControll.Form1.GetAttachmentsInfo(MailItem mailItem) ChooseFormSend.cs:line 33
   at OutlookControll.Form1.Btn_standard_Click(Object sender, EventArgs e) ChooseFormSend.cs:line 74
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

Solution

  • Check if MailItem.Attachments.Count == 0. Or, if there were, for example, image files, check if the number of attachments is the same as when the message was created.