How To Send Mail Using Visual Studio 10 Ado.net

How To Send Mail Using Visual Studio 10
Ado.net
Server Parameters
Server Name
SMTP Address
Port
SSL
Yahoo!
smtp.mail.yahoo.com
587
Yes
GMail
smtp.gmail.com
587
Yes
Hotmail
smtp.live.com
587
Yes
Sample Code
Hide   Shrink http://www.codeproject.com/images/arrow-up-16.png   Copy Code
using System.Net;
using System.Net.Mail;

string smtpAddress = "smtp.mail.yahoo.com";
int portNumber = 587;
bool enableSSL = true;

string emailFrom = "email@yahoo.com";
string password = "abcdefg";
string emailTo = "someone@domain.com";
string subject = "Hello";
string body = "Hello, I'm just writing this to say Hi!";

using (MailMessage mail = new MailMessage())
{
   mail.From = new MailAddress(emailFrom);
   mail.To.Add(emailTo);
   mail.Subject = subject;
   mail.Body = body;
   mail.IsBodyHtml = true;
   // Can set to false, if you are sending pure text.

   mail.Attachments.Add(new Attachment("C:\\SomeFile.txt"));
   mail.Attachments.Add(new Attachment("C:\\SomeZip.zip"));

   using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
   {
       smtp.Credentials = new NetworkCredential(emailFrom, password);
       smtp.EnableSsl = enableSSL;
       smtp.Send(mail);
   }
}

New mail
Introduction

Sending email is a very common task in any web application for many purposes. In daily development we need to add some mail functionality to our project to send e-mail to the customer or another in our web site.

Using the code

For sending mail from ASP.NET we use the "System.Net.Mail" namespace. Let's see how to do this.
  • Open Visual Studio 2010
  • "File" -> "New" -> "Project..."
  • Choose Visual C#- Web - Select ASP.NET Empty Web Application
  • Add a new aspx page
The following is the code for the design of the page.

Sendmail.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <table>
            <tr>
                <td>To : </td>
                <td>
                    <asp:TextBox ID="txtTo" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>Subject:      </td>
                <td>
                    <asp:TextBox ID="txtsubject" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td>Message:
                </td>
                <td>
                    <asp:TextBox ID="txtmessage" runat="server" TextMode="MultiLine" Height="99px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="Bttn_Send" runat="server" Text="Send" OnClick=" Bttn_Send _Click" />
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

In the code above we have the following 3 fields:
  • To
  • Subject
  • Message
When the user clicks the "Send" button, the mail will be sent to the specified mail address that you provide in the "txtTo" TextBox. So add the following code for the Button_Click.

SendMail.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using System.Net.Mail;
 
public void SendMail()
{
    mailMessage mail = new MailMessage();
    mail.To.Add(txtTo.Text);
    mail.From = new MailAddress("sourabh9303@gmail.com");
    mail.Subject = "Email using Gmail";
    string Body = txtmessage.Text;
    mail.Body = Body;
    SmtpClient smtp = new SmtpClient();
    smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
    smtp.Port = 587;
    smtp.UseDefaultCredentials = false;
    smtp.Credentials = new System.Net.NetworkCredential
    ("username", "password");

    //Or your Smtp Email ID and Password
    smtp.EnableSsl = true;
    smtp.Send(mail);
}
protected void Bttn_Send_Click(object sender, EventArgs e)
{
    SendMail();
}

Understanding the Code

In the code above we have a SendMail() userdefined method. In this method, we create an object of the MailMessage class.

MailMessage mail = new MailMessage();

MailMessage is the main class for sending mail, this is the part of the System.Net.Mail namespace.

The MailMessage class has properties, the important ones are:
  • To
  • From
  • Cc
  • Bcc
  • Subject
  • Body
So we add our data into specified properties.

mail.To.Add(txtTo.Text);
mail.From = new MailAddress("digisupp2@gmail.com");
mail.Subject = "Email using Gmail";
string Body = txtmessage.Text;
mail.Body = Body;

For sending mail we need a SMTP Server, so in ASP.Net we have the SmtpClient class, using that class object we set its properties for the SMTP settings.

SmtpClient smtp = new SmtpClient();

The SMTPClient class has these basic properties:
  • Host
  • Port
  • UseDefaultCredential
  • Credentials
  • EnableSsl
  • Send
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential("username""password");
smtp.EnableSsl = true;

Here in the code above smtp.Host = "smtp.gmail.com"; This is the SMTP Host address of Gmail, if you want to use any other SMTP host service please add a different SMTP host protocol, for example for Hotmail it is smtp.live.com.

Smtp.Port=587 , 587 is the port for Gmail, so for any other service port you have to change the port correspondingly.

smtp.Credentials = new System.Net.NetworkCredential("username""password");

Smtp.Credentials specifies the Network Crendentials of your Gmail id so please add your username and password instead of ("username""password");
The following is for a secure mail server, so you enable your SSL layer.

smtp.EnableSsl = true;

Smtp.Send sends the mail so please add your MailMesssage object here, based on properties, your mail will be sent. See:
Smtp.Send(mail);

ntroduction
In my previous article I told you about How to Send Bulk Mail Using SMTP Configuration. In that article I sent the emails using Gmail credentials, if you try to send an email using your Yahoo or Hotmail credential then an error message will be shown because you need a different configuration for both Yahoo and Hotmail.
In this article I will tell you about how to send bulk email from Yahoo and Hotmail using ASP.NET.
Step 1
First of all you need to add some namespaces to your application, which are as follows:
using System.Configuration;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Data;
using System.Data.OleDb;
Step 2
After adding these namespaces you need to add a Grid View and a button to your application, write this code in the .aspx page:
    <div>
        <asp:Button ID="king" runat="server" Text="Show all the Members" OnClick="king_Click" />     
        <asp:Label ID="kinglbl" runat="server" Text="Total Members: "></asp:Label>
        <asp:Label ID="Label2" runat="server" ForeColor="Red" Font-Size="Larger"></asp:Label>
        <br />
        <br />
        <asp:Button ID="Sendbtn" runat="server" Text="Send" OnClick="Sendbtn_Click"  />
        <asp:Label ID="cnfrm" runat="server"></asp:Label>
        <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="Both">
            <AlternatingRowStyle BackColor="White" />
            <EditRowStyle BackColor="#7C6F57" />
            <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#E3EAEB" />
            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#F8FAFA" />
            <SortedAscendingHeaderStyle BackColor="#246B61" />
            <SortedDescendingCellStyle BackColor="#D4DFE1" />
            <SortedDescendingHeaderStyle BackColor="#15524A" />
        </asp:GridView>
    </div>
Here I took two buttons, the click of the first button will show the person's name and their MailIds in the Grid View, the click of the second button will send the mail.
Step 3
Now you need to create a database of people to whom email needs to be sent, you can create the database in SQL, Access, Excel, Oracle or any other database depending on your needs. The main thing is you must know how to bind them with an ASP.NET application and how to show their data in a Grid. I have created an Excel Sheet in which more then 60 users have been entered.
After creating the database, now it's time to bind it to our application, write this code on the click of the first button:
        protected void king_Click(object sender, EventArgs e)
        {
            OleDbConnection con=new OleDbConnection("
provider=microsoft.ace.oledb.12.0;data source=E:\\mail.xls;extended properties =excel 12.0");
            con.Open();
            OleDbCommand cmd = new OleDbCommand("Select Email,Name from [sheet1$]", con);
            OleDbDataAdapter adp = new OleDbDataAdapter(cmd);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
            Label2.Text = GridView1.Rows.Count.ToString();
            con.Close();
        }
Here I simply created a connection in which the path of the Excel Sheet is provided, after that I fetched the name and Email Id of the users and then shown them in a Grid.
Step 4
Now I will show how to send email using Yahoo Credentials, write this code on the click of the second button:
        protected void Sendbtn_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow grow in GridView1.Rows)
            {
                string Emails = grow.Cells[0].Text.Trim();

                string file = Server.MapPath("~/Mail.html");
                string mailbody = System.IO.File.ReadAllText(file);
                string to = Emails;
                string from = "xyz@yahoo.com";
                MailMessage msg = new MailMessage(from, to);
                msg.Subject = "Auto Response Email";
                msg.Body = mailbody;
                msg.BodyEncoding = Encoding.UTF8;
                msg.IsBodyHtml = true;
                SmtpClient client = new SmtpClient("smtp.mail.yahoo.com", 25);
                System.Net.NetworkCredential basicCredential = new System.Net.NetworkCredential("xyz@yahoo.com""YourPassword");
                client.EnableSsl = true;
                client.UseDefaultCredentials = true;
                client.Credentials = basicCredential;
                try
                {
                    client.Send(msg);
                    cnfrm.Text = "Email Sended Successfully";
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
            }
        }
This code will work for each row in the Grid.
Here I took a variable whose name is Emails, in this variable the first column of our Excel sheet is bound; that's because in the first column I provided the Email Id of the users.
After this the path of the file whose content is to be sent in all the mails is provided in a variable named file.
After this all the Email Id are passed into "to" and your mail Id can be passed into "from".
Now the main thing is "SmtpClient", while we were working on a Gmail account we have usedSmtpClient="smtp.gmail.com" but for Yahoo it is changed to "smtp.mail.yahoo.com". This is the thing that will help you send the mail using Yahoo credentials.
The Port number is "25", if you are using this application on your server and not locally then the port number will changed to 587.
After this you need to provide your Yahoo Mail Id and it's password.
Step 5
If you want to send email using a Hotmail Account then SmtpClient should be "smtp.live.com".
Now our application is ready for execution.
Output
On running the application you will get an output like this one:
Send Bulk Email from Yahoo and Hotmail Using ASP.NET
Here simply two buttons and a label can be seen.
Now when I click on the first button, output like this can be seen:
Send Bulk Email from Yahoo and Hotmail Using ASP.NET
Now I clicked on the Send button and you can see I am getting the mail in my Gmail Account:
Send Bulk Email from Yahoo and Hotmail Using ASP.NET
You can also check the mail Id from where I had sent the mail:
Send Bulk Email from Yahoo and Hotmail Using ASP.NET
The complete code of this application is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Configuration;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Data;
using System.Data.OleDb;

namespace WebApplication64
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void king_Click(object sender, EventArgs e)
        {
            OleDbConnection con=new OleDbConnection("provider=microsoft.ace.oledb.12.0;data source=E:\\mail.xls;extended properties =excel 12.0");
            con.Open();
            OleDbCommand cmd = new OleDbCommand("Select Email,Name from [sheet1$]", con);
            OleDbDataAdapter adp = new OleDbDataAdapter(cmd);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
            Label2.Text = GridView1.Rows.Count.ToString();
            con.Close();
        }
        protected void Sendbtn_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow grow in GridView1.Rows)
            {
                string Emails = grow.Cells[0].Text.Trim();

                string file = Server.MapPath("~/Mail.html");
                string mailbody = System.IO.File.ReadAllText(file);
                string to = Emails;
                string from = "xyz@yahoo.com";
                MailMessage msg = new MailMessage(from, to);
                msg.Subject = "Auto Response Email";
                msg.Body = mailbody;
                msg.BodyEncoding = Encoding.UTF8;
                msg.IsBodyHtml = true;
                SmtpClient client = new SmtpClient("smtp.mail.yahoo.com", 25);
                System.Net.NetworkCredential basicCredential = new System.Net.NetworkCredential("xyz@yahoo.com""YourPassword");
                client.EnableSsl = true;
                client.UseDefaultCredentials = true;
                client.Credentials = basicCredential;
                try
                {
                    client.Send(msg);
                    cnfrm.Text = "Email Sended Successfully";
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
            }
        }

Sending Email with System.Net.Mail

Sunday, December 11, 2005
.NET 2.0 includes much richer Email API support within the System.Net.Mail code namespace.  I've seen a few questions from folks wondering about how to get started with it.  Here is a simple snippet of how to send an email message from “sender@foo.bar.com” to multiple email recipients (note that the To a CC properties are collections and so can handle multiple address targets):

MailMessage message = new MailMessage();
message.From = new MailAddress("sender@foo.bar.com");

message.To.Add(new MailAddress("recipient1@foo.bar.com"));
message.To.Add(new MailAddress("recipient2@foo.bar.com"));
message.To.Add(new MailAddress("recipient3@foo.bar.com"));

message.CC.Add(new MailAddress("carboncopy@foo.bar.com"));
message.Subject = "This is my subject";
message.Body = "This is the content";

SmtpClient client = new SmtpClient();
client.Send(message);

System.Net.Mail reads SMTP configuration data out of the standard .NET configuration system (so for ASP.NET applications you’d configure this in your application’s web.config file).  Here is an example of how to configure it:

  <system.net>
    <mailSettings>
      <smtp from="test@foo.com">
        <network host="smtpserver1" port="25" userName="username" password="secret"defaultCredentials="true" />
      </smtp>
    </mailSettings>
  </system.net>

Hope this helps,

Scott

P.S. Many thanks to Federico from my team for putting the above sample together.

aspx
Message from: <asp:TextBox ID="text1" runat="server"></asp:TextBox>
Message To: <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
Message subject: <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="b1" runat="server" OnClick="click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
.aspx.cs
public void click(object sender, EventArgs e)
{
   try
   {
       //mail message
       MailMessage mM = new MailMessage();
       //Mail Address
       mM.From = new MailAddress( text1.Text);
       //emailid to send
       mM.To.Add(TextBox1.Text);
       //your subject line of the message
       mM.Subject = "your subject line will go here.";
       //now attached the file
       //mM.Attachments.Add(new Attachment(@"C:\\attachedfile.jpg"));
       //add the body of the email
       mM.Body = "Your Body of the email.";
       mM.IsBodyHtml = false;
       //SMTP
       SmtpClient SmtpServer = new SmtpClient();
       //your credential will go here
       SmtpServer.Credentials = new System.Net.NetworkCredential("sender@yahoo.com", "password");
       //port number to login yahoo server
       SmtpServer.Port = 587;
       //yahoo host name
       SmtpServer.Host = "smtp.mail.yahoo.com";
       SmtpServer.Send(mM);
       Label1.Text = "successfull";
       //Send the email

   }//end of try block
   catch (Exception ex)
   {
   }//end of catch
}//end of Yahoo Email Method


No comments:

Post a Comment

Thank You For Your Great Contribution

Featured Post

how to find n number of nodes have child or cildren

 how to find n number of nodes have child or cildren for that we use recursive function  const   data = {     'id' : '0' ,...

Popular Posts