Send Email with Attachements and Progressbar in C# Windows Form

0
4550


In this post explains how to send email from your c# windows application with progress bar and attachment, this method uses the smtp feature of email clients.
Change the red color text to your credentials.

Create a New Windows Form Application

File -> New -> Project -> Windows Forms Application

Add 4 Textbox for To,Subject,Attachements,Message
Add 5 Labels
Add 2 Buttons for Send and Attachment Upload
Add 1 Progressbar

Add Namespace 
using System.Net
using System.Net.Mail;


Code for Uploading Attachment in Upload Button Click


private void btUpload_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
tbAttach.Text = dlg.FileName.ToString();
}
}

Code for Sending Email in Send Button Click

private void btSend_Click(object sender, EventArgs e)
{
if (tbTo.Text != "" && tbSub.Text != "" && tbBody.Text != "")
{
try
{
lblSucces.Text = "Sending ...";
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = 587;
client.EnableSsl = true;

//progress Bar
progressBar1.Visible = true;
progressBar1.Minimum = 1;
progressBar1.Maximum = 100000;
progressBar1.Value = 1;
progressBar1.Step = 1;
for (int x = 1; x <= 100000; x++)
{
progressBar1.PerformStep();
}
//progress Bar

client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("username@gmail.com", "passsword");
MailMessage msg = new MailMessage();
msg.To.Add(tbTo.Text);
msg.From = new MailAddress("username@gmail.com");
msg.Subject = tbSub.Text;
msg.Body = tbBody.Text;
if (tbAttach.Text != "")
{
Attachment data = new Attachment(tbAttach.Text);
msg.Attachments.Add(data);
client.Send(msg);
lblSucces.Visible = true;
MessageBox.Show("Successfully Sent Message.");
progressBar1.Visible = false;
lblSucces.Text = "Email Send Successfully";
}
else
{
client.Send(msg);
lblSucces.Visible = true;
MessageBox.Show("Successfully Sent Message.");
progressBar1.Visible = false;
lblSucces.Text = "Email Send Successfully";
lblSucces.ForeColor = Color.Green;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
lblSucces.Text = "Email Sending Failed !";
}
}
else
{
MessageBox.Show("All Fields are Mandatory !");
}
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here