-1

The following error is returned during user registration. Frankly I think the problem is caused by netcore.mailkit. Or there may be a problem on the AutoMapper side. Because this is a code structure that I use often. The project is being developed on Netcore 5.0.

MissingMethodException: Method not found: 'Void MimeKit.MailboxAddress..ctor(System.String)'

Versions of mailkit and features:

  • Netcore.MailKit Version: 2.0.3
  • Microsoft.AspNetcore.Http.Features version: 5.0.9

here is the registration method:

 if (!ModelState.IsValid)
        {
            return View(userModel);
        }

        var user = _mapper.Map<User>(userModel);

        var result = await userManager.CreateAsync(user, userModel.Password);
        if (!result.Succeeded)
        {
            foreach (var error in result.Errors)
            {
                ModelState.TryAddModelError(error.Code, error.Description);
            }

            return View(userModel);
        }
        await userManager.AddToRoleAsync(user, "Customer");

        var token = await userManager.GenerateEmailConfirmationTokenAsync(user);
        var confirmationLink = Url.Action(nameof(ConfirmEmail), "Account", new { token, email = user.Email }, Request.Scheme);

        var message = new Message(new string[] { user.Email }, "Confirmation email link", confirmationLink, null);
        await emailSender.SendEmailAsync(message);

        return RedirectToAction(nameof(SuccessRegister));

EmailSender Class:

public class EmailSender : IEmailSender
{
    private readonly EmailConfiguration _emailConfig;

    public EmailSender(EmailConfiguration emailConfig)
    {
        _emailConfig = emailConfig;
    }

    public void SendEmail(Message message)
    {
        var emailMessage = CreateEmailMessage(message);

        Send(emailMessage);
    }

    public async Task SendEmailAsync(Message message)
    {
        var mailMessage = CreateEmailMessage(message);

        await SendAsync(mailMessage);
    }

    private MimeMessage CreateEmailMessage(Message message)
    {
        var emailMessage = new MimeMessage();
        emailMessage.From.Add(new MailboxAddress(_emailConfig.From));
        emailMessage.To.AddRange(message.To);
        emailMessage.Subject = message.Subject;

        var bodyBuilder = new BodyBuilder { HtmlBody = string.Format("<h2 style='color:red;'>{0}</h2>", message.Content) };

        if (message.Attachments != null && message.Attachments.Any())
        {
            byte[] fileBytes;
            foreach (var attachment in message.Attachments)
            {
                using (var ms = new MemoryStream())
                {
                    attachment.CopyTo(ms);
                    fileBytes = ms.ToArray();
                }

                bodyBuilder.Attachments.Add(attachment.FileName, fileBytes, ContentType.Parse(attachment.ContentType));
            }
        }

        emailMessage.Body = bodyBuilder.ToMessageBody();
        return emailMessage;
    }

    private void Send(MimeMessage mailMessage)
    {
        using (var client = new SmtpClient())
        {
            try
            {
                client.Connect(_emailConfig.SmtpServer, _emailConfig.Port, true);
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                client.Authenticate(_emailConfig.UserName, _emailConfig.Password);

                client.Send(mailMessage);
            }
            catch
            {
                //log an error message or throw an exception, or both.
                throw;
            }
            finally
            {
                client.Disconnect(true);
                client.Dispose();
            }
        }
    }

    private async Task SendAsync(MimeMessage mailMessage)
    {
        using (var client = new SmtpClient())
        {
            try
            {
                await client.ConnectAsync(_emailConfig.SmtpServer, _emailConfig.Port, true);
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                await client.AuthenticateAsync(_emailConfig.UserName, _emailConfig.Password);

                await client.SendAsync(mailMessage);
            }
            catch
            {
                //log an error message or throw an exception, or both.
                throw;
            }
            finally
            {
                await client.DisconnectAsync(true);
                client.Dispose();
            }
        }
    }
}

And Message Class:

 public class Message
{
    public List<MailboxAddress> To { get; set; }
    public string Subject { get; set; }
    public string Content { get; set; }

    public IFormFileCollection Attachments { get; set; }

    public Message(IEnumerable<string> to, string subject, string content, IFormFileCollection attachments)
    {
        To = new List<MailboxAddress>();

        To.AddRange(to.Select(x => new MailboxAddress(x)));
        Subject = subject;
        Content = content;
        Attachments = attachments;
    }
}

And Startup Class:

.AddEntityFrameworkStores<AppDbContext>()
            .AddDefaultTokenProviders()
            .AddErrorDescriber<TurkishIdentityErrorDescriber>();

        var emailConfig = Configuration.GetSection("EmailConfiguration").Get<EmailConfiguration>();
        services.AddSingleton(emailConfig);
        services.AddSingleton<Extension>();
        services.AddScoped<IEmailSender, EmailSender>();
        services.Configure<DataProtectionTokenProviderOptions>(opt => opt.TokenLifespan = TimeSpan.FromHours(2));
        services.AddAutoMapper(typeof(Startup));
James Z
  • 12,209
  • 10
  • 24
  • 44

1 Answers1

2

This is the problem right here: To.AddRange(to.Select(x => new MailboxAddress(x)));

That method doesn't exist. You meant to use To.AddRange(to.Select(x => MailboxAddress.Parse(x)));.

Same with this: emailMessage.From.Add(new MailboxAddress(_emailConfig.From));

It should be: emailMessage.From.Add(MailboxAddress.Parse(_emailConfig.From));

jstedfast
  • 35,744
  • 5
  • 97
  • 110
  • unfortunately this answer didn't work. Or I didn't understand you. I tried what you said. I keep getting the same error. – Ramazan Musluoğlu Jul 13 '22 at 10:54
  • 1
    Then you've got another place that makes the exact same mistake. – jstedfast Jul 13 '22 at 11:32
  • I did as you said. This time it returns similar error for sendasync: Method not found: 'System.Threading.Tasks.Task MailKit.MailTransport.SendAsync(MimeKit.MimeMessage, System.Threading.CancellationToken, MailKit.ITransferProgress)' – Ramazan Musluoğlu Jul 13 '22 at 12:30
  • 1
    Your netcore.mailkit package requires an older version of MailKit. But why use a third-party fork of MailKit instead of the real thing? Just use MailKit. – jstedfast Jul 13 '22 at 14:48