![Sending an email with ASP.NET Core](/img/articleImages/send-email-asp-net-core.webp)
Sending an email with ASP.NET Core
![Original YouTube Logo](/img/original-youtube-logo.png)
Article have related YouTube video
In this article you will find the code in C# to send an email with ASP.NET Core. The example is a contact page, however you can use the same logic for whatever you want. The way of writing the code will be the same C# code.
If you want an examination of the code then watch my YouTube video in the article. Else fell free to copy and paste the code that sends an email.
Remember to change the smtpClient to match your own mailserver settings and edit the message.To() and the message.From().
The SendMail method takes three parameters which is name, email and message. You can always add more parameters to the method to fit your needs.
There are two using statements you need to implement for make the code run properly.
using System.Net;
using System.Net.Mail;
public bool SendMail(string name, string email, string message1)
{
MailMessage message = new MailMessage();
SmtpClient smtpClient = new SmtpClient();
message.From = new MailAddress("yourFrom@email.com");
message.To.Add("to@email.com");
message.Subject = "Test email";
message.IsBodyHtml = true;
message.Body = "<p>Name: " + name + "</p>" + "<p>Email: " + email + "</p>" + "<p>Message: " + message1 + "</p>";
smtpClient.Port = 587;
smtpClient.Host = "your.host.com";
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential("Username", "Password");
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Send(message);
return true;
}
For more in depth knowledge of how the code work, please watch this YouTube video.