How to send emails using C#
Nov 30, 2020 07:06 0 Comments C# (C-Sharp) PARTH

               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());

}

 

 

Prev Next
About the Author
Topic Replies (0)
Leave a Reply
Guest User

You might also like

Not sure what course is right for you?

Choose the right course for you.
Get the help of our experts and find a course that best suits your needs.


Let`s Connect