Blog Archives

Build and Send email method to SharePoint – Using Outgoing SMTP Configuration on Central Administration.

To create and Send emails on sharepoint programmatically you can use the following code, but first you need configure the following things:

  • Configure SMTP on server.
  • Configure Outgoing E-Mail on Central Admininstration

(Central Administration > System Settings > Configure outgoing e-mail settings)

  • Oubound SMTP server is server’s IP.

Code:

StringBuilder body = new StringBuilder();
body.Append("TEXT OF BODY EMAIL"); // TextBox
string subjectEmail = "SUBJECT OF EMAIL"; // TextBox
string senderTo = "fcsharepoint@outlook.com"; //TextBox

SendEmail(senderTo, subjectEmail, body);

Method:

 public bool SendEmail(string sTo, string sSubject, StringBuilder sBody)
 {
  // Email header
  StringBuilder sHeader = new StringBuilder();
  sHeader.Append("<html>");
  sHeader.Append("<body>");

  // Email footer
  StringBuilder sFooter = new StringBuilder();
  sFooter.Append("</body>");
  sFooter.Append("</html>");

  string htmlBody = sHeader.ToString() + sBody.ToString() + sFooter.ToString();

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

 // Add the alternate views instead of using MailMessage.Body
  MailMessage m = new MailMessage();
  m.From = new MailAddress(smtpFrom);
  m.To.Add(new MailAddress(sTo));
  m.Subject = sSubject.ToString();
  m.Body = htmlBody;
  m.IsBodyHtml = true;

 SmtpClient client = new SmtpClient(smtpServer);

 try
 {
   client.Send(m);
   return true;
 }
  catch (Exception) { }
  return false;
}