Attach a document from SharePoint 2010 document library in email

Steps Involved:
  1. Open Visual Studio 2010 by going Start | All Programs | Microsoft Visual Studio 2010 | Right click on Microsoft Visual Studio 2010 and click on Run as administrator.
  2. Go to File tab, click on New and then click on Project.
  3. In the New Project dialog box, expand the Visual C# node, and then select the Windows node.
  4. In the Templates pane, select Console Application.
  5.  Enter the Name as SendEmailand then click OK.
  6.  In the solution explorer, right click on the solution and then click on Properties.
  7. Select the Application tab, check whether “.Net Framework 3.5” is selected for Target Framework.
  8. Select the Build tab, check whether “Any CPU” is selected for Platform Target.
  9. Add the following references

     Microsoft.SharePoint 

  1. Add the following namespaces

        using Microsoft.SharePoint; 
   using System.Net.Mail;

  1. Replace Program.cs with the following code

 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Net.Mail;

using Microsoft.SharePoint;

 

namespace SendEmail

{

    class Program

    {

        static void Main(string[] args)

        {

            using (SPSite site = new SPSite("https://serverName/sites/Test/"))

            {

                using (SPWeb web = site.OpenWeb())

                {

                    SPList list = web.Lists.TryGetList("Shared Documents");

                    if (list != null)

                    {

                        SPFile file = list.Items[0].File;

                        MailMessage mail = new MailMessage();

                        mail.From = new MailAddress("[email protected]");

                        mail.To.Add("[email protected]");

                        mail.Subject = "Test";

                        mail.Body = "TEST";

                        mail.Attachments.Add(new Attachment(file.OpenBinaryStream(), file.Name));

                        // SmtpClient class sends the email by using the specified SMTP server

                        SmtpClient smtp = new SmtpClient(site.WebApplication.OutboundMailServiceInstance.Server.Address);

                        smtp.UseDefaultCredentials = true;

                        smtp.Send(mail);

                    }

                }

            }

        }

    }

}



Output:

email.jpg