在 ASP.NET Core 中使用 mailgun 服务和 MailKit 发送电子邮件时出现 SMTP 服务器意外断开连接错误

问题描述 投票:0回答:1

我在 ASP.NET Core 应用程序中尝试使用 MailKit 库发送电子邮件时遇到问题。电子邮件在我的本地计算机上成功发送,但是当我将应用程序部署到远程服务器(IIS)时,遇到以下异常:

异常:发送电子邮件失败:SMTP 服务器意外断开连接。 电子邮件发送者类:

using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.Extensions.Options;
using MimeKit;
using MimeKit.Text;
using System;
using System.Threading.Tasks;
using MailKit.Security;

namespace syngri_web_app.Services
{
    public class EmailSender : IEmailSender
    {
        private readonly MailgunSettings _mailgunSettings;

        public EmailSender(IOptions<MailgunSettings> mailgunSettings)
        {
            _mailgunSettings = mailgunSettings.Value;
        }

        public async Task SendEmailAsync(string email, string subject, string htmlMessage)
        {
            try
            {
                var mimeMessage = new MimeMessage();
                mimeMessage.From.Add(new MailboxAddress("Excited Admin", "foo@" + _mailgunSettings.Domain));
                mimeMessage.To.Add(new MailboxAddress("Excited User", email));
                mimeMessage.Subject = subject;
                mimeMessage.Body = new TextPart(TextFormat.Html)
                {
                    Text = htmlMessage
                };

                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    await client.ConnectAsync("smtp.mailgun.org", 587, SecureSocketOptions.StartTls);
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    await client.AuthenticateAsync("postmaster@"+_mailgunSettings.Domain+"", _mailgunSettings.ApiKey);

                    await client.SendAsync(mimeMessage);
                    await client.DisconnectAsync(true);
                }
            }
            catch (Exception ex)
            {
                // Log the exception details
                Console.WriteLine("An exception occurred while sending the email: " + ex.ToString());
                if (ex.InnerException != null)
                {
                    Console.WriteLine("Inner Exception: " + ex.InnerException.ToString());
                }
                throw new Exception("Failed to send the email: " + ex.Message);
            }
        }
    }
}

控制器代码:

        [HttpPost]
        [AllowAnonymous]

        public async Task<IActionResult> Forget(UserDto request)
        {

            if (ModelState.IsValid)
            {
                var user = await userManager.FindByEmailAsync(request.Email);
                if (user != null && !user.EmailConfirmed)
                {
                    ModelState.AddModelError("message", "Email not confirmed yet");
                    ItoastNotification.Error("Something went Wrong");
                    return View(request);

                }
                if (user == null) {
                    ModelState.AddModelError("message", "Email not Exist");
                    ItoastNotification.Error("Something went Wrong, Please inter valid email");
                    return View(request);
                }
                var code = await userManager.GeneratePasswordResetTokenAsync(user);
                code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                var callbackUrl = Url.Action(
                    "ResetPassword",
                    "Account",
                    new { area = "", code, request.Email },
                    protocol: Request.Scheme
                );
                var emailMessage = $"Please reset your password by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.";
                await emailSender.SendEmailAsync(request.Email, "Reset Password", emailMessage);

                ItoastNotification.Success("Reset Email Has been Sent Please Check your Email");
                return RedirectToAction("Login");
            }
            foreach (var error in ModelState.Values.SelectMany(v => v.Errors))
            {
                // Handle or log the validation error messages
                var errorMessage = error.ErrorMessage;
                ItoastNotification.Error("Something went Wrong: "+errorMessage);
                break;
            }
            
            return View(request);
        }

我已验证 SMTP 服务器设置是否正确,并且电子邮件已成功从我的本地计算机发送。但是,只有在部署到远程服务器时才会出现此问题。

c# asp.net asp.net-core smtp mailgun
1个回答
0
投票

我通过使用以下代码更新我的 emailSender 类解决了我的问题:

var smtpClient = new SmtpClient("smtp.mailgun.org")
{
    Port = 587,
    Credentials = new NetworkCredential(_mailgunSettings.UserName, _mailgunSettings.Password),
    EnableSsl = false
};

var mailMessage = new MailMessage
{
    From = new MailAddress("[email protected]"),
    Subject = subject,
    Body = formattedHtmlMessage,
    IsBodyHtml = true
};

mailMessage.To.Add(email);

await smtpClient.SendMailAsync(mailMessage);
© www.soinside.com 2019 - 2024. All rights reserved.