Saturday, September 27, 2008

Sending document as attachment in email

Scenario:
You client want to be able to actually e-mail the document itself from the document library to themselves, so they could read it apart from being on the SharePoint site.

Solution:
Design a Custom Application Page and use the code below to email the document.

Code:

using System.Net.Mail

private void SendEmail(string toAddress, string subject, SPFile file, SPList list)
{
SPWebApplication webApp = SPContext.Current.Site.WebApplication;
SPOutboundMailServiceInstance mailServer = webApp.OutboundMailServiceInstance;
string smtpServer = mailServer.Server.Address;

string listUrl = SPContext.Current.Web.Url + list.DefaultViewUrl;

MailMessage message = new MailMessage("administrator@training.com", toAddress);
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = "This file was sent from the following SharePoint list: " +
"<a href=\"" + listUrl + "\">" + listUrl + "</a>.";

Stream stream = file.OpenBinaryStream();
//You can add code to figure out which MIME type to use based on the type of attachment.
Attachment attachment = new Attachment(stream, @"application/msword");
attachment.Name = file.Name;
message.Attachments.Add(attachment);

try
{
SmtpClient client = new SmtpClient(smtpServer);
//client.Send(message);
client.SendAsync(message,"mail sent.");

}
catch (Exception e)
{
throw e;
}
finally
{
stream.Close();
}
}
Article:http://furuknap.blogspot.com/2008/07/send-sharepoint-document-library-file.html

0 comments: