How to send emails using C#
How to send emails using C#
For sending emails in C#, we use MailMessage class which is a part of System.Net.Mail namespace and is used to create email messages that are then sent over an SMTP server.
Let’s see an example –
using System.Net;
using System.Net.Mail;
MailAddress toAddress = new MailAddress("parthjolly1991@gmail.com");
MailAddress fromAddress = new MailAddress("parthjolly1991@outlook.com");
MailMessage message = new MailMessage(fromAddress, toAddress);
message.Subject = "Hello";
message.Body = "My name is Parth.";
SmtpClient client = new SmtpClient("smtp.server.address", 2525)
{
Credentials = new NetworkCredential(“username", "password"),
EnableSsl = true
};
try
{
client.Send(message);
}
catch (SmtpException ex)
{
Console.WriteLine(ex.ToString());
}
Let’s see one more example, but this time with an attachment –
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
String pathOfTheFile = "data.xlsx";
Attachment data = new Attachment(pathOfTheFile, MediaTypeNames.Application.Octet);
MailAddress toAddress = new MailAddress("parthjolly1991@gmail.com");
MailAddress fromAddress = new MailAddress("parthjolly1991@outlook.com");
MailMessage message = new MailMessage(fromAddress, toAddress);
message.Subject = "Result";
message.Body = "Please find attached the result of the match.";
message.Attachments.Add(data);
SmtpClient client = new SmtpClient("smtp.server.address", 2525)
{
Credentials = new NetworkCredential("username", "password"),
EnableSsl = true
};
try
{
client.Send(message);
}
catch (SmtpException ex)
{
Console.WriteLine(ex.ToString());
}
