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.
Please make sure you have .NET SDK Installation. Don't have it yet? Download here. Anyway, I use .NET 6.
Create .NET Project
- Generate the project using this command:
dotnet new console -o MailExample
. - I also generate
.gitignore
andsln
files. Using these commands:dotnet new gitignore
anddotnet new sln
. After that connect sln file with the project file, using this command:dotnet sln add .\MailExample\
. - Finally, try to build your project using
dotnet build
.
Coding Time
- 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());
}
Run the project. Using this command:
dotnet run --project .\MailExample\
.Check your account inbox (the Ethereal account, not your
To
inbox).
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.
Top comments (2)
I used
https://www.inbucket.org/
for similar effect in the past.Thank you for the reference. 👍