简体   繁体   中英

Attaching an 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:

  1. I am writing a plugin for outlook
  2. I am getting the error on this line : Attachment attach = new Attachment(mailItem, new System.Net.Mime.ContentType("text/html; charset=us-ascii"));
  3. Error message is : Cannot create an instance of the abstract class or interface 'Microsoft.Office.Interop.Outlook.Attachment'
  4. Sample code 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); } } } 

After doing a bit more reading/searching, I was able to find something that works. Probably the most difficult 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);
                }

Thanks to @Kris Vandermotten for pointing me in the right direction

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM