3

Hi I used following code to send mail from Timer job, (Thanks to Mr Deepu for providing a sample template). After deploying it, I could able to find this job, in the monitoring section of the Central Admin. I did able to change the start and end time. And run the Job manually, however though the job shows that it run successfully, I did not get any mail.

Also is there any way I can just debug each step?

public override void Execute(Guid contentDbId)
        {


            string SiteListURL = "http://sok:123/Lists/Live/";
            using (SPSite oSPSite = new SPSite(SiteListURL))
            using (SPWeb oSPWeb = oSPSite.OpenWeb())                
            {

                string emailTo;
                MailInfo oMailInfo = new MailInfo(); // Where Mail Info is a class to send the Email
                string EmailHtmlBody;

                MailNotifier oMailNotifier = new MailNotifier("IP Address");//Give IP address
                emailTo = "[email protected]";

                if (!string.IsNullOrEmpty(emailTo) && emailTo != null)
                {
                    EmailHtmlBody = "The Opportunity ";


                    oMailInfo.EMailTo = emailTo;

                    oMailInfo.MailFrom = "[email protected]";
                    oMailInfo.Subject = "Closure Expiry Alert";
                    oMailInfo.MailBody = EmailHtmlBody;

                    oMailNotifier.SendMail(oMailInfo); // Please find the SendMail function in the below class MailNotifier !!
                }                        


            }

        }

The below Class is for Email configuration and sending it.

public struct MailInfo
    {
        public string MailBody;
        public string EMailToCC;
        public string EMailTo;
        public string MailFrom;
        public string Subject;
    }

    public class MailNotifier
    {
        private string _SMTPServerName;

        public MailNotifier(string SMTPServerName)
        {
            if (string.IsNullOrEmpty(SMTPServerName))
                throw new NullReferenceException("SMTPServerName NULL");

            _SMTPServerName = SMTPServerName;
        }

        public bool SendMail(MailInfo oMailInfo)
        {
            System.Net.Mail.SmtpClient osmtp;
            System.Net.Mail.MailMessage Mail;
            bool Result = false;


            try
            {
                    Mail = new System.Net.Mail.MailMessage();
                    Mail.To.Add(oMailInfo.EMailTo);
                    Mail.CC.Add(oMailInfo.EMailToCC);
                    Mail.From = new System.Net.Mail.MailAddress(oMailInfo.MailFrom);
                    Mail.Body = oMailInfo.MailBody;
                    osmtp = new System.Net.Mail.SmtpClient(_SMTPServerName);
                    Mail.IsBodyHtml = true;
                    Mail.Subject = oMailInfo.Subject;
                    osmtp.Send(Mail);
                    Mail = null;
                    osmtp = null;
                    Result = true;
            }
            catch
            {
                Result = false;
            }
            finally
            {
                Mail = null;
                osmtp = null;
            }

            return Result;

        }
    }

UPDATE: I tried with KAI's example, Even that is not sending any mail, Outgoing mail is formatted correctly and it is sending out mails!! I could able to see the Timer job from Farm and also I could able to see the last run time, and I even tried manual run.... No mails are sending!!

Simplified Code..

public class EMailAlertJob : SPJobDefinition
    {
        public const string EMAIL_ALERT_JOB_NAME = "Closure Date";
        SPWebApplication _webApplication;
        SPContentDatabase _contentDb;

        public EMailAlertJob()
            : base()
        {
            this.Title = EMAIL_ALERT_JOB_NAME;
        }

        public EMailAlertJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)
            : base(jobName, service, server, targetType)
        {
            this.Title = EMAIL_ALERT_JOB_NAME;

        }


        public EMailAlertJob(string jobName, SPWebApplication webApplication)
            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
        {
            this.Title = EMAIL_ALERT_JOB_NAME;
        }


        public override void Execute(Guid contentDbId)
        {


            SPListItemCollection CampaignsToBeNotified = null;
            string SiteListURL = "http://sok:1111/Lists/ListName/";

            using (SPSite oSPSite = new SPSite(SiteListURL))
     {
            using (SPWeb oSPWeb = oSPSite.OpenWeb())
            {
                var headers = new StringDictionary();
                headers.Add("subject", "Hi!");
                // "text/html" to send rich html text in message body
                headers.Add("content-type", "text/html");
                headers.Add("to", "[email protected]");
                SPUtility.SendEmail(oSPWeb, headers, "<b>Hi there!</b>");

            }
    }
        }

2 Answers 2

8

To debug timer job you need to attach to SharePoint Timer process (after each code deployment you also need restart this service to make sure that it picks up your recent code updates, you can restart it using command prompt - net stop SPTimerV4 and net start SPTimerV4)

About sending mail - make sure that your mail server configured and working (write a sample console app to test it), also you can try using standard sharepoint method for sending emails - SPUtility.SendEmail. Sample of using it:

var headers = new StringDictionary();
headers.Add("subject", "Hi!");
// "text/html" to send rich html text in message body
headers.Add("content-type", "text/html");
headers.Add("to", "[email protected]");
SPUtility.SendEmail(web, headers, "<b>Hi there!</b>");

To use SPUtility.SendEmail you need "Configure outgoing e-mail settings" (under System Settings) in central admin (setup correct Outbound SMTP server address).

7
  • HI Kai I did try creating ur code, however I did not able to use SPUtility from Console, I did not get anything to Resolve as well.... Again I used the above code to check the Timer Job. Nothing happened. I have set outgoing mail in the farm level, hope that we do not have separate mail setting for each Site collection.
    – Jithu
    Dec 30, 2011 at 8:03
  • Why did you not able to use SPUtility.SendEmail? May be exception is thrown? If your mail server and sharepoint settings configured correctly, code above should work. Dec 30, 2011 at 8:21
  • Try to create a webpart and implement the above code...
    – Strider
    Dec 30, 2011 at 8:26
  • Easy and quickly way to check if your sharepoint mail system working is to add yourself to a sharepoint group on some site (make sure "Send welcome e-mail to the new users" checkbox is checked). If all correct, you receive message, if not, an error will appear ("The user or users have been added successfully, but there was an error in sending the e-mail message....") Dec 30, 2011 at 8:39
  • Yes Kai, That is working great!! My site is able to send welcome messages using my email address, which I configured for outgoing mail!! Now only problem is my timer job is not doing so...
    – Jithu
    Dec 30, 2011 at 8:46
3
+50

Can you try debugging the solution? Add a Debugger.break() statement in your code where you need to debug. Deploy the timer job solution to the farm again and when you run the timer job, there will be a debugger window poping up to select your visual studio solution. Select your solution and within few seconds, it will start debugging.

Try debugging and find the statement where the problem exist.

Good luck.

9
  • It did not hit, Execute method!!
    – Jithu
    Jan 3, 2012 at 7:20
  • Do you reset timer process after you deployed your dll into GAC? You must to do it each time when you deploy your dll. Jan 3, 2012 at 7:45
  • As Kai suggested, do a restart on timer service after deployment. Did it work then?
    – Deepu Nair
    Jan 3, 2012 at 9:10
  • Since I am doing it from vs 2010. I directly right click the project and deploy. I believe the deploying of dll will do automatically!!
    – Jithu
    Jan 3, 2012 at 10:23
  • yes your deploy from VS will move the dll automatically. But after that, go to Administrative tools -> Services -> SharePoint Timer Job service -> Restart the timer job and then run the timer job manually. It should fire the debugger.
    – Deepu Nair
    Jan 3, 2012 at 10:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.