we need the following design in windows application project.
the above forms for SMTP Configuration form and Sending Mail form.
Step 2 : Add the SMTP configuration class
add the following class in you project in order to make a SMTP configuration for your mail that we need to send.
public class cls_smtpConfiguration
{
public static string host;
public static int port;
public static int timeout;
public static bool enable_ssl;
public static string username_account;
public static string password_account;
}
this class has a values from SMTP Configuration form and will get it for Sending Mail form.
Step 3 : In the SMTP Configuration form
Add the following code in the button Save Setting in the SMTP Configuration form
cls_smtpConfiguration.host = textBox1.Text;
cls_smtpConfiguration.port = Convert.ToInt32(textBox2.Text);
cls_smtpConfiguration.timeout = Convert.ToInt32(textBox4.Text);
if (radioButton1.Checked == true)
{
cls_smtpConfiguration.enable_ssl = true;
}
else
{
cls_smtpConfiguration.enable_ssl = false;
}
cls_smtpConfiguration.username_account = textBox6.Text;
cls_smtpConfiguration.password_account = textBox5.Text;
this.Close();
The above code try to setting values from controls of form to members of cls_smtpConfiguration Class
Step 4 : In the Sending Mail form
follow the following steps under the Send mail button
- Define the following line
- System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
- System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(cls_smtpConfiguration.host, cls_smtpConfiguration.port);
- System.Net.Mail.Attachment attach;
message object : for setting values (from, to, body ....)
smtp object : for setting smtp configuration about from mail
attach object : for setting the attachement files that is required to be attached with mail .
- Try to validate [mail from] and [mail to] if (ValidateEmail(textBox2.Text) == true) { message.To.Add(textBox2.Text); } else { MessageBox.Show("not valid mail");return; }
- if (ValidateEmail(textBox1.Text) == true) {message.From = new System.Net.Mail.MailAddress(textBox1.Text); } else { MessageBox.Show("not valid mail"); return; }
- Setting the following values
- message.Subject = textBox3.Text;
- message.Body = richTextBox1.Text;
- smtp.Timeout = cls_smtpConfiguration.timeout;
- smtp.EnableSsl = cls_smtpConfiguration.enable_ssl;
- smtp.Credentials = new System.Net.NetworkCredential(cls_smtpConfiguration.username_account, cls_smtpConfiguration.password_account);
- the following code for setting [attach] object all attachement that is exist in listbox1 if (listBox1.Items.Count > 0) { for (int i = 0; i < listBox1.Items.Count; i++) { attach = new System.Net.Mail.Attachment(listBox1.Items[i].ToString()); message.Attachments.Add(attach); } }
- Final Step, sending mail smtp.Send(message); MessageBox.Show("message sended !!");
x.ShowDialog();
follow the following steps under the Select button
x.ShowDialog();
listBox1.Items.Add(x.FileName);