This tutorial show you how to send email via SMTP (Free Gmail.com SMTP) in C#.Net Window Form. Includes CC, BCC, html content and attachment files.
1. Create new winform project
2. Design form like below
3. Open Form .CS file
- Add Mail function references:using System.Net.Mail; using System.Net;- Add attachment files:
+) In design add listBox to show attachment files.
+) Attach Button action:
Define global file dialog
OpenFileDialog dlgopenFile = new OpenFileDialog();Add attachment into listBox
dlgopenFile.Title = "Choose files attach";
dlgopenFile.Multiselect = true;
dlgopenFile.InitialDirectory = "C:\\";
if (dlgopenFile.ShowDialog() == DialogResult.OK)
{
string[] fileName = dlgopenFile.FileNames;
int i = fileName.Length;
for (int j = 0; j < i; j++)
{
lstfiles.Items.Add(fileName[j]);
}
}
Remove attachment button ( choose line on listBox to remove )while (lstfiles.SelectedItems.Count > 0)
{
lstfiles.Items.Remove(lstfiles.SelectedItem);
}
+) Sent mail button event:MailMessage MyMailMessage = new MailMessage(youradress_tbox.Text, toadress_tbox.Text);
// Add BCC
if (txtBCC.Text.Trim() != string.Empty)
{
string[] bccMail = this.txtBCC.Text.Trim().Split(';');
for (int i = 0; i < bccMail.Length; i++)
{
MyMailMessage.Bcc.Add(bccMail[i].ToString());
}
}
// Add CC
if (this.txtCC.Text.Trim() != string.Empty)
{
string[] ccMail = this.txtCC.Text.Trim().Split(';');
for (int i = 0; i < ccMail.Length; i++)
{
MyMailMessage.CC.Add(ccMail[i].ToString());
}
}
// Create mail body
MyMailMessage.Subject = subject_tbox.Text; ;
MyMailMessage.Body = this.content_tbox.Text; ;
MyMailMessage.IsBodyHtml = true;
// Attachment file
string sFile;
if (lstfiles.Items.Count > 0)
{
for (int i = 0; i < lstfiles.Items.Count; i++)
{
lstfiles.SelectedIndex = i;
sFile = lstfiles.Text;
if (sFile != string.Empty)
{
Attachment attachment = new Attachment(sFile);
MyMailMessage.Attachments.Add(attachment);
}
}
}
//MyMailMessage.IsBodyHtml = false;
// Create Cre email
NetworkCredential mailAuthentication = new NetworkCredential(youradress_tbox.Text, this.pass_tbox.Text.Trim());
// Create SMTP Gmail
SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);
mailClient.EnableSsl = true;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = mailAuthentication;
if (mailClient.Timeout.ToString() == "10000")
{
MessageBox.Show("Time out!");
}
else
{
try
{
mailClient.Send(MyMailMessage);
MessageBox.Show("Send success!");
}
catch (Exception ex)
{
MessageBox.Show("Send mail error: " + ex.Message);
}
}
+) Exit button event: Application.Exit();+) Download full project source (password: 9tuts.net)
Note:
- Run app without proxy server or open port of SMTP server
- You can fix your name and password in a .config file
- Comment if you have any question
