Wednesday, January 26, 2011

Send Emails in C#.NET

Hi Guys,
Its been a while since i've written some articles on .NET . In this article we will see how to send emails from a C# piece of code.

There are lots of variation in code available on the web (to send emails) using different versions of .NET (2.0, 3.0, 3.5, etc) and lots of API has been deprecated over time. The following code has been tested on visual studio 2008 (C# 3.5)

The following code excerpt is from a Windows Form application that is used to send emails. Feel free to use the code in try block in the  private void button1_Click(object sender, EventArgs e) function in whatever application you might be interested in writing.

So, basically you need to import System.Net.Mail, use SmtpClient class constructor to initialize the connection (with smtp address and port) and set various parameters like ssl, initialize network credentials, etc.



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;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
           
                SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);
                mailClient.EnableSsl = true;
                System.Net.NetworkCredential cred = new System.Net.NetworkCredential("username", "password");
                mailClient.Credentials = cred;
                mailClient.Send("xxxx@gmail.com", "xxxx@gmail.com","subject goes here", "email body goes here"); //send(from_email_address, to_email_address, subject, email_text);
                MessageBox.Show("SUCCESS");
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.ToString());
            }
  
        }
    }
}


The code mentioned above is a tested one. Feel free to experiment with it and ask questions.

No comments:

Post a Comment