ASp.Net day

Micro blog



About Satalaj

www.satalaj.com

The best inline translator

Live lookup to see what asp.net developers are searching





email delay       by Satalaj 5. January 2010 09:55
    

 I am using system.net.mail class to send mails from asp.net.
When i am sending mails the mails are sent although but the delivery is delayed. I am getting mails after 30 - 40 minutes.
Do you know what would be the reason,
  In this scenario you need to talk to your Network Administrator or ISP (Internet services provider) . If you are using Shared hosting / dedicated hosting
you need to open support ticket with them. If they fail to answer warn them; you will terminate their services. And look for another host.

Satalaj

     

Gridview select email       by Satalaj 28. October 2009 11:06
     Here I will select multiple rows of gridview containg email addresses to send an email.

The complete source can be downloded from here:
Gridview_send_email.zip (4.02 kb)


Here is .aspx source code:
         <asp:TextBox ID="txtSubject" runat="server"></asp:TextBox><br />
        <br />
        <table>
            <tr>
                <td style="width: 280px">
                    Email body:</td>
                <td style="width: 163px">
                    Select Recipients</td>
            </tr>
            <tr>
                <td style="width: 280px" valign="top">
                    <asp:TextBox ID="TextBox1" runat="server" Height="184px" TextMode="MultiLine" Width="368px"></asp:TextBox>
                    <asp:Button ID="Button3" runat="server" OnClick="Button3_Click" Text="send" /></td>
                <td style="width: 163px">
                    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
                        ForeColor="#333333" GridLines="None" DataKeyNames="Email">
                        <Columns>
                            <asp:TemplateField HeaderText="Sr.No.">
                                <ItemTemplate>
                                    <%# Container.DataItemIndex+1 %>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="First Name">
                                <ItemTemplate>
                                    &nbsp;<asp:Label ID="lblFirstName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"FirstName") %>'></asp:Label><br />
                                    <asp:TextBox ID="txtFirstName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"FirstName") %>'
                                        Visible="False"></asp:TextBox>
                                </ItemTemplate>
                                <FooterTemplate>
                                    <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
                                </FooterTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Last Name">
                                <ItemTemplate>
                                    <asp:Label ID="lblLastName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"LastName") %>'></asp:Label>
                                    <br />
                                    <asp:TextBox ID="txtLastName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"LastName") %>'
                                        Visible="False"></asp:TextBox>
                                </ItemTemplate>
                                <FooterTemplate>
                                    <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
                                </FooterTemplate>
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtLastName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"LastName") %>'></asp:TextBox>
                                </EditItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Email">
                                <ItemTemplate>
                                    <asp:Label ID="lblEmail" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"Email") %>'></asp:Label>
                                    <asp:TextBox ID="txtEmail" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"Email") %>'
                                        Visible="False"></asp:TextBox>
                                </ItemTemplate>
                                <FooterTemplate>
                                    <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
                                </FooterTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Check All">
                                <HeaderTemplate>
                                    <asp:CheckBox ID="chkAll" runat="server" AutoPostBack="True" OnCheckedChanged="chkAll_CheckedChanged" />
                                </HeaderTemplate>
                                <ItemTemplate>
                                    <asp:CheckBox ID="chkItem" runat="server" />
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                        <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                        <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
                        <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
                        <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
                        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                        <AlternatingRowStyle BackColor="White" />
                    </asp:GridView>
                </td>
            </tr>
        </table>

C#.Net code behind

GridView1.DataKeys[gr.RowIndex]["Email"].ToString()

For using DataKeys you need to add dataKeys to your gridview. you can add multiple dataKeys to your gridview separated by ",".

e.g.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
                        ForeColor="#333333" GridLines="None" DataKeyNames="Email">


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

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


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

        if (!Page.IsPostBack)
        {
            BindGrid();
        }
    }

    private void BindGrid()
    {
        GridView1.DataSource = GridDataProvider.GetData();

        GridView1.DataBind();

    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        GridView1.ShowFooter = true;
        BindGrid();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {

    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow gr in GridView1.Rows)
        {
            TextBox t = (TextBox)gr.FindControl("txtFirstName");
            TextBox tLastName = (TextBox)gr.FindControl("txtLastName");
            TextBox tEmail = (TextBox)gr.FindControl("txtEmail");
            Label lFirstName = (Label)gr.FindControl("lblFirstName");
            Label lLastName = (Label)gr.FindControl("lblLastName");
            Label lEmail = (Label)gr.FindControl("lblEmail");

            if (t.Visible)
            {
                t.Visible = false;
                tLastName.Visible = false;
                tEmail.Visible = false;
                lFirstName.Visible = true;
                lLastName.Visible = true;
                lEmail.Visible = true;
            }
            else
            {
                t.Visible = true;
                tLastName.Visible = true;
                tEmail.Visible = true;
                lFirstName.Visible = false;
                lLastName.Visible = false;
                lEmail.Visible = false;

            }


        }
    }
    protected void LinkButton2_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow gr in GridView1.Rows)
        {
            TextBox t = (TextBox)gr.FindControl("txtFirstName");
            TextBox tLastName = (TextBox)gr.FindControl("txtLastName");
            TextBox tEmail = (TextBox)gr.FindControl("txtEmail");
            Label lFirstName = (Label)gr.FindControl("lblFirstName");
            Label lLastName = (Label)gr.FindControl("lblLastName");
            Label lEmail = (Label)gr.FindControl("lblEmail");

            // Call your SQL server Data Access layer to save appropriate fields.

        }

    }
   

    protected void chkAll_CheckedChanged(object sender, EventArgs e)
    {
       
       
        foreach(GridViewRow gr in GridView1.Rows)
        {
            CheckBox cb = (CheckBox)gr.FindControl("chkItem");
            if(((CheckBox)sender).Checked)
             cb.Checked = true;
                else
             cb.Checked = false;
        }
       

       
    }


    protected void Button3_Click(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();

        foreach(GridViewRow gr in GridView1.Rows)
        {
            CheckBox cb = (CheckBox)gr.FindControl("chkItem");
            if(cb.Checked)
            {
                sb.Append(GridView1.DataKeys[gr.RowIndex]["Email"].ToString());
                sb.Append(",");
            }
        }
       
        MailMessage msg = new MailMessage("
mailto:your_hotmail_id@hotmail.com%22,sb.ToString());
        msg.Subject = txtSubject.Text;
        SmtpClient sc = new SmtpClient("smtp.live.com",25);
        sc.Credentials = new NetworkCredential("
mailto:your_hotmail_id@hotmail.com%22,%22Your_password");
        sc.EnableSsl = true;
        try
        {
        sc.Send(msg);
            Response.Write("<B>Email Has been sent successfully.</B>");
        }
        catch(Exception ex)
        {
            Response.Write(ex.Message);
        }
       

    }
}

Vb.Net code

Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls

Imports System.Net.Mail
Imports System.Text
Imports System.Net


Public Partial Class _Default
 Inherits System.Web.UI.Page
 Protected Sub Page_Load(sender As Object, e As EventArgs)

  If Not Page.IsPostBack Then
   BindGrid()
  End If
 End Sub

 Private Sub BindGrid()
  GridView1.DataSource = GridDataProvider.GetData()

  GridView1.DataBind()

 End Sub
 Protected Sub Button2_Click(sender As Object, e As EventArgs)
  GridView1.ShowFooter = True
  BindGrid()
 End Sub
 Protected Sub Button1_Click(sender As Object, e As EventArgs)

 End Sub
 Protected Sub LinkButton1_Click(sender As Object, e As EventArgs)
  For Each gr As GridViewRow In GridView1.Rows
   Dim t As TextBox = DirectCast(gr.FindControl("txtFirstName"), TextBox)
   Dim tLastName As TextBox = DirectCast(gr.FindControl("txtLastName"), TextBox)
   Dim tEmail As TextBox = DirectCast(gr.FindControl("txtEmail"), TextBox)
   Dim lFirstName As Label = DirectCast(gr.FindControl("lblFirstName"), Label)
   Dim lLastName As Label = DirectCast(gr.FindControl("lblLastName"), Label)
   Dim lEmail As Label = DirectCast(gr.FindControl("lblEmail"), Label)

   If t.Visible Then
    t.Visible = False
    tLastName.Visible = False
    tEmail.Visible = False
    lFirstName.Visible = True
    lLastName.Visible = True
    lEmail.Visible = True
   Else
    t.Visible = True
    tLastName.Visible = True
    tEmail.Visible = True
    lFirstName.Visible = False
    lLastName.Visible = False

    lEmail.Visible = False


   End If
  Next
 End Sub
 Protected Sub LinkButton2_Click(sender As Object, e As EventArgs)
  For Each gr As GridViewRow In GridView1.Rows
   Dim t As TextBox = DirectCast(gr.FindControl("txtFirstName"), TextBox)
   Dim tLastName As TextBox = DirectCast(gr.FindControl("txtLastName"), TextBox)
   Dim tEmail As TextBox = DirectCast(gr.FindControl("txtEmail"), TextBox)
   Dim lFirstName As Label = DirectCast(gr.FindControl("lblFirstName"), Label)
   Dim lLastName As Label = DirectCast(gr.FindControl("lblLastName"), Label)

    ' Call your SQL server Data Access layer to save appropriate fields.

   Dim lEmail As Label = DirectCast(gr.FindControl("lblEmail"), Label)
  Next

 End Sub


 Protected Sub chkAll_CheckedChanged(sender As Object, e As EventArgs)


  For Each gr As GridViewRow In GridView1.Rows
   Dim cb As CheckBox = DirectCast(gr.FindControl("chkItem"), CheckBox)
   If (DirectCast(sender, CheckBox)).Checked Then
    cb.Checked = True
   Else
    cb.Checked = False
   End If
  Next

 End Sub


 Protected Sub Button3_Click(sender As Object, e As EventArgs)
  Dim sb As New StringBuilder()

  For Each gr As GridViewRow In GridView1.Rows
   Dim cb As CheckBox = DirectCast(gr.FindControl("chkItem"), CheckBox)
   If cb.Checked Then
    sb.Append(GridView1.DataKeys(gr.RowIndex)("Email").ToString())
    sb.Append(",")
   End If
  Next

  Dim msg As New MailMessage("your_hotmail_id@hotmail.com", sb.ToString())
  msg.Subject = txtSubject.Text
  Dim sc As New SmtpClient("smtp.live.com", 25)
  sc.Credentials = New NetworkCredential("
your_hotmail_id@hotmail.com", "Your_password")
  sc.EnableSsl = True
  Try
   sc.Send(msg)
   Response.Write("<B>Email Has been sent successfully.</B>")
  Catch ex As Exception
   Response.Write(ex.Message)
  End Try


 End Sub
End Class

'=======================================================
'Service provided by Telerik (
http://www.telerik.com/)
'Conversion powered by NRefactory.
'Built and maintained by Todd Anglin and Telerik
'=======================================================


For demo purpost I used hotmail smtp, you can use your own smtp to send customised emails.







Satalaj
     

ASP.net read email hotmail       by Satalaj 29. September 2009 12:54
     kick it on DotNetKicks.com


    Days ago I come across the post saying hotmail is offering pop3. So I re-written my previos read gmail pop3 code to see how it works with hotmail.
This article will read your first hotmail email.  I have explained the commands that we can use with POP3.
I'm using ASP.net with C#.net and TcpIPClient to read email.
I saw many developers are searching for the code to read an email programatically.

I have created test user to use below code.

UserName:
satalajmore@hotmail.com
password:
Passw@rd


using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.IO;

using System.Net.NetworkInformation;

using System.Net.Security;

using System.Net.Sockets;

public partial class pop : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

}

protected void Button1_Click(object sender, EventArgs e)

{

try

{

// create an instance of TcpClient

TcpClient tcpclient = new TcpClient();

// HOST NAME POP SERVER and gmail uses port number 995 for POP

tcpclient.Connect("pop3.live.com", 995);

// This is Secure Stream // opened the connection between client and POP Server

System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream());

// authenticate as client

sslstream.AuthenticateAsClient("pop3.live.com");

//bool flag = sslstream.IsAuthenticated; // check flag

// Asssigned the writer to stream

System.IO.StreamWriter sw = new StreamWriter(sslstream);

// Assigned reader to stream

System.IO.StreamReader reader = new StreamReader(sslstream);

// refer POP rfc command, there very few around 6-9 command

sw.WriteLine("USER satalajmore@hotmail.com");

// sent to server

sw.Flush();

sw.WriteLine("PASS Passw@rd");

sw.Flush();

// RETR 1 will retrive your first email.

// It will read content of your first email.

sw.WriteLine("RETR 1");

sw.Flush();

// close the connection

sw.WriteLine("Quit ");

sw.Flush();

string str = string.Empty;

string strTemp = string.Empty; while ((strTemp = reader.ReadLine()) != null)

{

// find the . character in line

if (strTemp == ".")

{

break;

}

if (strTemp.IndexOf("-ERR") != -1)

{

break;

}

str += strTemp;

}

Response.Write(str);

Response.Write("<BR>" + "Congratulation.. ....!!! You read your first hotmail email ");

}

catch (Exception ex)

{

Response.Write(ex.Message);

}

}

}

Note* there are very few commands required to communicate with pop3 server.

You can use below commands to perform the operations on your pop3 server.

For more details about below command please refer RFC
http://www.ietf.org/rfc/rfc1939.txt 
 

 e.g.

1. LIST 
2.
RETR
3. 
STAT
4.
USER
5.
PASS
6.
DELE
7. QUIT


You can use above command instead of RETR

sw.WriteLine("STAT 1");

sw.Flush();


I'm using System.Net.Security.SslStream becaus hotmail accepts secure socket.


-Satalaj

     

C# Send email       by Satalaj 1. June 2009 11:10
    

Send email using your SMTP and SMTP credentials. Here is code for snding email.


 protected void Button6_Click(object sender, EventArgs e)

 { 
    System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();  
    // instantiate message object System.Net.Mail.
    MailAddress address = new System.Net.Mail.MailAddress("from.mail@mail.com","From Mail display name");
    msg.From = address;
    msg.To.Add(
satalaj.more@sat.com);
    msg.Subject = "HELLO TEST";msg.Body = "HELLO SDFSF";
    System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();  
    // instantiate smtp object sc.Host = "my_SMTP_address";  
    // your smtp host
    sc.Port = 25;  // your smtp port
    System.Net.NetworkCredential nc = new System.Ne t.NetworkCredential(); 
    // your network credentials object
    nc.UserName =
your.name@yourdomain;
    nc.Password = "pasword";
    sc.Credentials = nc;     // pass network credentials to smtp
    sc.Send(msg);  / / paas message to smtp  and send and email.
}