Home > Software design >  How to get the attachment count when sending email C#
How to get the attachment count when sending email C#

Time:02-12

I'm not that good at C# to be honest and I'm trying to create a little app for my job that need to count the number of attachment in the email that the user want to send. I've look in the MS doc and on other StackOverflow's threads but I'm still unable to find something that work for me.

Here's what I have for now, I just need to get the count of attachment of the email:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Windows.Forms;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;

namespace OutlookAddIn1
{
    public partial class ThisAddIn
    {
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            Application.ItemSend  = new Outlook.ApplicationEvents_11_ItemSendEventHandler(Application_ItemSend);
        }

        void Application_ItemSend(object Item, ref bool Cancel)
        {
            MessageBox.Show("You have"   Application_ItemAttached().ToString()   "item(s) attached in this mail");
            Cancel = true;
        }

        public static int Application_ItemAttached(Outlook.MailItem mailitems)
        {
            var attachments = mailitems.Attachments;
            return attachments.Count;
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
            // Remarque : Outlook ne déclenche plus cet événement. Si du code
            //    doit s'exécuter à la fermeture d'Outlook (consultez https://go.microsoft.com/fwlink/?LinkId=506785)
        }

        #region Code généré par VSTO

        /// <summary>
        /// Méthode requise pour la prise en charge du concepteur - ne modifiez pas
        /// le contenu de cette méthode avec l'éditeur de code.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup  = new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown  = new System.EventHandler(ThisAddIn_Shutdown);
        }
        
        #endregion
    }
}

Thanks for your help!

CodePudding user response:

Does your code actually compile? You already have the function that counts the attachments, but it takes MailItem object as a parameter, and you are not passing anything. Change it to

MessageBox.Show("You have "   Application_ItemAttached(Item as Outlook.MailItem).ToString()   " item(s) attached in this mail");
  • Related