使用 .NET 核心 2.2 中的 MailKit SMTP 客户端使用 Gmail SMTP 发送邮件对我不起作用

Get*_*ons 7 .net smtp mailkit .net-core asp.net-core

我正在使用 NLog 目标来使用 smtp.google.com:587 SMTP 服务器将日志发送到一些电子邮件。当我使用标准 System.Net.Mail.SmtpClient 库时,它可以正常工作,但是在使用 MailKit 时,它会抛出错误:

发送邮件时出错。异常:>System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (10061): 无法建立连接,因为目标机器主动拒绝它。>[::ffff:173.194.76.108]:587

我添加了一个带有两个控制台项目的解决方案。一种使用 MailKit 和其他 System.Net.Mail。所有设置参数看起来都一样,但它在 MailKit 中不起作用:

using System;
using System.Diagnostics;
using MailKit.Net.Smtp;
using MailKit;
using MailKit.Security;
using MimeKit;

namespace SendMailKit
{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Create message");
            var message = new MimeMessage();
            message.From.Add(new MailboxAddress("GTS", "tfs.gettaxsolutions@gmail.com"));
            message.To.Add(new MailboxAddress("Me", "info@gettaxsolutions.com"));
            message.Subject = "Test mail";
            message.Body = new TextPart("plain")
            {
                Text = @"Hello, This is the test"
            };

            Console.WriteLine("Create SMTP client");
            using (var client = new SmtpClient())
            {
                // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                Console.WriteLine("Connect");
                **client.Connect("smtp.gmail.com", 587, true);**
                Console.WriteLine("Authenticate");
                client.Authenticate("tfs.gettaxsolutions", "*********");
                client.Connected += Client_Connected;
                client.Disconnected += Client_Disconnected;
                client.Authenticated += Client_Authenticated;
                client.MessageSent += Client_MessageSent;
                Console.WriteLine("Send Message");
                client.Send(message);
                Console.WriteLine("Disconnect");
                client.Disconnect(true);
            }

            Console.ReadLine();
        }

        private static void Client_MessageSent(object sender, MessageSentEventArgs e)
        {
            Console.WriteLine("MessageSent");
        }

        private static void Client_Authenticated(object sender, AuthenticatedEventArgs e)
        {
            Console.WriteLine("Authenticated");
        }

        private static void Client_Disconnected(object sender, DisconnectedEventArgs e)
        {
            Console.WriteLine("Disconnected");
        }

        private static void Client_Connected(object sender, ConnectedEventArgs e)
        {
            Console.WriteLine("Connected");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这会在 NLog 中抛出与此相同的异常。例外是在 client.Connect("smtp.gmail.com", 587, true); 所以问题出在 MailKit 连接上。在其他使用 System.Net.Mail 的项目中,一切正常,邮件发送成功。我在同一台机器上启动它们,相同的环境只是改变控制台应用程序的启动点来测试(所以连接不是问题):

using System;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.ComponentModel;
namespace SendSimpleMail
{
    public class Program
    {
        static bool mailSent = false;
        private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            // Get the unique identifier for this asynchronous operation.
            String token = (string)e.UserState;

            if (e.Cancelled)
            {
                Console.WriteLine("[{0}] Send canceled.", token);
            }
            if (e.Error != null)
            {
                Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
            }
            else
            {
                Console.WriteLine("Message sent.");
            }
            mailSent = true;
        }
        public static void Main()
        {
            // Command-line argument must be the SMTP host.
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            client.EnableSsl = true;
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential("tfs.gettaxsolutions", "***********");
            // Specify the email sender.
            // Create a mailing address that includes a UTF8 character
            // in the display name.
            MailAddress from = new MailAddress("tfs.gettaxsolutions@gmail.com", "GTS");
            // Set destinations for the email message.
            MailAddress to = new MailAddress("info@gettaxsolutions.com", "Me");
            // Specify the message content.
            MailMessage message = new MailMessage(from, to);
            message.Body = "This is a test email message sent by an application. ";
            // Include some non-ASCII characters in body and subject.
            string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' });
            message.Body += Environment.NewLine + someArrows;
            message.BodyEncoding = System.Text.Encoding.UTF8;
            message.Subject = "test message 1" + someArrows;
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            // Set the method that is called back when the send operation ends.
            client.SendCompleted += new
            SendCompletedEventHandler(SendCompletedCallback);
            // The userState can be any object that allows your callback 
            // method to identify this send operation.
            // For this example, the userToken is a string constant.
            string userState = "test message1";
            client.SendAsync(message, userState);
            Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
            string answer = Console.ReadLine();
            // If the user canceled the send, and mail hasn't been sent yet,
            // then cancel the pending operation.
            if (answer.StartsWith("c") && mailSent == false)
            {
                client.SendAsyncCancel();
            }
            // Clean up.
            message.Dispose();
            Console.WriteLine("Goodbye.");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我找不到 MailKit 的问题所在。设置看起来相同。你知道什么是问题吗?这是错误还是我的设置有问题?

MailKit 必须成功发送电子邮件

ASP.NET 核心 2.2、MailKit 2.1.3

小智 3

就在几分钟前,我刚刚部分解决了一个非常相似的问题;我学到的可能对你有帮助。

在我的例子中,MailKit 有可靠的工作代码可以从目标为 NET Core 2.1 的应用程序发送。

最近我更新了所有 Nuget 包,认为这样做是一个很好的做法。然后我后来发现我正在工作的 SMTP 发送代码突然停止工作,并且报告了与您所经历的相同的错误。

带着这种情况我检查了smtp服务器、防火墙等各种问题,直到想起Nuget更新,开始尝试,最终将MailKit降级到2.0.0。MailKit 版本降级后,发送代码再次开始工作。

我还没有查明失败的确切位置和机制,但已经建立了一些信心(在我一直在研究的情况下)所使用的 MailKit 版本直接涉及其中。今天,它已恢复处理 MailKit 2.0.0 降级,并且需要进行更多研究才能超越该状态。