title: How do you send an email as part of the startup configure process?
body: <p>I want my application to persist to if the email credentials were valid when first starting up and sending a startup email to a location as part of this test. </p>
  
  <p>When I place email functions in startup or even SendGrid, if the credentials are valid there is no error, but no message sent. I can do it as part of a middleware filter and as part of a cache, but this would be my preference actually becoming a scoped service.</p>
  
  <p>My email code works as part of a controller or service call, but even though it doesn't error in startup if the credentials are valid the email doesn't actually send.</p>
  
  <p><em>startup.cs</em></p>
  
  <pre><code>public void ConfigureServices(IServiceCollection services)
  {
      var emailStatus = new EmailStatus();
  
      try
          {
              _emailSender.SendEmailAsync(Options.Support, "App STARTUP",
                     $"email success.");
              emailStatus.failed = false;
              //Set
          }
          catch (SmtpCommandException ex)
          {
              _logger.LogError(ex.Message);
              emailStatus.failed = false;
          }
          catch (Exception ex)
          {
              _logger.LogError(ex.Message);
  
              // Debug.WriteLine("Exception: " + ex.Message);
              _logger.LogError("Task Inner Exception: " + ex.InnerException);
              _logger.LogError("Task StackTrace: " + ex.StackTrace);
              emailStatus.failed = false;
          }
  
        services.AddSingleton(emailStatus);
  }
  </code></pre>
  
  <p><em>EmailSender.cs</em></p>
  
  <pre><code>public class EmailSender : IEmailSender
  {
      public EmailSender(IOptions&lt;AuthMessageSenderOptions&gt; optionsAccessor)
      {
          Options = optionsAccessor.Value;
      }
  
      public EmailSender(AuthMessageSenderOptions options)
      {
          this.Options = options;
  
      }
      public AuthMessageSenderOptions Options { get; } //set only via Secret Manager
  
      public Task SendEmailAsync(string email, string subject, string message)
      {
          return Execute(subject, message, email);
      }
  
      public async Task Execute(string subject, string message, string email)
      {
          if (Options.Service != "SendGrid")
          {
              var mailMessage = new MimeMessage();
              mailMessage.To.Add(new MailboxAddress(email));
              mailMessage.From.Add(new MailboxAddress("noreply@email.com"));
  
  
              mailMessage.Subject = subject;
              mailMessage.Body = new TextPart(TextFormat.Html)
              {
                  Text = message
              };
              // mailMessage.Body = message;
              //Be careful that the SmtpClient class is the one from Mailkit not the framework!
              using (var emailClient = new SmtpClient())
              {
                  //The last parameter here is to use SSL (Which you should!)
                  await emailClient.ConnectAsync(Options.Domain, Options.Port, true);
  
                  //Remove any OAuth functionality as we won't be using it. 
                  emailClient.AuthenticationMechanisms.Remove("XOAUTH2");
  
                  emailClient.Authenticate(Options.SendGridUser, Options.SendGridKey);
  
                  try
                  {
                      await emailClient.SendAsync(mailMessage).ConfigureAwait(false);
                      await emailClient.DisconnectAsync(true).ConfigureAwait(false);
                  }
                  catch (Exception ex)
                  {
                      await emailClient.DisconnectAsync(true).ConfigureAwait(false);
                      throw ex;
                      // return BadRequest(new { message = "Email failed to send", error = ex.ToString() });
                      // Label1.Text = ex.ToString();
                  }
                  // emailClient.Disconnect(true);
              }
          }
          else
          {
  
              var client = new SendGridClient(Options.SendGridKey);
              var msg = new SendGridMessage()
              {
                  From = new EmailAddress("noreply@email.com", "Do Not Reply"),
                  Subject = subject,
                  PlainTextContent = message,
                  HtmlContent = message
              };
              msg.AddTo(new EmailAddress(email));
  
              // Disable click tracking.
              // See https://sendgrid.com/docs/User_Guide/Settings/tracking.html
              msg.SetClickTracking(false, false);
  
              await client.SendEmailAsync(msg);
          }
      }
  }
  </code></pre>