Pages

Search This Blog

Tuesday, March 22, 2011

Send Mail through code in Sharepoint using SMTP Mail

Many a times, we need to build our own mail sending utility while working on SharePoint Projects. The requirement could be either to send a mail to document owner for any specific changes made to the document, sending error mails to administrator etc. We can use "SPUtility.SendEmailbut everyone is aware of its long length limitation of 2048 characters. So I tried using SmtpMail instead. In Below example I have instantiated an object of

SmtpMail which is derived from “System.Web.Mail” namespace. the main task while instanciating the SmtpMail object is to retrieve the “fromAddress” and “smtpServerAddress”. We can get these from the Web Application Context:

“WebApplication.OutboundMailSenderAddress”
“WebApplication.OutboundMailServiceInstance.Server.Address”


public static String SendMail(String strMessage, String siteUrl)
        {
            String strMailIds = String.Empty;
            String fromAddress, smtpServer;
            String strErrorMsg = String.Empty;
            System.Web.Mail.MailMessage objMailMsg;
            try
            {

            SPSecurity.RunWithElevatedPrivileges(delegate()
              {
                using (SPSite objSite = new SPSite(siteUrl))
                {
                  using (SPWeb PrevelegedWeb = objSite.OpenWeb())
                  {
                    strMailIds = "test@abc.com;test2@abc.com";
fromAddress = PrevelegedWeb.Site.WebApplication.OutboundMailSenderAddress;
smtpServer = revelegedWeb.Site.WebApplication.OutboundMailServiceInstance.Server.Address;
                    if (!(String.IsNullOrEmpty(fromAddress)
&& String.IsNullOrEmpty(smtpServer)))
                    {
                        MailMessage objMailMsg = new System.Web.Mail.MailMessage();
                        objMailMsg.From = fromAddress;
                        objMailMsg.To = strMailIds;
                        objMailMsg.Subject = "This is a test Mail";
                        objMailMsg.BodyFormat = MailFormat.Html;
                        objMailMsg.Body = strMessage;
                        SmtpMail.SmtpServer = smtpServer;
                        SmtpMail.Send(objMailMsg);
                    }
                    else
                    {
strErrorMsg = "There is an error in sending email
 because of server configuration. ";
                    }
                  }
                }
              });
            }
            catch (Exception Ex)
            {
                throw new Exception("An error has occured while sending mail", Ex);
            }
            return strErrorMsg;
        }







2 comments:

  1. TREMENDOUSLY helpful, and very well-written. Thank you so much! Saved the day for me my friend! :)

    -- Jon

    ReplyDelete