Created
May 6, 2024 02:32
-
-
Save orlys/6256d6ee59e595ec9f76b2e2f1e274af to your computer and use it in GitHub Desktop.
Mock Mail Server & Client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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", "[email protected]")); | |
message.To.Add(new MailboxAddress("Orlys Ma", "[email protected]")); | |
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