我编写了一个C#.net可执行文件,它通过Outlook Exchange服务器发送电子邮件。我手动运行时一切正常,但当我使用计划任务调用可执行文件时,它不会发送电子邮件。其他一切正常,但电子邮件不会被发送。我将计划任务设置为以我的用户帐户运行。当任务正在运行时,我可以在任务管理器中看到可执行文件在我的用户名下运行。这排除了任何明显的权限问题。
在调试时,我让程序将一些文本输出到运行Exchange的同一台机器上的网络共享上的文件中。这个文件输出正常,所以我知道程序可以连接到那台机器。
有人可以帮忙吗?
答案 0 :(得分:1)
好的,正如您在上面看到的那样,我试图通过正在运行的Outlook实例发送邮件。虽然我没有在评论框中发布代码而没有拉我的头发@amitapollo给了我使用System.Net.Mail命名空间的线索。在一天结束时,我开始工作了。这是我的代码:
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient("myExchangeServerIPAddress");
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential("myDomain\\myUsername", "myPassword");
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
System.Security.Cryptography.X509Certificates.X509Store xStore = new System.Security.Cryptography.X509Certificates.X509Store();
System.Security.Cryptography.X509Certificates.OpenFlags xFlag = System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly;
xStore.Open(xFlag);
System.Security.Cryptography.X509Certificates.X509Certificate2Collection xCertCollection = xStore.Certificates;
System.Security.Cryptography.X509Certificates.X509Certificate xCert = new System.Security.Cryptography.X509Certificates.X509Certificate();
foreach (System.Security.Cryptography.X509Certificates.X509Certificate _Cert in xCertCollection)
{
if (_Cert.Subject.Contains("myUsername@myDomain.com"))
{
xCert = _Cert;
}
}
smtpClient.ClientCertificates.Add(xCert);
//I was having problems with the remote certificate no being validated so I had to override all security settings with this line of code...
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object s, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; };
smtpClient.Send("myUsername@myDomain.com", "myUsername@myDomain.com", "mySubject", "myBody");