Testing SMTP server is running via C#(测试 SMTP 服务器正在通过 C# 运行)
问题描述
如何在不发送消息的情况下通过 C# 测试 SMTP 是否启动并运行.
How can I test SMTP is up and running via C# without sending a message.
我当然可以试试:
try{
// send email to "nonsense@example.com"
}
catch
{
// log "smtp is down"
}
必须有一个更整洁的方法来做到这一点.
There must be a more tidy way to do this.
推荐答案
你可以试试对您的服务器说 EHLO 并查看它是否以 250 OK 响应.当然这个测试并不能保证你以后一定能成功发送邮件,但这是一个很好的迹象.
You can try saying EHLO to your server and see if it responds with 250 OK. Of course this test doesn't guarantee you that you will succeed sending the mail later, but it is a good indication.
这是一个示例:
class Program
{
    static void Main(string[] args)
    {
        using (var client = new TcpClient())
        {
            var server = "smtp.gmail.com";
            var port = 465;
            client.Connect(server, port);
            // As GMail requires SSL we should use SslStream
            // If your SMTP server doesn't support SSL you can
            // work directly with the underlying stream
            using (var stream = client.GetStream())
            using (var sslStream = new SslStream(stream))
            {
                sslStream.AuthenticateAsClient(server);
                using (var writer = new StreamWriter(sslStream))
                using (var reader = new StreamReader(sslStream))
                {
                    writer.WriteLine("EHLO " + server);
                    writer.Flush();
                    Console.WriteLine(reader.ReadLine());
                    // GMail responds with: 220 mx.google.com ESMTP
                }
            }
        }
    }
}
这是代码列表期待.
这篇关于测试 SMTP 服务器正在通过 C# 运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:测试 SMTP 服务器正在通过 C# 运行
				
        
 
            
        基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
 - 首先创建代码,多对多,关联表中的附加字段 2022-01-01
 - 错误“此流不支持搜索操作"在 C# 中 2022-01-01
 - 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
 - JSON.NET 中基于属性的类型解析 2022-01-01
 - 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
 - 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
 - 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
 - 如何动态获取文本框中datagridview列的总和 2022-01-01
 - 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				