我编写了一个代码来运行一个计时器作业,该作业在月初运行,通过电子邮件通知用户访问该站点。
下面是执行方法的代码:
public override void Execute(Guid targetInstanceId)
{
SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://server"));
string smtpServerName = string.Empty;
string from = string.Empty;
//setting the website from where the timer job will run
SPWeb web = webApp.Sites[0].RootWeb;
//retrieving from address from the central admin site
from = web.Site.WebApplication.OutboundMailSenderAddress;
//retreiving smtpservername from the central admin site
smtpServerName = web.Site.WebApplication.OutboundMailServiceInstance.Server.Address;
//retreiving the groups in the website
SPGroupCollection collGroups = web.SiteGroups;
//logic to send mail to all users in all groups
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(from);
string to = string.Empty;
foreach (SPGroup group in collGroups)
{
foreach (SPUser user in group.Users)
{
//bool flg1 = user.Email == null;
if (user.Email != null)
{
//mailMessage.To.Add(user.Email);
to = user.Email + ",";
}
}
}
mailMessage.Subject = "Acknowledgement Mail";
mailMessage.To.Add(to);
mailMessage.Body = "Sup yo";
mailMessage.IsBodyHtml = false;
SmtpClient client = new SmtpClient(smtpServerName);
client.UseDefaultCredentials = true;
client.Port = 25;
client.EnableSsl = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
client.Send(mailMessage);
}
catch (SmtpException)
{
return;
}
catch (ArgumentNullException)
{
return;
}
}
现在只是为了测试目的,我在一小时内每 5 分钟运行一次这个计时器作业。现在,假设组中有 2 个用户的电子邮件地址为 a@abc 和 b@abc。我希望使用“收件人”地址发送电子邮件,a@abc; b@abc;
并且我正在使用它smtp4dev
来传递消息。我看到的是计时器作业在 5 分钟内运行了两次,并发送了 3 条消息,第一个是给 a,第二个是给 a 和 b,第三个是给 a,b,然后是 a。如何让它只运行一次,无论持续时间如何,只发送一条消息,并且在“To”地址中只发送 a;b?
编辑:更改代码后,我忘记重新启动计时器服务。它现在可以工作,但是计时器作业在预定的时间间隔内运行多次,而不是只运行一次。对此有什么建议吗?抱歉搞砸了!