4

我制作了这个控制台应用程序,它扫描文件夹中的文件并通过电子邮件将它们作为附件发送。它在我的本地机器上运行良好。但是当我尝试在另一台机器(测试服务器)上远程运行它时,它给了我一个例外。

这是我看到的例外。

 innerException  {System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions *******:25
       at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
       at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
       --- End of inner exception stack trace ---
       at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6)
       at System.Net.PooledStream.Activate(Object owningObject, Boolean async, GeneralAsyncDelegate asyncCallback)
       at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback)
       at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
       at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
       at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
       at System.Net.Mail.SmtpClient.GetConnection()
       at System.Net.Mail.SmtpClient.Send(MailMessage message)} System.Exception {System.Net.WebException}

我不确定为什么这会在我的本地机器上而不是在服务器上工作。那是因为服务器上没有设置outlook帐户吗?

这是我的应用程序中的邮件代码 -

public static void SendMailMessage(string file) 
{
    const string subject = "TESTING";
    const string body = "";

    string from = ConfigurationManager.AppSettings["from"];        
    string to = ConfigurationManager.AppSettings["to"];
    var message = new MailMessage(from, to, subject, body);
    message.Attachments.Add(new Attachment(file));
    var client = new SmtpClient("smtp.mail***.com")
    {
        DeliveryMethod = SmtpDeliveryMethod.Network,
        UseDefaultCredentials = true

    };

    try
    {
        client.Send(message);
        Console.WriteLine("Email Successfully sent!");

    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }
}
4

2 回答 2

4

* 请记住,我们需要添加网络凭据:

 SmtpClient client = new SmtpClient();
        client.Credentials = new    System.Net.NetworkCredential("jorgesys@gmail.com", "patito12");
        client.Port = 587;
        client.Host = "smtp.gmail.com";
        client.EnableSsl = true;
        client.Send(mail);

有时会出现错误:“无法连接到远程服务器”,因为服务器端口587被阻止。

于 2015-08-29T01:52:33.403 回答
2

问题是您在远程服务器上使用了默认凭据,而远程服务器拒绝了该凭据,因为在这种环境中无法访问默认凭据。试试这个它会工作。

 var client = new SmtpClient("smtp.mail***.com",port)
 {  
    NetworkCredentials = new NetworkCredentials("username","password")        
 };
 client.Send();
于 2013-10-23T13:44:16.960 回答