Sunday, 21 February 2016

Send an email with attachment from sharepoint List/Library

using System.Net.Mail;
using (SPWeb web = site.OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;
                     
                        MailMessage message = new MailMessage();
                        //Get the Sharepoint SMTP information from the //SPAdministrationWebApplication
                        message.From = new MailAddress(SPAdministrationWebApplication.Local.OutboundMailSenderAddress.ToString());
                        message.To.Add(new MailAddress("user@gmail.com"));
                        message.IsBodyHtml = true;
                       //Set the subject and body of the message
                        message.Body = "Hi there, check out the attachment";
                        message.Subject = "Sent Attachment";
                        //Get the Document Library from where you want to sed the attachment
                        SPList library = web.Lists["MyDocuments"];
                        //Get the Url of the file to be sent as an attachment
                        string strUrl = "http://siteUrl/MyDocuments/Configuring Database Mial  SQL server 2008.doc";
                        //Get the file to be sent as an attachment
                        SPFile file = library.ParentWeb.GetFile(strUrl);
                        //Add the attachment
                        message.Attachments.Add(new Attachment(file.OpenBinaryStream(), file.Name));
                         //Create the SMTP client object and send the message
                        SmtpClient smtpClient = new SmtpClient(SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address);
                        smtpClient.Send(message);


                        web.AllowUnsafeUpdates = false;
                    }

No comments:

Post a Comment