我在C#中编写了一个小的命令行实用程序,该实用程序通过采取的措施发送电子邮件。从命令行手动运行时,电子邮件已成功发送,但作为计划任务运行时,则电子邮件未发送。我将其设置为以最高用户设置作为计划任务运行。没有防火墙设置可以阻止测试计算机上的传出电子邮件。
计划任务是否以受限制发送电子邮件的用户身份运行?我不确定是否有任何代码可以使用C#发送电子邮件并将邮件程序设置为管理员。
谢谢。
这是我用于发送电子邮件的C#代码:
public static void SendNotifications ()
{
string smtpServer = "mailserver.com";
string smtpUser = "[email protected]";
string smtpPassword = "abc123";
// Set the variables for the mail object.
using (MailMessage Email = new MailMessage ())
{
Email.IsBodyHtml = true;
Email.From = new MailAddress (smtpUser);
Email.To.Add ("[email protected]");
Email.CC.Add ("[email protected]");
Email.Subject = "Subject";
Email.Body = @"Here is a notification.";
SmtpClient smtp = new SmtpClient (smtpServer);
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential (smtpUser, smtpPassword);
smtp.UseDefaultCredentials = false;
smtp.Credentials = SMTPUserInfo;
try
{
// Send the mail.
smtp.Send (Email);
} // try
catch (Exception ex)
{
// ignore error message
} // catch (Exception e)
} // using (MailMessage Email = new MailMessage ())
}
假设您正在通过任务计划程序运行控制台应用程序,则可以将运行计划程序的用户更改为有权发送电子邮件的用户。如果您在代码中使用DefaultCredentials = true,那么这尤其重要。
通常,这是通过创建具有足够权限来执行手头任务的服务帐户来完成的,仅此而已。可以在“任务计划程序”中所讨论任务的“常规”选项卡上配置哪个用户帐户将执行该任务。将有一个“更改用户”按钮。确保选中“运行用户是否已登录”。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句