Testing Your Email Sending in .NET with Ethereal

berviantoleo

Bervianto Leo Pratama

Posted on June 17, 2022

Testing Your Email Sending in .NET with Ethereal

Preparation

For the previous part, you may need to visit the post here.

Alright, let's get started from scratch. Firstly, I will generate my project. Secondly, I will give a simple example code to send emails using SMTP server. Lastly, I will add the repository link, and you can test the code.

Note: You will need to create the Ethereal Account first. If you want to create an account, please visit here.

Create

Created

Please make sure you have .NET SDK Installation. Don't have it yet? Download here. Anyway, I use .NET 6.

Create .NET Project

  1. Generate the project using this command: dotnet new console -o MailExample.
  2. I also generate .gitignore and sln files. Using these commands: dotnet new gitignore and dotnet new sln. After that connect sln file with the project file, using this command: dotnet sln add .\MailExample\.
  3. Finally, try to build your project using dotnet build.

Coding Time

  1. Update MailExample/Program.cs file.


using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Text.Json;

var smtpClient = new SmtpClient("smtp.ethereal.email")
{
    Port = 587,
    Credentials = new NetworkCredential("<update your username here>", "<update your user here>"),
    EnableSsl = true,
};

var attachment = Attachment.CreateAttachmentFromString(JsonSerializer.Serialize(new
{
    Message = "Hello World!"
}), "helloworld.json", Encoding.UTF8, MediaTypeNames.Application.Json);

var message = new MailMessage("fromtest@test.com", "sendertest@test.com")
{
    Subject = "Test Email! Hello World!",
    Body = "<p>Test Email</p><b>Hello World!</b>",
    IsBodyHtml = true,
};

message.Attachments.Add(attachment);

try
{
    smtpClient.Send(message);
}
catch (SmtpException ex)
{
    Console.WriteLine(ex.ToString());
}


Enter fullscreen mode Exit fullscreen mode
  1. Run the project. Using this command: dotnet run --project .\MailExample\.

  2. Check your account inbox (the Ethereal account, not your To inbox).

Inbox

Email

dotnetemailexample

.NET Email Example






Some Notes

  • Anyway, I have little concern about privacy. So, if you have private projects, I don't recommend using this. I recommend using this if you have a public personal project or another project that it's okay if you disclose the information.
  • For the alternative, you may use Mailtrap or other email testing providers.

Thank you

Thanks for reading.

Thanks

💖 💪 🙅 🚩
berviantoleo
Bervianto Leo Pratama

Posted on June 17, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related