Attach email as an attachment to another email

I would like to know how to attach an email as an attachment to another email in C #. Details:

  • I am writing a plugin for Outlook
  • I get an error on this line: Attachment attach = new Attachment (mailItem, new System.Net.Mime.ContentType ("text / html; charset = us-ascii"));
  • Error message: cannot create an instance of the abstract class or interface "Microsoft.Office.Interop.Outlook.Attachment"
  • Code example below

    private void button1_Click(object sender, RibbonControlEventArgs e)
    {
        Explorer explorer = Globals.ThisAddIn.Application.ActiveExplorer();
        Selection selection = explorer.Selection;
    
        if (selection.Count > 0)   // Check that selection is not empty.
        {
            object selectedItem = selection[1];   // Index is one-based.
            MailItem mailItem = selectedItem as MailItem;
    
    
            if (mailItem != null)    // Check that selected item is a message.
            {
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                message.To.Add("blah@blah.com");
                message.Subject = "blah";
                message.From = new System.Net.Mail.MailAddress("test@test.com");
                message.Body = "This is the message body";
    
                 Attachment attach = new Attachment(mailItem, new System.Net.Mime.ContentType("text/html; charset=us-ascii"));
                 message.Attachments.Add(attach);
                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smlsmtp");
                smtp.Send(message);
    
            }
        }
    }
    
+4
source share
1 answer

After a bit more reading / searching, I was able to find something that works. Probably the hardest part is the first line.

                try
                {
                    Outlook.MailItem tosend = (Outlook.MailItem)Globals.ThisAddIn.Application.CreateItem(Outlook.OlItemType.olMailItem);
                    tosend.Attachments.Add(mailItem);
                    tosend.To = "blah@blah.com";
                    tosend.Subject = "test";
                    tosend.Body = "blah";
                    tosend.Save();
                    tosend.Send();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("{0} Exception caught: ", ex);
                }

@Kris Vandermotten ,

0

Source: https://habr.com/ru/post/1529717/


All Articles