Wednesday, November 25, 2009

send an e-mail with attachment from SharePoint

One of the ways to send an e-mail from SharePoint as developer, is to make use of the “SPUtility.SendEmail” classes. But unfortunately I did not find any possibility to include an attachment with the help of these classes.

I have used SPAdministrationWebApplication for used shaerpoint email credential and send email with attachement through system.net class.


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using System.IO;
using Microsoft.SharePoint.Utilities;
using System.Net.Mail;
using Microsoft.SharePoint.Administration;
using System.Net;


//Get the Sharepoint SMTP information from the SPAdministrationWebApplication
string smtpServer = SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address;
string smtpFrom = SPAdministrationWebApplication.Local.OutboundMailSenderAddress;

//Create the mail message and supply it with from and to info
MailMessage mailMessage = new MailMessage(smtpFrom, smtpTo);

//Set the subject and body of the message
mailMessage.Subject = "Test";
mailMessage.Body = "test email .";

//Download the content of the file with a WebClient
WebClient webClient = new WebClient();


//Supply the WebClient with the network credentials of our user
webClient.Credentials = CredentialCache.DefaultNetworkCredentials;

//Download the byte array of the file
byte[] data = webClient.DownloadData(imagepath);

//Dump the byte array in a memory stream because
//we can write it to our attachment
MemoryStream memoryStreamOfFile = new MemoryStream(data);

//Add the attachment
//mailMessage.Attachments.Add(new System.Net.Mail.Attachment(memoryStreamOfFile, insert_filename_attachment, insert_content_type));
mailMessage.Attachments.Add(new System.Net.Mail.Attachment(memoryStreamOfFile, ImageName));
//, insert_content_type));


//Create the SMTP client object and send the message
SmtpClient smtpClient = new SmtpClient(smtpServer);
smtpClient.Host = "hostname";

//Delivery mothod which get attachement which size is more than 1 MB and immediately send email to user
smtpClient.Port = 2095;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtpClient.Send(mailMessage);



Hopy this stuff is useful for every developer.