如果我忘记将附件添加到电子邮件,VSTO C# 自定义表单

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

当我按下表单上的自定义按钮时,我需要检查用户是否忘记添加附件,否则必须出现 msbox 并停止发送电子邮件,直到插入附件。

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

更新我

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);
    }

按下按钮后 Outlook 出错:Object reference not set to an instance of an object.

有什么想法吗?

更新二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)

检查是否 MailItem.Attachments.Count == 0。 或者,如果有,例如,图像文件,请检查附件数量是否与创建邮件时相同。

有解决办法:

    private void Btn_Click(object sender, EventArgs e)
    { 
        Microsoft.Office.Interop.Outlook.Application application = new Microsoft.Office.Interop.Outlook.Application();
        Inspector inspector = application.ActiveInspector();

        if (inspector.CurrentItem is MailItem inspectorMailItem)
        {
            String Subject = inspectorMailItem.Subject;
            String EmailAddress = inspectorMailItem.To;

            if (inspectorMailItem.Attachments.Count == 0)
            {
                MessageBox.Show("No Attachment");

                this.Hide();