无法连接到远程服务器 C#
本文关键字:服务器 连接 | 更新日期: 2023-09-27 18:36:29
我制作了这个控制台应用程序,它可以扫描文件夹中的文件,并通过电子邮件将其作为附件发送。它在我的本地机器中工作正常。但是当我尝试在另一台机器(测试服务器)上远程运行它时,它给了我一个例外。
这是我看到的例外。
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);
}
}
* 请记住,我们需要添加网络凭据:
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
被阻止。
问题是您在远程上使用默认凭据,但被远程服务器拒绝,因为在此类环境中无法访问默认凭据。试试这个它会起作用。
var client = new SmtpClient("smtp.mail***.com",port)
{
NetworkCredentials = new NetworkCredentials("username","password")
};
client.Send();