How to send email using c# with attachment

In this post, I will tell how to send email using c#.

There are few steps that must be followed to make email client that can send email from gmail account to any of other email address. For this we will use a new class System.Net.Mail and use some of there method like MailMessage and SmtpClient.

Step 1. Make a form shown below:-



Step 2. In this. we will use a tool  Openfiledialog which will be used for selecting the file, so select openfile dialog  and drag it on the window form
Step 3. Now double click on select file button and paste the coding:-
 (Note:- before pasting this code add a referance to the class using System.Net.Mail;)

if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                textBox6.Text = openFileDialog1.FileName;
            }
Step 4. Again come to design view and double click on the send email and paste the coding:-
  MailMessage Mail = new MailMessage();
            SmtpClient smtp = new SmtpClient("smtp.gmail.com");
            Mail.From = new MailAddress(textBox1.Text);
            Mail.To.Add(textBox3.Text);
            Mail.Subject = textBox4.Text;
            Mail.Body = textBox5.Text;
            System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(textBox6.Text);
            Mail.Attachments.Add(attachment);
            System.Net.Mail.Attachment attachment1 = new System.Net.Mail.Attachment(textBox7.Text);
            Mail.Attachments.Add(attachment1);
      
            smtp.Port = 587;
            smtp.Credentials = new System.Net.NetworkCredential(textBox1.Text, textBox2.Text);
            smtp.EnableSsl = true;
            smtp.Send(Mail);
            MessageBox.Show("mail send");

Now save your project and run it and fill detail to send email.
Download source code(click to download)


Thank for reading this..
Enjoy code.

1 comments :

Post a Comment