Send Email using Custom Timer Job in SharePoint 2013

Open your Visual Studio 2102.

Then select "File" -> "New" -> "Project..." then select Empty SharePoint Project.

add new project

Then click Office/SharePoint.

Then click SharePoint Solutions.

Then click SharePoint 2013 Empty Project.

Then set your server name where you want to deploy your solution and choose Deploy on Farm solution.

Deploy on farm solution

Then click Finish.

Then right-click on Solution Explorer (or press Ctrl+ ;).

Then add a new item.

add new item

Select code from the Installed Menu under Visual C# Items and click on Class.

Add class

Please use the following code.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using Microsoft.SharePoint.Administration;  
  6. using Microsoft.SharePoint;  
  7. using System.Net.Mail;  
  8.   
  9. namespace CustomTimerJob {  
  10.     public class Timer: Microsoft.SharePoint.Administration.SPJobDefinition {  
  11.         public Timer(): base() {}  
  12.         public Timer(string jobName, SPService service, SPServer server, SPJobLockType targetType): base(jobName, service, server, targetType) {}  
  13.         public Timer(string jobName, SPWebApplication webApplication): base(jobName, webApplication, null, SPJobLockType.ContentDatabase) {  
  14.             this.Title = "Email Notification Job";  
  15.         }  
  16.         public override void Execute(Guid contentDbId) {  
  17.             string from = string.Empty;  
  18.             string smtpAddress = string.Empty;  
  19.             string to = "rkswain@ubnsoft.com";  
  20.             string subject = "Email Notification";  
  21.             string body = "<h1> Email Sending from Testing My Timer Job Application </h1>";  
  22.             SPSecurity.RunWithElevatedPrivileges(delegate() {  
  23.                 // get a reference to the current site collection's content database   
  24.                 SPWebApplication webApplication = this.Parent as SPWebApplication;  
  25.                 SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];  
  26.   
  27.                 // get a reference to the "Tasks" list in the RootWeb of the first site collection in the content database   
  28.                 SPWeb rootWeb = contentDb.Sites[0].RootWeb;  
  29.   
  30.                 // Get the DB News Announcements List   
  31.                 SPList listjob = rootWeb.Lists.TryGetList("Tasks");  
  32.   
  33.                 // Get sender address from web application settings   
  34.                 from = rootWeb.Site.WebApplication.OutboundMailSenderAddress;  
  35.   
  36.                 // Get SMTP address from web application settings   
  37.                 smtpAddress = rootWeb.Site.WebApplication.OutboundMailServiceInstance.Server.Address;  
  38.   
  39.                 // Send an email if the news is approved   
  40.                 bool emailSent = SendMail(smtpAddress, subject, body, true, from, to, nullnull);  
  41.   
  42.                 if (listjob != null && emailSent) {  
  43.                     SPListItem newListItem = listjob.Items.Add();  
  44.                     newListItem["Title"] = string.Concat("Email Notification Sent at : ", DateTime.Now.ToString());  
  45.                     newListItem.Update();  
  46.                 }  
  47.             });  
  48.   
  49.         }  
  50.         public bool SendMail(string smtpAddress, string subject, string body, bool isBodyHtml, string from, string to, string cc, string bcc) {  
  51.             bool mailSent = false;  
  52.             SmtpClient smtpClient = null;  
  53.   
  54.             try {  
  55.                 // Assign SMTP address   
  56.                 smtpClient = new SmtpClient();  
  57.                 smtpClient.Host = smtpAddress;  
  58.   
  59.                 //Create an email message   
  60.                 MailMessage mailMessage = new MailMessage(from, to, subject, body);  
  61.                 if (!String.IsNullOrEmpty(cc)) {  
  62.                     MailAddress CCAddress = new MailAddress(cc);  
  63.                     mailMessage.CC.Add(CCAddress);  
  64.                 }  
  65.                 if (!String.IsNullOrEmpty(bcc)) {  
  66.                     MailAddress BCCAddress = new MailAddress(bcc);  
  67.                     mailMessage.Bcc.Add(BCCAddress);  
  68.                 }  
  69.                 mailMessage.IsBodyHtml = isBodyHtml;  
  70.   
  71.                 // Send the email   
  72.                 smtpClient.Send(mailMessage);  
  73.                 mailSent = true;  
  74.             } catch (Exception) {  
  75.                 mailSent = false;  
  76.             }  
  77.   
  78.             return mailSent;  
  79.         }  
  80.   
  81.   
  82.     }  
  83. }  
Then add a New Feature and change the Scope and rename it .

add a New Feature

Then create another class and copy this code.

We need to set the interval of our timer job application.
  1. using System;  
  2. using System.Runtime.InteropServices;  
  3. using System.Security.Permissions;  
  4. using Microsoft.SharePoint;  
  5. using Microsoft.SharePoint.Security;  
  6. using System.Linq;  
  7.   
  8. namespace CustomTimerJob.Features.NotificationTimerJobFeature {  
  9.   
  10.     public class EventReceiver: SPFeatureReceiver {  
  11.         // Name of the Timer Job, but not the Title which is displayed in central admin   
  12.         private  
  13.         const string List_JOB_NAME = "NotificationTimerJob";  
  14.   
  15.         // Uncomment the method below to handle the event raised after a feature has been activated.   
  16.   
  17.         public override void FeatureActivated(SPFeatureReceiverProperties properties) {  
  18.             SPSecurity.RunWithElevatedPrivileges(delegate() {  
  19.                 SPSite site = properties.Feature.Parent as SPSite;  
  20.   
  21.                 // make sure the job isn't already registered   
  22.                 site.WebApplication.JobDefinitions.Where(t => t.Name.Equals(List_JOB_NAME)).ToList().ForEach(j => j.Delete());  
  23.   
  24.                 // install the job   
  25.                 Timer listLoggerJob = new Timer(List_JOB_NAME, site.WebApplication);  
  26.                 SPMinuteSchedule schedule = new SPMinuteSchedule();  
  27.                 schedule.BeginSecond = 0;  
  28.                 schedule.EndSecond = 59;  
  29.                 schedule.Interval = 15;  
  30.                 listLoggerJob.Schedule = schedule;  
  31.                 listLoggerJob.Update();  
  32.             });  
  33.         }  
  34.   
  35.   
  36.         // Uncomment the method below to handle the event raised before a feature is deactivated.   
  37.   
  38.         public override void FeatureDeactivating(SPFeatureReceiverProperties properties) {  
  39.             SPSecurity.RunWithElevatedPrivileges(delegate() {  
  40.                 SPSite site = properties.Feature.Parent as SPSite;  
  41.   
  42.                 // delete the job   
  43.                 site.WebApplication.JobDefinitions.Where(t => t.Name.Equals(List_JOB_NAME)).ToList().ForEach(j => j.Delete());  
  44.             });  
  45.         }  
  46.   
  47.   
  48.         // Uncomment the method below to handle the event raised after a feature has been installed.   
  49.   
  50.         //public override void FeatureInstalled(SPFeatureReceiverProperties properties)   
  51.         //{   
  52.         //}   
  53.   
  54.   
  55.         // Uncomment the method below to handle the event raised before a feature is uninstalled.   
  56.   
  57.         //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)   
  58.         //{   
  59.         //}   
  60.   
  61.         // Uncomment the method below to handle the event raised when a feature is upgrading.   
  62.   
  63.         //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)   
  64.         //{   
  65.         //}   
  66.     }  
  67. }  
Then deploy the project.

deploy

After successful deployment go to your SharePoint central administrator.

Click on monitoring.

Click on monitoring
Then click Review job definition.

monitoring

Then go to your created timer job application.

It’s working successfully.