4

I have a list of documents and email addresses.

I am trying to create a method I can use to iterate throw the list of emailAddresses and for each creates a new email I Outlook and attaches the corresponding document.

The Creating the MailItem is was I get stuck. Found a sample on MSDN that should work from Office 2013 and forward.

This is what I have so far:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Outlook;

namespace Test_Invoice
{
    class SendviaMail
    {
        string demofile = @"C:\Desktop\test-inv\1_Test Testesen_1_010.pdf";
        public void Send()
        {
            MailItem eMail = new MailItem();

            eMail.Subject = "Here is Your Invoice";
            eMail.To = "test@testesen.dk";
            eMail.Body = "Dette er en test mail for TestMailApp";

        }

        public void Send(string email, string filename)
        {

        }
    }
}

I've been trying to understand the documentation on MSDN and read thru a few posts on here.

As far as I can figure out, the next step is to add the attachment (the demo file) If I understand it right I need something like

eMail.AttachmentAdd = demofile;

But that does not work.

It might be me that does not understand the library correctly. Looking at this sample from MSDN https://msdn.microsoft.com/en-us/library/bb644320.aspx

Results in this code:

using Microsoft.Office.Interop.Outlook;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Outlook = Microsoft.Office.Interop.Outlook;

namespace Test_Invoice
{
    class SendviaMail
    {
        string demofile = @"C:\Desktop\test-inv\1_Test Testesen_1_010.pdf";
        public void Send()
        {
            Outlook.MailItem mail = Application.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
            mail.Subject = "Quarterly Sales Report FY06 Q4";

            //MailItem eMail = new MailItem();

            //eMail.Subject = "tilmelding og faktura";
            //eMail.To = "test@testesen.dk";
            //eMail.Body = "Dette er en test mail for TestMailApp";
            //eMail.AttachmentAdd
        }

        public void Send(string email, string filename)
        {

        }
    }
}
Jonas
  • 53
  • 1
  • 2
  • 6
  • 1
    [MSDN](https://msdn.microsoft.com/en-us/library/bb644320.aspx) seems to offer a decent example. – Filburt May 28 '17 at 10:54
  • I have actually looked at that. It might be that I just don't understand it. but VS does not recognise the Application.CreateItem – Jonas May 28 '17 at 12:17
  • This is the Error I get: Error CS0120 An object reference is required for the non-static field, method, or property '_Application.CreateItem(OlItemType)' – Jonas May 28 '17 at 12:40
  • Could you update your code here with the `Application.CreateItem` that gives you this error? – Filburt May 28 '17 at 12:42
  • You are right - the linked example is wrong - you need to construct an Outlook.Application instance to get this to work. Be prepared that your running instance of Outlook will inquire if your app can use the opened instance. – Filburt May 28 '17 at 12:55
  • @Filburt Thanks. Can you point me to a good resource to read up on this? in the meantime I'll try google. – Jonas May 28 '17 at 12:58
  • Possible duplicate of [Sending Email through Outlook 2010 via C#](https://stackoverflow.com/questions/19911230/sending-email-through-outlook-2010-via-c-sharp) – Gokul Jun 02 '17 at 10:12

2 Answers2

1

use .Net class for that:

public static void CreateMessageWithAttachment(string server,string filePath)
{
    // Specify the file to be attached and sent.
    // This example assumes that a file named Data.xls exists in the
    // current working directory.
    string file = filePath;
    // Create a message and set up the recipients.
    MailMessage message = new MailMessage(
       "jane@contoso.com",
       "ben@contoso.com",
       "Quarterly data report.",
       "See the attached spreadsheet.");

    // Create  the file attachment for this e-mail message.
    Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
    // Add time stamp information for the file.
    ContentDisposition disposition = data.ContentDisposition;
    disposition.CreationDate = System.IO.File.GetCreationTime(file);
    disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
    disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
    // Add the file attachment to this e-mail message.
    message.Attachments.Add(data);

    //Send the message.
    SmtpClient client = new SmtpClient(server);
    // Add credentials if the SMTP server requires them.
    client.Credentials = CredentialCache.DefaultNetworkCredentials;

    try {
      client.Send(message);
    }
    catch (Exception ex) {
      Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}", 
                  ex.ToString() );            
    }
    data.Dispose();
}

after that just iterate the list from loop and send it to the function

more example you can use https://www.codeproject.com/Tips/286952/create-a-simple-smtp-server-in-csharp

Leon Barkan
  • 2,676
  • 2
  • 19
  • 43
  • will this use the current users email profile in windows? its a wpf application and needs to use the current users outlook to generate the email. – Jonas May 28 '17 at 12:13
  • if you have smpt server on the pc you need to send in to the function or just initialize it hardcoded in the function – Leon Barkan May 28 '17 at 12:15
  • Nice example. But it seams to me that we are overcomplicating things by writing an SMTP Server into the application to be able to send the email. as Filburt surgested above the other method by using Outlook seams to be well documented and there are lots of posts and samples on it. But I seam to be missing some part of the puzzle. – Jonas May 28 '17 at 12:28
  • @Jonas There is no *programming* overhead involved sending the message via smtp - however it can be difficult to convince your administrators to allow smtp relay for every user. Also if your requirement is, to have your mail item tracked in your Exchange account, the quoted example is the way to go. – Filburt May 28 '17 at 12:39
  • This will submit the email to an SMTP server from the application host. The original poster asked to create a new email with attachment for sending from Outlook 2016. It's a useful alternative, but doesn't answer the question. – Suncat2000 Feb 15 '19 at 19:03
1

The fixed sample code should look like this:

var ol = new Outlook.Application();
Outlook.MailItem mail = ol.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;

note that you need to declare the Outlook alias with your using statement:

using Outlook = Microsoft.Office.Interop.Outlook;

(as you already did) ... but must also remove

using Microsoft.Office.Interop.Outlook;

to avoid Visual Studio confusing your references.

The rest of the MSDN example should work as expected I don't have any other samples I can point you to, so your best bet is searching for Microsoft.Office.Interop.Outlook or explore linked questions here.

Filburt
  • 17,626
  • 12
  • 64
  • 115
  • Found this reference and sample for using the Application or getting the active process https://msdn.microsoft.com/en-us/library/office/ff462097.aspx – Jonas May 28 '17 at 22:21