Thursday 28 April 2011

Mail Sending Program in win forms using C#


Mail Sending Program in win forms using C#





using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        MailMessage mailMessage;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (textBox1.Text != null && textBox2.Text != null)
                {
                    mailMessage = new MailMessage(textBox1.Text, textBox4.Text);

                    mailMessage.Subject = textBox5.Text;
                    mailMessage.Body = textBox6.Text;
                    mailMessage.IsBodyHtml = true;

                    /* Set the SMTP server and send the email  */

                    SmtpClient smtpClient = new SmtpClient();

                    
                    smtpClient.Host = "smtp.gmail.com";
                    
                    smtpClient.Port = 587;
                    smtpClient.UseDefaultCredentials = true;

                    
                    smtpClient.Credentials = new NetworkCredential(textBox1.Text, textBox2.Text);

                    //this will be the true in case of gamil and it varies from the service provider
                    smtpClient.EnableSsl = true;
                    smtpClient.Send(mailMessage);
                }
               
                string msg="Message Send Successfully:";
                msg+="\n To :"+ textBox4.Text;
 
                MessageBox.Show(msg.ToString());

                /* clear the controls */
                textBox1.Text = string.Empty;
                textBox2.Text = string.Empty;
                textBox3.Text = string.Empty;
                textBox4.Text = string.Empty;
                textBox5.Text = string.Empty;
                textBox6.Text = string.Empty;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }


        }

        private void button2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

No comments:

Post a Comment