Sunday, April 22, 2012

Sending e-mail with attachments from SharePoint

Sending email is a key function of enterprises solutions. Inside SharePoint collaboration environment you always need to send email with the required attachments. This can be used in some cases like once your document is approved / updated then through workflow we can send it to all the associated users.

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.

You can easily use the following specified methods to send email with attachment.


       I.            Method 1

Here we are going to use “System.Net.Mail” classes to send a message. Instead of hard coding the SMTP information into the code, we are going to use the SMTP settings that are configured with the SharePoint Central Administration. These settings are found in the “SPAdministrationWebApplication” class.
Below is a brief example on how you can send the mail with attachment from code. If you prefer to use the user’s e-mail address instead of the configured SMTP user you can retrieve it with SPControl.GetContextWeb(Context).CurrentUser.Email.

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

            //Create the mail message and supply it with from and to info
            MailMessage objMailMessage = new MailMessage(strSmtpFrom,"");

            //Set the subject and body of the message
            objMailMessage.Subject = "Subject: Testing Sending mail with attachment";
            objMailMessage.Body = "This is Test Mail with a attachment";
            //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(insert_ attachment_url);

           //Dump the byte array in a memory stream because
           //we can write it to our attachment
            MemoryStream memoryStreamOfFile = new MemoryStream(data);
    //Add the attachment
           objMailMessage.Attachments.Add(new System.Net.Mail.Attachment(memoryStreamOfFile, insert_Filenamefor_attachment, insert_content_type));

            //Create the SMTP client object and send the message
            SmtpClient objSmtpClient = new SmtpClient(strSmtpServer);

     II.            Method 2

    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(""));
    message.IsBodyHtml = true;

   //Set the subject and body of the message
    message.Body = "Hi there, check out the attachment";
    message.Subject = "Sent Attachment";

      using (SPWeb web = SPContext.Current.Web)
//Get the Document Library from where you want to sed the attachment
          SPList splDataSpringsLibrary = web.Lists["MyDocuments"];

            //Get the Url of the file to be sent as an attachment
          string strUrl = "http://ocs-wks-029:2323/MyDocuments/Configuring Database Mial  SQL server 2008.doc";
          //Get the file to be sent as an attachment
SPFile file = splDataSpringsLibrary.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);.




Send Email from SharePoint - SPUtility.SendEmail

Sending email is a key function of enterprises solutions. Inside SharePoint collaboration environment you always need to send email from within SharePoint. For this purpose you can use SPUtility class SendEmail method.

Did you ever need to send an email out, from your SharePoint custom web application? When you have such a task, perhaps the first idea that you have is to use System.Net.Mailnamespace. However, this requires that your application maintains a setting for the SMTP server, reply address and etc.
If you want the task of storing this configuration to SharePoint (and its Administrator) and instead, just focus on sending out the actual email then the solution is the Microsoft.SharePoint.Utilities.SPUtilityclass! It has the very convenient method 'SendEmail'. This is basically SharePoint's native functionality for email delivery.

The first thing you (or the SharePoint Administrator) need to do is setup the Outgoing email SMTP server. Open Central Admin àSystem SettingsàConfigure Outgoing Email
There, you need to set the Outbound SMTP server, From address and Reply-to address.
Now, you actually send email from your code as follows:
First, it is always a good idea to check if the email server is set:
bool blnIsEmailServerSet = SPUtility.IsEmailServerSet(web);

If this returns false, you should not bother trying to send the email. Instead, show an error message or notify the SharePoint administrator, to check the settings of the server. If it returns true, you are good to go:
SPWeb web = SPContext.Current.Web;
bool appendHtmlTag = false;
bool htmlEncode = false;
string toAddress = "";
string subject = "Subject";
string message = "Message text";
bool result = SPUtility.SendEmail(web, appendHtmlTag, htmlEncode, toAddress, subject, message);

In some cases, you may need to run this code with elevated privileges:
bool result = SPUtility.SendEmail(web, appendHtmlTag, htmlEncode, toAddress, subject, message);
SendEmail method returns a boolean, indicating if sending the email was successful or not.

As you can see that sending email using SPUtility is straightforward, please also note the following considerations
1.   No attachment allowed
2.   Message body size cannot exceed 2048 characters.
3.   The from address will be the “Outbound Sender Address” configured in the central admin.