Sending Email with C#

This article, looks at how to programmatically send email messages from a Web page

public void SendMail()

{

if (txt_username.Text != "" && txt_password.Text != "")

{{ System.Net.Mail.MailMessage msg = new

System.Net.Mail.MailMessage(); //create the message

//msg.To.Add("balajisathe@gmail.com");

msg.To.Add(txt_to.Text);

//msg.To.Add("balaji@domain.com");

msg.From = new MailAddress("balajisathe@gmail.com",

txt_username.Text, System.Text.Encoding.UTF8);

msg.Subject = txt_subject.Text;

// msg.Subject = "HI friends";

msg.SubjectEncoding = System.Text.Encoding.UTF8;

msg.Body = txt_body.Text;

//msg.Body = "I am Balaji";

msg.BodyEncoding = System.Text.Encoding.UTF8;

msg.IsBodyHtml = false;

msg.Priority = MailPriority.High;

SmtpClient client = new SmtpClient();

//Network Credentials for Gmail

client.Credentials = new

System.Net.NetworkCredential(txt_username.Text, txt_password.Text);

client.Port = 587;

client.Host = "smtp.gmail.com";

client.EnableSsl = true;

//Attachment data = new Attachment("C:/ok.txt");

// Attachment data = new Attachment(openFileDialog1.FileName);

// if (dialog.ShowDialog() == DialogResult.OK)

try

{

//if (openFileDialog1.CheckPathExists)

if(openFileDialog1 .FileName !="")

{

Attachment data = new Attachment(openFileDialog1.FileName);

//throw new FileNotFoundException("Send Without Attachments");

{

msg.Attachments.Add(data);

try

{

client.Send(msg);

}

catch

{

data.Dispose();

}

data.Dispose();

}

}

else

{

MessageBox.Show("Message send without attachment");

}

}

catch (FileNotFoundException fx)

{ MessageBox.Show("Message Send Without Attachments");

client.Send(msg); }

catch (Exception ex) { }

//File.WriteAllText(appstart.path, ""); //empties the file

MessageBox.Show("Message sent Succefully");

txt_password.Text = txt_username.Text = txt_body.Text =

txt_to.Text = txt_subject.Text = "";

}

}

else

{

MessageBox.Show("Please enter all Information ");

}

}

private void button1_Click(object sender, EventArgs e)

{

SendMail();

}

private void button2_Click(object sender, EventArgs e)

{

openFileDialog1.ShowDialog();

}

private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)

{

Process myproceess = new Process();

try

{

myproceess.StartInfo.FileName = "www.csharpindepth.blogspot.com";

myproceess.Start();

}

catch (Exception ex)

{ }

}