Skip to content

Simple SMTP server. It can be run in c# code. It's created for unit tests purposes.

Notifications You must be signed in to change notification settings

travislaborde/MailRetriever

 
 

Repository files navigation

MailRetriever

Logo It is a simple SMTP server. It can be run in c# code. It was created for unit tests purposes (espacially BDD tests). You can run SMTP server by one line of code. After that server can inform you when specific email was retrieved. Server has also a list of all received messages.

      using (var server = new SmtpServer(12000))
      {
          // Sending an email...
          SendEmail("[email protected]", "subject", "content"); 
          
          // Waiting for email (timeout is 10 seconds)...
          emailMessage = server.WaitForEmailFromAsync("[email protected]", 10).Result;
      }

Example of usage in unit test:

  [Fact]
  public void ServerRetrieveEmail()
  {
      EmailMessage emailMessage;
      List<EmailMessage> emailMessages;
      using (var server = new SmtpServer(12000))
      {
          AsyncHelpers.RunSync(() => SendEmail(
              new[] { "[email protected]", "[email protected]" },
              "Simple subject",
              "Email content")
          );

          emailMessage = server.WaitForEmailFromAsync("[email protected]", 10).Result;
          emailMessages = server.EmailMessages.ToList();
      }

      Assert.Equal(1, emailMessages.Count);
  }
      
  public static async Task<bool> SendEmail(string[] recipientAddress, string subject, string body)
  {
      var mimeMessage = new MimeMessage();
      mimeMessage.From.Add(new MailboxAddress("MailRetriever", "[email protected]"));
  
      foreach (var address in recipientAddress)
      {
          mimeMessage.To.Add(new MailboxAddress(address, address));
      }
  
      mimeMessage.Subject = subject;
      mimeMessage.Body = new TextPart("html")
      {
          Text = body
      };
  
      using (var client = new SmtpClient())
      {
          await client.ConnectAsync("127.0.0.1", 12000, false);
          await client.AuthenticateAsync("[email protected]", "password");
          await client.SendAsync(mimeMessage);
          await client.DisconnectAsync(true);
      }
  
      return true;
  }

For sending email you can use MailKit which is also ASP.NET Core 1 compatible.

AppVeyour status:

branch status
master Build status
develop Build status

About

Simple SMTP server. It can be run in c# code. It's created for unit tests purposes.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • C# 100.0%