dotnetemailexample
.NET Email Example
Posted on June 17, 2022
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.
Please make sure you have .NET SDK Installation. Don't have it yet? Download here. Anyway, I use .NET 6.
dotnet new console -o MailExample
..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\
.dotnet build
.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());
}
Run the project. Using this command: dotnet run --project .\MailExample\
.
Check your account inbox (the Ethereal account, not your To
inbox).
Thanks for reading.
Posted on June 17, 2022
Sign up to receive the latest update from our blog.