Dot Net Code Tips
Toggle navigation
Home
Categories
Azure
C#
CSS / Less
Network
Powershell
Razor
Security
SQL
Text Files
Visual Studio
Web.config
About
Contact
Send an email with the SMTP client
Create and send an email in C# code.
How to use the SmtpClient class to Send an email
Create a MailMessage specifying the sender, recipient, subject and body content.
Create an Smtp client using the localhost as the host. Set the credentials for the system user.
Use the SmtpClient to send the message.
var
msg =
new
MailMessage(
"from@domain.com"
,
"to@domain.com"
)
{
Subject =
"Your Subject Line"
;
Body =
"Email Body"
};
try
{
SmtpClient client =
new
SmtpClient(
"localhost"
)
{
Credentials =
new
System.Net.NetworkCredential(
"userid@domain.com"
,
"user-password"
)
};
client.Send(msg);
}
catch
(Exception ex)
{
System.Console.WriteLine(msg.Body + ex.TargetSite.ToString());
}