2

我编写了一个 C# .net 可执行文件,它通过 Outlook 交换服务器发送电子邮件。当我手动运行它时一切正常,但是当我使用计划任务调用可执行文件时,它不会发送电子邮件。其他一切正常,但电子邮件没有发送。我将计划任务设置为作为我的用户帐户运行。当任务运行时,我可以在任务管理器中看到可执行文件正在我的用户名下运行。这排除了任何明显的权限问题。

在调试时,我让程序将一些文本输出到运行 Exchange 的同一台机器上的网络共享文件中。这个文件输出很好,所以我知道程序可以连接到那台机器。

任何人都可以帮忙吗?

4

1 回答 1

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");
于 2013-05-17T22:05:34.733 回答