Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send mail using C#?

Tags:

c#

email

asp.net

i want to send mail to any email address, how to do that using C#. i am working on local host.

like image 669
Sheery Avatar asked Mar 01 '10 07:03

Sheery


2 Answers

System.Net.Mail.MailMessage message=new System.Net.Mail.MailMessage(
                new MailAddress(EmailUsername), new MailAddress("toemailaddress"));

message.Subject = "Message Subject";   // E.g: My New Email
message.Body = "Message Body";         // E.g: This is my new email ... Kind Regards, Me

For the SMTP part, you can also use SmtpClient:

SmtpClient client = new SmtpClient(ServerIP);
client.Credentials = new System.Net.NetworkCredential(EmailUsername, EmailPassword);
client.Send(message);

Please consider accepting some answers. A 0% accepted rate is not great.


Edited to fix the silly mistakes. Serves me right for not checking the code first.

like image 104
Kyle Rosendo Avatar answered Oct 11 '22 16:10

Kyle Rosendo


You can use the SmtpClient class and call Send (or SendAsync) with a MailMessage instance. Both these classes are in the System.Net.Mail namespace.

SmtpClient's default constructor uses the configuration from your app/web.config, but you can use other constructors to specify the SMTP settings you want.

// using System.Net.Mail;

SmtpClient client = new SmtpClient();

MailMessage mm = new MailMessage()
{
    Subject = "Subject here",
    Body = "Body here"
};

mm.To.Add("[email protected]");
mm.From = new MailMessage("[email protected]");

client.Send(mm);
like image 45
Richard Szalay Avatar answered Oct 11 '22 14:10

Richard Szalay