Skip to content

Instantly share code, notes, and snippets.

@Orlys
Created May 6, 2024 02:32
Show Gist options
  • Save Orlys/6256d6ee59e595ec9f76b2e2f1e274af to your computer and use it in GitHub Desktop.
Save Orlys/6256d6ee59e595ec9f76b2e2f1e274af to your computer and use it in GitHub Desktop.
Mock Mail Server & Client
using SmtpServer.ComponentModel;
using SmtpServer;
using MimeKit;
using MailKit.Net.Smtp;
using SmtpServer.Storage;
using System.Buffers;
// **PREREQUIRED: ADD '127.0.0.1 aaa.bbb' to HOSTS file.
var options = new SmtpServerOptionsBuilder()
.ServerName("aaa.bbb")
.Port(25, 587)
.Build();
var sp = new ServiceProvider();
sp.Add(new SampleMessageStore());
var smtpServer = new SmtpServer.SmtpServer(options, sp);
_ = smtpServer.StartAsync(CancellationToken.None);
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Joey Tribbiani", "joey@aaa.bbb"));
message.To.Add(new MailboxAddress("Orlys Ma", "orlys@aaa.bbb"));
message.Subject = "How you doin'?";
message.Body = new TextPart("plain")
{
Text =
"""
Hey Orlys,
I just wanted to let you know that Monica and I were going to go play some paintball, you in?
-- Joey
"""
};
using (var client = new SmtpClient())
{
client.Connect("aaa.bbb", 587, false);
// Note: only needed if the SMTP server requires authentication
//client.Authenticate("joey", "password");
client.Send(message);
client.Disconnect(true);
}
Console.ReadKey();
public class SampleMessageStore : MessageStore
{
public override async Task<SmtpServer.Protocol.SmtpResponse> SaveAsync(ISessionContext context, IMessageTransaction transaction, ReadOnlySequence<byte> buffer, CancellationToken cancellationToken)
{
await using var stream = new MemoryStream();
var position = buffer.GetPosition(0);
while (buffer.TryGet(ref position, out var memory))
{
await stream.WriteAsync(memory, cancellationToken);
}
stream.Position = 0;
var message = await MimeMessage.LoadAsync(stream, cancellationToken);
await Console.Out.WriteLineAsync("FROM:" + string.Join(",", message.From));
await Console.Out.WriteLineAsync("TO:" + string.Join(",", message.To));
await Console.Out.WriteLineAsync("CONTENT:" + message.TextBody);
return SmtpServer.Protocol.SmtpResponse.Ok;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment