Sending e-mails with C# .NET 2.0

 

First step: Setting-up your SMTP (Simple Mail Transfer Protocol)

 

you must have installed IIS (internet information services), so you can setup your SMTP Virtual Server from there.

 

Control Panel->Administrative Tools->Internet Information Services , then you select the SMTP Virtual Server Properties and grant permission to local host (127.0.0.1) (Access->Relay).

 

Second Step: Writing the basic C# Code

 

Example: Windows Application

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Net;

using System.Net.Mail;

using System.Windows.Forms;

 

namespace Threading

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }       

    protected void Button1_Click(object sender, EventArgs e)

    {

        MailMessage objMM = new MailMessage();

        objMM.From = new MailAddress(textBox1.Text, “sender name”);

        objMM.To.Add(new MailAddress(textBox2.Text, “reciever name”));

        objMM.Subject = textBox3.Text;

        objMM.Body = richTextBox1.Text;

        SmtpClient objSC = new SmtpClient(“localhost”, 25);

        objSC.DeliveryMethod = SmtpDeliveryMethod.Network;

        objSC.Host = “smtp.gmail.com”; // for example gmail smtp server

        objSC.EnableSsl = true;

        objSC.Credentials = new System.Net.NetworkCredential(“mailid”, “password”);

        try

        {

            objSC.Send(objMM);

        }

        catch (Exception ex)

        {

            MessageBox.Show(ex.ToString());

        }

 

        MessageBox.Show(“Mail send successfully”);

    }       

    }

}

 

 

Be sure that the recipient checks his spam messages because many of the e-mails using this algorithm go there. Also don’t forget to include System.Net.Mail namespace (using System.Net.Mail ;).

 

Extra:

 

In .NET 1.1 you can use SmtpMail class (.NET1.1 does not support SmtpClient class) and be sure to include System.WEB.Mail.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: