Giter Club home page Giter Club logo

netdumbster's Introduction

dotnetcore

netDumbster

netDumbster is a .Net Fake SMTP Server clone of the popular Dumbster.

netDumbster is based on the API of nDumbster (http://ndumbster.sourceforge.net/default.html) and the nice C# Email Server (CSES) written by Eric Daugherty.

License: http://www.apache.org/licenses/LICENSE-2.0.html

Usage

Create a netDumbster Server instance:

using var server = SimpleSmtpServer.Start(port);

Check received email count:

var count = server.ReceivedEmailCount

Get the body of the first email received:

var smtpMessage = server.ReceivedEmail[0];
var body = smtpMessage.MessageParts[0].BodyData

Subscribe to the message received event:

server.MessageReceived += (sender, args) =>
    {
        // Get message body.
        var body = args.Message.MessageParts[0].BodyData;
    };

netdumbster's People

Contributors

adamholdenyall avatar artur-intech avatar cmendible avatar inkp avatar joaopgrassi avatar mindriven avatar queil avatar rklec avatar seanfeldman avatar simoncropp avatar stefan-schweiger avatar thompson-tomo avatar villan3ll3 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

netdumbster's Issues

SimpleSmtpServer.Start is not checking if port is in use

If I have two different processes doing this

var smtpServer = SimpleSmtpServer.Start(port: 25);

The second one should throw an exception informing that the port is already in use.

What I see is that the 2nd process continues silently, not triggering the MessageReceived event if subscribed.

Ensure proper cleanup of connections on server stopping

If a client does not close its own connection properly (e.g., when an SmtpClient is not disposed), a thread keeps running even when the server is stopped.

The problem is that the SmtpProcessor is not stopped once the server is being stopped.

c# - how to get email Subject?

Hello community, I'm probably dumb. I'm trying to receive email using netDumbster. I'm able to get email body, but how to get email Subject? Thanks for help!

    static void Main()
    {
        SimpleSmtpServer server = SimpleSmtpServer.Start(25);
        while (true)
        {
            if (server.ReceivedEmailCount > 0)
            {
                foreach (SmtpMessage message in server.ReceivedEmail)
                {
                    Console.WriteLine("----------------------------------------------------------------");
                    Console.WriteLine(message.ToAddresses[0].ToString());  //first ToAddress
                    //how to print message SUBJECT???
                    Console.WriteLine(message.MessageParts[0].BodyData.ToString());   //email body
                }
            server.ClearReceivedEmail();
            }
            Thread.Sleep(100);
        }
    }

TCPListener keeps socket open

Hi,

This is a fantastic project, but in my experience, the internal TCPListener is keeping the socket open, making it very diffecult to use from xUnit in a multi-test project.

Therefore I am proposing adding the following line to the server startup:
tcp.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
this will solve this problem.
Would you like a pull request/is this project maintained anymore?
Cheers
Sean.

Stopping connection mid message closes TCP Listener

Since version 2.0 if the socket is force closed by the client then it stops listening for any new messages.

Line 239
Socket socket = await this.tcpListener.AcceptSocketAsync();

throws An existing connection was forcibly closed by the remote host.

I've currently reverted to version 1.3.07 as it doesn't seem to have the same problem

SmtpMessagePart.HeaderData does not contain all headers

I am writing unit tests to verify a mail client.

SmtpMessagePart.HeaderData only contains the value of Content-Type. For my tests I need to verify attachments and linked resources(inline attachments). I am unable to differentiate between the two nor any other kind of mime part as I can't get the value of Content-Disposition.

Please include a way to get the full set of headers for a mime part.

Tests with netdumbster fail on github action

If I run the tests locally, everything is fine.
But they are executed by a github action, they fail with the following error:

Error Message:
System.Net.Sockets.SocketException : Permission denied
Stack Trace:
at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketError error, String callerName)
at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Bind(EndPoint localEP)
at System.Net.Sockets.TcpListener.Start(Int32 backlog)
at System.Net.Sockets.TcpListener.Start()
at netDumbster.smtp.SimpleSmtpServer.StartListening()
at netDumbster.smtp.SimpleSmtpServer.Start(Configuration configuration)
at netDumbster.smtp.Configuration.Build()

Any ideas?

Connection aborted error when client tries to connect to SimpleSmtpServer when specifying a port...

Hi,

Have some tests running under xUnit and using netDumbster

Here is the scenario///

  1. Basically each time a test is run, I start the server and specify the port.
        smtpServer = SimpleSmtpServer.Start(9000);
  1. Test case is executed

  2. After test is executed call SimpleSmtpServer.Stop()

        smtpServer.Stop()
  1. Run next test.

On the second run, I get the following error

System.Net.Mail.SmtpException : Failure sending mail.
----> System.IO.IOException : Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.
----> System.Net.Sockets.SocketException : An established connection was aborted by the software in your host machine
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at netDumbster.Test.Tests.SendMail(Boolean smtpAuth, Boolean isBodyHtml, Byte[] attachment) in Tests.cs: line 56
at netDumbster.Test.Tests.SendMail(Boolean smtpAuth) in Tests.cs: line 33
at netDumbster.Test.Tests.SendMail() in Tests.cs: line 28
at netDumbster.Test.Tests.Send_100_Mails() in Tests.cs: line 103
--IOException
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Mail.SmtpPooledStream.Dispose(Boolean disposing)
at System.IO.Stream.Close()
at System.Net.ConnectionPool.Destroy(PooledStream pooledStream)
at System.Net.ConnectionPool.PutConnection(PooledStream pooledStream, Object owningObject, Int32 creationTimeout, Boolean canReuse)
at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
--SocketException
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)

I can replicate this error in NetDumbster code (fails a couple of the tests) by changing the following...

In Tests.cs Line 68 in Setup()

    [SetUp]
    public void SetUp()
    {
                    _Server = SimpleSmtpServer.Start(50001);
        _Server.ClearReceivedEmail();
    }

Cheers.

Use a package readme

Summary

I wish for the nuget packages to have a more informative readme.

Details

The nuget package should be using the same readme as the repo to make it as easy as possible for a user to get started with the package.

Set Licence type expression on package info

Summary

I wish for the nuget packages to have the licence expression property set correctly

Details

The licence expression property should be set to the correct licence type (depending on the repo) as this will enable analysis of licences in use to occur in external tools & the license type will be shown in Nuget etc.

HeaderData has ASCII encoding

Hi Carlos!
Thanks for such helpful tool. We use it a lot in our integration tests but I noticed that my tests are failed. I started to look into it and noticed that subject of my mail messages contains characters in UTF-8 encoding (f.e. ’). I saw similar Issue reported for body so it seems the same issue for header data.

Reusing SmtpClient hangs in net50

The following test succeeds when running under netcoreapp3.1, but fails by timing out in net50

[Fact(Timeout = 10000)]
public async Task Net50Repo()
{
    var config = Configuration.Configure();
    using var server = SimpleSmtpServer.Start(config.WithRandomPort().Port);
    var inst = new SmtpClient
    {
        Host = "localhost",
        Port = server.Configuration.Port,
        EnableSsl = false
    };

    for (int messageNo = 0; messageNo < 2; messageNo++)
    {
        var mailMessage = new MailMessage("[email protected]", "[email protected]");

        await inst.SendMailAsync(mailMessage);

        Assert.Equal(messageNo + 1, server.ReceivedEmailCount);
    }
}

The issue seems to be reusing the SmtpClient, the first SendMailAsync succeeds, but the second call always just hangs indefinitely.

Works in 3.1. Newing up a new client for each call also works. Testing against a different Smtp server (eg. Papercut) also works.

netDumpster just ends up waiting inside SmtpContext on this line:

count = this.socket.Receive(byteBuffer);

It's like if the socket remains open it cannot be reused anymore for some reason. Any idea what changed?

Body Encode issue

I have found out SmtpContext init function would set the encode to ASCII at Link.

image

This makes UTF-8 char output incorrect.

ASCII encoding is not sufficient

Currently the netDumbster uses the ASCII encoding (hardcoded in the SmtpContext class). The ASCII uses 7 bits so the Encoding.GetString() returns question characters ('?') for all bytes that are greater than 127.
As a result I see '?' instead of letters in an email with Cyrillic text in the body.
It works great if I change the encoding to UTF8.

Please, change the encoding to UTF8 or make it customizable. Thanks!

Originally posted: http://goo.gl/dZmFN

Case sensitive properties

The SmtpMessage class contains an Importance property that returns the 'Importance' header.
However the software that I'm testing uses the 'importance' header instead of 'Importance'. And the Importance property returns an empty string in this case.

It seems that MIME headers are case insensitive as per discussion here: http://stackoverflow.com/questions/6143549/are-email-headers-case-sensitive. So, please, change the Importance property to be case insensitive. This is also applicable for XPriority and Priority properties.

Originally posted: http://goo.gl/PP63a

log4net dependency

Recent change in 1.3.0.1 has introduced dependency on log4net that is not encapsulated. As a result of that, it conflicts with many other nuget based libraries that are still on log4net 1.2.*
Since netDumbster is introduced later in projects (usually when code is tested), implementation libraries are already in place. Therefore possible options are

  1. as a workaround downgrade to use netDumbster 1.3.0.0 (no log4net dependency)
  2. do not use netDumbster at all

Would it be possible to abstract/encapsulate log4net? Perhaps something like this https://github.com/NServiceBus/NServiceBus/tree/develop/src/NServiceBus.Core/Logging
Thank you.

TLS Not supported

Hi,

Not sure if this is something that can be fixed, but when testing an email sent over TLS i get the error "The SMTP server does not support the STARTTLS extension.".

Thanks,
Adam

Add support for AlternateViews

Here is a unit test

[Test]
public void Send_Email_With_AlternateViews()
{
    using (var client = new SmtpClient("localhost", server.Port))
    {
        var mailMessage = new MailMessage("[email protected]", "[email protected]", "test", "this is the body");
        mailMessage.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("FooBar", new ContentType("text/html")));
        client.Send(mailMessage);
    }
    Assert.AreEqual(1, server.ReceivedEmailCount);
    var smtpMessage = server.ReceivedEmail[0];
    //TODO: validate AlternateViews here
}

Body is "cut" when using Mimekit/MailKit

I'm using MailKit + Mimekit to send emails in my .net app, since the one from System.Net.Mail is obsolete (dotnet/dotnet-api-docs#2986) and decided to give this a go for my unit tests.

After setting up the tests, they failed when asserting the body message. Somehow when getting the body via MessageParts[0].BodyData returns always the original message without the last two characters.

Here's an example test using MailKit (need to add the NuGet package to the test project)

[Fact]
public async Task Send_MimeKitEmail()
{
    using (var client = new MailKit.Net.Smtp.SmtpClient())
    {
        client.ServerCertificateValidationCallback = (_, __, ___, ____) => true;
        
        await client.ConnectAsync("localhost", this.server.Configuration.Port, false).ConfigureAwait(false);
        client.AuthenticationMechanisms.Remove("XOAUTH2");
        
        var from = new MimeKit.MailboxAddress("[email protected]");
        var to = new MimeKit.MailboxAddress("[email protected]");
        var body = "this is the body";
        
        var message = new MimeKit.MimeMessage();
        
        message.From.Add(from);
        message.To.Add(to);
        message.Subject = "test";
        message.Body = new MimeKit.TextPart("plain") { Text = body };
        
        client.Send(message);
    }
    
    Assert.Equal(1, server.ReceivedEmailCount);
    // this fails with the BodyData returning: "this is the bo"
    Assert.Equal("this is the body", server.ReceivedEmail[0].MessageParts[0].BodyData);
}

Not sure if am I missing something obvious or if this is a bug.

Support simpler SMTP transaction

Would be nice if a simple as possible SMTP transaction was supported:

IE.

telnet 127.0.0.1 25
helo 127.0.0.1
mail from: [email protected]
rcpt to: [email protected]
data
subject: test
blabla
.

As of now, you have to do the whole shebang with content typing, parts and whatnot, otherwise you'll just get disconnected.
Of course using SmtpClient works swell, but sometimes it'd be nice to just hack it off with a telnet session.

Make Start(Configuration configuration) public

Currently it's not possible as far as I can see to actually use DoNotReuseConnection because the Start(Configuration configuration) is not public. I don't think there is any downside to actually make this method available to all users.

Since it's only a one line change I can open a PR if you want.

No emails after ClearReceivedEmail called, even in subsequent tests.

Hi,

I'm using SpecFlow to coordinate NUnit tests.

When I call .ClearReceivedEmail the emails in subsequent tests aren't available in SimpleSmtpServer.smtpMessageStore.

I think it might be something to do with the new ConcurrentBag smtpMessageStore that is replacing the old one in ClearReceivedEmail(). I changed it so that ClearReceivedEmail just removes the old items and now it works!

SmtpMessage someItem;
while(!this.smtpMessageStore.IsEmpty)
{
this.smtpMessageStore.TryTake(out someItem);
}

I don't know why the reference in SmptProcessor isn't updated when you just create the new ConcurrentBag. Could be another problem in there somewhere.

If I knew how to push/pull then I'd submit it to you guys and get myself my first ever contribution.

Douglas.

Replace references to /libs by NuGet package references

IMO this is the preferred way.

It also fixes this issue: currently, the supplied log4net.dll has a different public key than the NuGet-version. I use netDumbster in a project that has a dependency on a library that has a reference to log4net on NuGet. These references to versions of log4net that have different public keys cannot coexist.

The SMTP server does not support authentication

Hi,

When I try to use method Authenticate I get the following error message:

System.NotSupportedException: 'The SMTP server does not support authentication.'

client.Authenticate("userName", "Password");

Could you suggest how to fix this error? I saw in your test project that you use SmtpClient with authentication.

image

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.