How do you send an email in C#/.NET? That sounds like it should be simple, after all, electronic mail existed decades before the Internet.
If you've worked with emails for any length of time, you'll soon hear about the Simple Mail Transfer Protocol (SMTP) for sending and Internet Message Access Protocol (IMAP - which replaced POP3) for receiving. That's an important distinction to take note of: sending, and receiving emails use different protocols.
System.Net.Mail
At first glance, SMTP seems relatively straightforward.
Here's how to write an email using System.Net.Mail (there's a better way though):
var smtpClient = new SmtpClient("smtp.example.com"){
Port = 587,
Credentials = new NetworkCredential("username", "password"),
EnableSsl = true,
};
smtpClient.Send("[email protected]", "[email protected]", "subject", "body");
That doesn't actually look that bad, and might be all you need at the moment.
You can even re-write it to make an email object called MailMessage first:
var mailMessage = new MailMessage{
From = new MailAddress("[email protected]"),
To = new MailAddress("[email protected]"),
Subject = "subject",
Body = "<p>Hello</p>",
IsBodyHtml = true,
};
smtpClient.Send(mailMessage);
You can also move the client definition to a separate appsettings.json file like so (if adding it manually then make sure to set Properties -> Copy to Output Directory -> Copy if newer):
{
"EmailSender": {
"SmtpHost": "smtp.gmail.com",
"SmtpPort": 587,
"SmtpCredential": {
"UserName": "[email protected]",
"Password": "App1icati0nP455w0rd"
},
"ProtocolLog": "Logs\\SmtpClient.txt"
}
}
You could read those settings with Microsoft.Extensions.Configuration.Json and use them as follows (keep reading though, there's a better way!):
using Microsoft.Extensions.Configuration;
var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var smtpClient = new SmtpClient(configuration["EmailSender:SmtpHost"]){
Port = int.Parse(configuration["EmailSender:SmtpPort"]),
Credentials = new NetworkCredential(configuration["EmailSender:SmtpCredential:UserName"], configuration["EmailSender:SmtpCredential:Password"]),
EnableSsl = true,
};
Let's simplify that by parsing the configuration to a predefined object type (later we'll re-use MailKitSimplified.Sender.Models.EmailSenderOptions):
using Microsoft.Extensions.Configuration;
var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
var emailSenderOptions = configuration.GetRequiredSection(EmailSenderOptions.SectionName).Get<EmailSenderOptions>();
var smtpClient = new SmtpClient(emailSenderOptions.SmtpHost){
Port = emailSenderOptions.SmtpPort,
Credentials = emailSenderOptions.SmtpCredential,
EnableSsl = emailSenderOptions.SmtpPort == 587 ? true : false,
};
venus najadPosted May 4, 2024, 7:11 PM
Hello... i will like Ebay, people contact each other with their different email accounts, without any condition... i have specified different smtp for each email accounts, but i get error for special gmail: The SMTP server requires a secure connection or the client was not authenticated. how should i solve it? even in this email conversation between us, i have registeret may email and i send you this message without any condition and you respond me without any condition... how it works? other onlne market place, contact eachother with deifferent email accounts without any condition.. how it works? i appreciate your solution... i have make DropDownLists for both smtp and port, but i receive the error???!!! how should i solve it? my project is c# asp net webform... my email is [email protected]... i apprecaite your solution. kind regards
Daniel CollingwoodPosted Nov 28, 2022, 4:33 AM
Hi @Abdullah Shah, try setting up https://github.com/rnwood/smtp4dev and connecting to that. If that works then set the ProtocolLog option to "Logs/SmtpClient.txt" and copy the log here. The error message suggests you've got the wrong hostname or port. If you're using gmail then the host is "smtp.gmail.com:587", but for testing locally you can either leave the port as default or set it to port 25.
Abdullah ShahPosted Nov 25, 2022, 5:54 AM
I get the following error message when trying to send a simple message:A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.