Send email with C# and SMTP

 

Used
Microsoft Visual studio 8 with .net 3.5

The Form

Create a form with:

6 x textBox
1 x label
1 x button

The Code
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;

using System.Net.Mail;
using System.Net;

namespace email
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            textBox1.Text = "emailFrom";
            textBox2.Text = "emailTo";
            textBox3.Text = "smtpUserName";
            textBox4.Text = "smtpPassword";
            textBox5.Text = "smtpServer";
            textBox6.Text = "smtpPort";
        }

        private void button1_Click(object sender, EventArgs e)
        {           
            //init
            string smtpEmailFrom = this.textBox1.Text.Trim();
            string smtpEmailTo = this.textBox2.Text.Trim();
            string smtpUserName = this.textBox3.Text.Trim();
            string smtpPassword = this.textBox4.Text.Trim();
            string smtpHost = this.textBox5.Text.Trim();
            int smtpPort = Convert.ToInt32(this.textBox6.Text.Trim());
           
            //mail
            MailAddress emailFrom = new MailAddress(smtpEmailFrom);
            MailAddress emailTo = new MailAddress(smtpEmailTo);
            MailMessage eMail = new MailMessage(emailFrom, emailTo);
           
            eMail.Subject = "test";
            eMail.Body = "test";

            //smtp
            SmtpClient sSmtp = new SmtpClient(smtpHost);
            sSmtp.Port = smtpPort;
            sSmtp.UseDefaultCredentials = false;
            sSmtp.Credentials = new NetworkCredential(smtpUserName, smtpPassword);

            try
            {
                sSmtp.Send(eMail);
            }
            catch (Exception ex)
            {
                label1.Text = ex.Message.ToString();
            }
        }
    }
}
 

 

www.programmingsystems.eu