Wednesday, July 18, 2012

Ways of sending mails in Sharepoint through code (for farm solutions only).

There are two ways of sending mail through code in sharepoint sites. One Through SPUtility Class of Microsoft.Sharepoint and another for SmtpClient Class of System.Net.Mail namespace. Both call its own function of Send mail and uses same parameters. But the main difference I found between them is if you want to send mail with attachments you don't have any parameter in SPUtility  class for the purpose however in SmtpClient you can. I am citing here an example of both.

Through SPUtility Class :

 public void SendMail(Guid objSPSiteId)      
{
 using (SPSite objSPSite = new SPSite(objSPSiteId))
            {
                using (objSPWeb = objSPSite.AllWebs[properties.OpenWeb().ID])
                {
                    SPUtility.SendEmail(objSPWeb, true, true, "abc@xyz.com", "Demo Mail for test.", "Abc");
                }
            }
}

You also need to configure Web Application Outgoing E-Mail Settings for that particular Web Application in which your site is hosted. Here fill all text boxes with details. This is needed in both the cases.

Through SmtpClient Class :


 public void SendMail(Guid objSPSiteId)      

 {
            using (SPSite objSPSite = new SPSite(objSPSiteId))
            {
                using (objSPWeb = objSPSite.AllWebs[properties.OpenWeb().ID])
                {
                    //SPUtility.SendEmail(objSPWeb, true, true, "abc@xyz.com", "Demo Mail for test through event receiver Adding event.", "Abc");
                    string smtpServer = objSPSite.WebApplication.OutboundMailServiceInstance.Server.Address;
                    string smtpFrom = objSPSite.WebApplication.OutboundMailSenderAddress;
                    MailMessage mailMessage = new MailMessage(smtpFrom, "def@mno.com");
                    mailMessage.Body = "Demo Body for the mail..";
                    mailMessage.Subject = "Demo Subject for the mail..";
                    SmtpClient objSmtpClient = new SmtpClient();
                    objSmtpClient.Send(mailMessage);
                }
           }
  }

We need to do these entry in web.config :

<system.net>
    <!--<defaultProxy />-->
    <mailSettings>
      <smtp from="def@mno.com">
        <network host="localhost"/>(I have put these).
      </smtp>
    </mailSettings>
  </system.net>

There are following steps need to follow when need to send with an list items attachments:

1.) First get all the attechments attached to particular list item :

 SPList mylist = SPContext.Current.List;
                    SPListItem myitem =  SPContext.Current.ListItem;
                    SPAttachmentCollection myattach = myitem.Attachments;
                    if (myattach.Count != 0)
                    {
                        objSPWeb.AllowUnsafeUpdates = false;
                        List<SPFile> lstSPFile = null;
                        SPSecurity.RunWithElevatedPrivileges(delegate
                        {
                            using (SPSite oSite = new SPSite(myitem.ParentList.ParentWeb.Site.ID))
                            {
                                using (SPWeb oWeb = oSite.OpenWeb(myitem.ParentList.ParentWeb.ID))
                                {
                                    SPFolder folder = myitem.ParentList.RootFolder.SubFolders["Attachments"].SubFolders                                               [myitem.ID.ToString()];
                                    lstSPFile = new List<SPFile>();
                                    foreach (SPFile file in folder.Files)
                                    {
                                        lstSPFile.Add(file);
                                    }
                                    _fileList = lstSPFile;
                                }
                            }
                        });

2.) Now get attachments in byte format and then add it into the MailMessage Class Object.

foreach (var file in _fileList)
                        {
                            WebClient webClient = new WebClient();//Supply the WebClient with the network credentials of our user
                            webClient.Credentials = CredentialCache.DefaultNetworkCredentials;
                            string mypath = objSPWeb.Url + "/Lists/" + mylist.Title + "/Attachments/"+ myitem.ID +"/"+ file.Name;                             //Download the byte array of the file
                            byte[] data = webClient.DownloadData(mypath);
                            MemoryStream memoryStreamOfFile = new MemoryStream(data);
                            mailMessage.Attachments.Add(new System.Net.Mail.Attachment(memoryStreamOfFile, file.Name.ToString()));
                        }

In this way you can send mail through Sharepoint site by calling these function on any particular event.

No comments:

Post a Comment