I have the following code that works fine sending emails, but I'm getting these warnings that say that I should label some of the methods Obsolete. I Looked at the docs on the mailKit website and it says that I should use a different constructor than MailboxAddress(String). I get that, but am having troubles on how to implement the way they're asking, it seems simple but i think im missing a step. This is one of the ways that's recommend MailboxAddress(String, String) new way of doing it.
Code as follows:
Controller
public IActionResult RequestPassword() { var message = new Message(new string[] { "[email protected]" }, "Test Email", "This is the content from out email." ); _emailSender.SendEmail(message); return View(); } Message.cs
For this class the warning pops up on line To.AddRange(to.Select(x => new MailboxAddress(x)));
public class Message { public List<MailboxAddress> To { get; set; } public string Subject { get; set; } public string Content { get; set; } public Message(IEnumerable<string> to, string subject, string content) { To = new List<MailboxAddress>(); To.AddRange(to.Select(x => new MailboxAddress(x))); Subject = subject; Content = content; } } EmailSender class For this class the warning pops up on line emailMessage.From.Add(new MailboxAddress(_emailConfig.From));
public class EmailSender : IEmailSender { private readonly EmailConfiguration _emailConfig; public EmailSender(EmailConfiguration emailConfig) { _emailConfig = emailConfig; } // This creates the Email and then sends it. public void SendEmail(Message message) { var emailMessage = CreateEmailMessage(message); Send(emailMessage); } // Creates Email Message 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; emailMessage.Body = new TextPart(MimeKit.Text.TextFormat.Text) { Text = message.Content }; return emailMessage; } // Sends the email private void Send(MimeMessage mailMessage) { using var client = new SmtpClient(); try { client.Connect(_emailConfig.MailServer, _emailConfig.MailPort, false); client.Authenticate(_emailConfig.Username, _emailConfig.Password); client.Send(mailMessage); } catch (Exception) { throw; } finally { client.Disconnect(true); client.Dispose(); } } } Interface
public interface IEmailSender { void SendEmail(Message message); } If you want the StartUp.cs as well let me know.
