Friday, August 14, 2009

Sending Mails with attachments using Gmail

Sending Mails with attachments using Gmail

Many times I came across the question that how can we send mails with some files as attachments and in continuation do we reaky need to buy some domain of our's to send mail or there is a domain using which we can send mails using gmail or yahoo or hotmail accounts. so the answer. So I decided to write this article which will help in solving the above quest.

Let answer First the above questions and then we will code how to send mails with attachments.
Question : Do we need our own domain to send mails?
Answer : No we do not necessarily need our own domain to send mails. Gmail
provides us free pop service and yahoo, hotmail and other mail engines charge for the service. Rather if we have our own domain that would be a benefit.
Question : Can we send files as an attachment?
Answer : Yes we can and even any extension of file can be send as attachment if server allows that as Gmail do not allow to send exe files rest you can send pdf,html,doc etc. any.
Question : Some Times our code is perfectly fine still we are not able to send mails ether we get error failed to send or could not connect to the server what may be the reasons?

Answer : The Reasons is very simple that we have some firewalls or the anti
virus installed on the system which prevents us to do so Specially Mac Fee prevents us sending the mails by blocking the port. The
Remedies is just off the antivirus for some time and then try sending the mail.

Requirements:

Development Machine Requirements
  1. Dotnet installed on the system VS2005 or above The Downloadable version comes for VS2008
  2. Files to attach with the mails
  3. Anti-Virus off while debugging the application
Client Side Requirements
  1. Dotnet Framework 2.0 or above in which the application is made
  2. Browser to run the Application
  3. Anti-Virus off while executing the application

Now lets start developing the application

  1. Create a web application with the name "SendMailWithAttachment". You can even use any name of your choice I am using this for my example.
  2. Add The Following code in the body tag of the Default.aspx page to genrate an interface for the aplication.
    <%@
    Page Language="C#"
    AutoEventWireup="true"
    CodeBehind="Default.aspx.cs"
    Inherits="SendMailWithAttachment._Default"
    %>


    <!DOCTYPE
    html PUBLIC
    "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


    <html
    xmlns="http://www.w3.org/1999/xhtml"
    >


    <head
    runat="server">


    <title>Send
    Mail Using Gmail Account With Attachments</title>
    </head>
    <body>
    <form id="Form1" method="post" runat="server">

<table borderColor="#339933" cellSpacing="0" cellPadding="4" width="55%" align="center" border="1">
<tr>
<td>
<table cellPadding="4" width="70%" align="center" border="0"> <tr bgColor="#339933"> <td align="center" colSpan="2"><asp:label id="lblHeader" Runat="server"
Font-Bold="True">Gmail Account Details for Sending Mails</asp:label></td>
</tr>
<tr>
<td vAlign="middle" align="right" width="40%">Username:</td> <td
vAlign="middle" width="60%">
<asp:TextBox
ID="txtUserName" runat="server" Font-Names="Verdana" Font-Size="X-Small"
Width="350px"></asp:TextBox>
</td>
</tr>
<tr>
<td vAlign="middle" align="right" width="40%">Password</td> <td
vAlign="middle" width="60%">
<asp:TextBox
ID="txtPassword" Font-Names="Verdana" Font-Size="X-Small"
Width="350px" runat="server" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr bgColor="#339933"> <td align="center" colSpan="2"><asp:label id="Label1" Runat="server"
Font-Bold="True">SMTP
Mail with Attachment</asp:label></td>

</tr>
<tr>
<td vAlign="middle" align="right" width="40%">From :</td> <td vAlign="middle"
width="60%"><asp:textbox id="txtSender"
tabIndex="1" runat="server" Font-Names="Verdana" Font-Size="X-Small"
Width="350px"></asp:textbox></td>
</tr>
<tr>
<td vAlign="middle" align="right">To :</td>
<td><asp:textbox id="txtReceiver" tabIndex="1"
runat="server" Font-Names="Verdana"
Font-Size="X-Small"
Width="350px"></asp:textbox></td>

</tr>
<tr>
<td vAlign="middle" align="right">Cc :</td>
<td><asp:textbox id="txtCc" tabIndex="1" runat="server"
Font-Names="Verdana" Font-Size="X-Small"
Width="350px"></asp:textbox></td>
</tr>
<tr>
<td vAlign="middle" align="right">Bcc :</td>
<td><asp:textbox id="txtBcc" tabIndex="1" runat="server"
Font-Names="Verdana" Font-Size="X-Small"
Width="350px"></asp:textbox></td>
</tr> <tr>
<td vAlign="middle" align="right">Subject :</td>
<td><asp:textbox id="txtSubject" tabIndex="2" runat="server" Font-Names="Verdana" Font-Size="X-Small"
Width="350px"></asp:textbox></td>

</tr>
<tr>
<td vAlign="middle" align="right">Format :</td>
<td><asp:radiobuttonlist id="rblMailFormat" tabIndex="3"
runat="server" repeatcolumns="2" repeatdirection="Horizontal">

<asp:ListItem Value="Text" Selected="True">Text</asp:ListItem>
<asp:ListItem Value="HTML">HTML</asp:ListItem>
</asp:radiobuttonlist></td>
</tr>
<tr>
<td vAlign="middle" align="right">Message :</td>
<td height="84"> <p><asp:textbox id="txtBody"
tabIndex="4" runat="server" Font-Names="Verdana" Font-Size="X-Small"
columns="40" rows="5" textmode="MultiLine" width="350px"></asp:textbox></p> </td>
</tr>
<tr>
<td vAlign="middle" align="right">Attachment :</td><td><input id="inpAttachment1" tabIndex="5" type="file" size="53" name="filMyFile" runat="server"></td> </tr>
<tr>
<td vAlign="middle" align="right">Attachment :</td>
<td><input id="inpAttachment2" tabIndex="6" type="file"
size="53" name="filMyFile" runat="server"></td>

</tr>
<tr>
<td vAlign="middle" align="right">Attachment :</td>
<td><input id="inpAttachment3" tabIndex="7" type="file"
size="53" name="filMyFile" runat="server"></td>

</tr>
<tr>
<td align="center" colSpan="2"><asp:button id="btnSend"
tabIndex="9" runat="server" width="100px" text="Send" onclick="btnSend_Click"></asp:button></td>

</tr>
<tr>
<td align="center" colSpan="2"><asp:Label ID="lblMessage"
Runat="server"></asp:Label>

</td>
</tr>
</table>
</td> </tr> </table>
</form>
</body>
</html>


  1. The Default.aspx will now look like:
  2. Now Let us code for the Functionality double Click on the button and the event handler is genrated for the buttonclick
    Before we start the code for the event let us include some namespaces:
    1. using System.Net.Mail;
    2. using System.IO;
    3. using System.Drawing;

      Here is the code for the button event. The code is having inline commets to explain the meamning of each line.

using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Net.Mail;
using
System.IO;
using
System.Drawing;

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

try
{
/* Create a new blank MailMessage with the from and to
adreesses*/

MailMessage mailMessage = new MailMessage txtSender.Text,txtReceiver.Text);
/*Checking the condition that the cc is empty or not if
not then * include them
*/

if (txtCc.Text != null && txtCc.Text != string.Empty)
{
mailMessage.CC.Add(txtCc.Text);
}
/*Checking the condition that the Bcc is empty or not
if not then
* include them
*/

if (txtBcc.Text != null && txtBcc.Text != string.Empty)
{
mailMessage.Bcc.Add(txtBcc.Text);
}
//Ading Subject to the Mail
mailMessage.Subject = txtSubject.Text;
//Adding the Mail Body
mailMessage.Body = txtBody.Text;
/* Set the properties of the MailMessage to the
values on the form as per the mail is HTML formatted or plain text */

if (rblMailFormat.SelectedItem.Text ==
"Text")
mailMessage.IsBodyHtml = false;
else
mailMessage.IsBodyHtml = true;
/* We use the following variables to keep track of
attachments and after we can delete them */

string attach1 = null;
string attach2 = null;
string attach3 = null;
/*strFileName has a attachment file name for
attachment process. */

string strFileName = null;
/* Bigining of Attachment1 process & Check the first open file dialog for a attachment */
if (inpAttachment1.PostedFile != null)
{
/* Get a reference to PostedFile object */
HttpPostedFile attFile = inpAttachment1.PostedFile;
/* Get size of the file */
int attachFileLength = attFile.ContentLength;
/* Make sure the size of the file is > 0 */
if (attachFileLength > 0)
{
/* Get the file name */
strFileName = Path.GetFileName(inpAttachment1.PostedFile.FileName);

/* Save the file on the server */
inpAttachment1.PostedFile.SaveAs(Server.MapPath(strFileName));
/* Create the email attachment with the uploaded file
*/
Attachment attach = new
Attachment(Server.MapPath(strFileName));
/* Attach the newly created email attachment */
mailMessage.Attachments.Add(attach);
/* Store the attach filename so we can delete it later
*/
attach1 = strFileName;
}
}
/* Attachment-2 Repeat previous step defiend above*/
if (inpAttachment2.PostedFile != null)
{
HttpPostedFile attFile = inpAttachment2.PostedFile;
int attachFileLength = attFile.ContentLength;
if (attachFileLength > 0)
{
strFileName = Path.GetFileName(inpAttachment2.PostedFile.FileName); inpAttachment2.PostedFile.SaveAs(Server.MapPath(strFileName));
Attachment attach = new Attachment(Server.MapPath(strFileName));
mailMessage.Attachments.Add(attach);
attach2 = strFileName;
}
}
/* Attachment-3 Repeat previous steps step defiend above*/
if (inpAttachment3.PostedFile != null)
{
HttpPostedFile attFile = inpAttachment3.PostedFile;
int attachFileLength = attFile.ContentLength;
if (attachFileLength > 0)
{
strFileName = Path.GetFileName(inpAttachment3.PostedFile.FileName); inpAttachment3.PostedFile.SaveAs(Server.MapPath(strFileName));
Attachment attach = new Attachment(Server.MapPath(strFileName));
mailMessage.Attachments.Add(attach);
attach3 = strFileName;
}
}
/* Set the SMTP server and send the email with attachment */
SmtpClient smtpClient = new SmtpClient();
// smtpClient.Host = emailServerInfo.MailServerIP;
//this will be the host in case of gamil and it varies from the service provider
smtpClient.Host = "smtp.gmail.com";
//smtpClient.Port = Convert.ToInt32 emailServerInfo.MailServerPortNumber);
//this will be the port in case of gamil for dotnet and
it varies from the service provider

smtpClient.Port = 587;
smtpClient.UseDefaultCredentials = true;
//smtpClient.Credentials = new
System.Net.NetworkCredential(emailServerInfo.MailServerUserName,
emailServerInfo.MailServerPassword);

smtpClient.Credentials = new System.Net.NetworkCredential(txtUserName.Text, txtPassword.Text);
//this will be the true in case of gamil and it varies
from the service provider

smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
/* Delete the attachements if any */
try{

if (attach1 != null)
File.Delete(Server.MapPath(attach1));
if (attach2 != null)
File.Delete(Server.MapPath(attach2));
if (attach3 != null)
File.Delete(Server.MapPath(attach3));

}
catch{}
/* clear the controls */
txtSender.Text = string.Empty;
txtReceiver.Text = string.Empty;
txtCc.Text = string.Empty;
txtBcc.Text = string.Empty;
txtSubject.Text = string.Empty;
txtBody.Text = string.Empty;
txtUserName.Text = string.Empty;
/* Dispaly a confirmation message to the user. */
lblMessage.Visible = true;
lblMessage.ForeColor = Color.Black;
lblMessage.Text = "Message sent.";
}
catch (Exception ex)
{
/* Print a message informing the user about the exception that was risen */
lblMessage.Visible = true;
lblMessage.ForeColor = Color.Red;
lblMessage.Text = ex.ToString();
}
}
}
}

Download code from here





Thanks and Regards

Meetu Choudhary

My Blog My Web My Forums

Thursday, August 6, 2009

Export Grid to Excel

Export to Excel

In this article we are going to read and understand how in a web application we can export a grid data in the excel file. As many times in real time programming we generate reports in the grid format to display to the user.

For example

1 .The list of commodities purchased this month

2. Reports of SMS Sent.

3. Reports of invites. etc.and user might want to save this list for the future use. In Excel format then we need to export this grid to the excel.

Prerequisites:

1. To view an Excel workbook file's contents, you must have installed Microsoft Excel (alone or with MS-Office) on your system.

2. Microsoft Visual Studio (VS) must be installed on the (I haven't tested it on the Prior versions)

Let's start with creating an application in VS2008 (You can even go for VS2005 or VS2010)

Following the steps to we are going to follow.

  1. Create a new project in VS2008 as name it as "ExporttoExcel" in the C# category.
  2. Place a gridview on the default.aspx page and rename it to grdtoexport.
  3. And place a button which will export the grid to excel.
  4. Now lets create a datatable which will bind the grid.

The Code will look like:

protected void Page_Load(object sender, EventArgs e)

{

//creating a table for the grid use namespace System.Data;

DataTable dt = new DataTable ();

//adding columns to the datatale

try

{

dt.Columns.Add("Srno");

dt.Columns.Add("Name");

}

catch { }

//adding values to the datatable

for (int i = 1; i <= 10; i++)

{

DataRow dr = dt.NewRow();

dr[0] = i;

dr[1] = "Meetu Choudhary " + i.ToString();

dt.Rows.Add(dr);

}

//binding databale to the grid

grdtoexport.DataSource = dt;

grdtoexport.DataBind();

}

Writing a ExportToExcel class

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data;

using System.Configuration;

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.Text;

using System.IO;

namespace ExportToExcel

{

/// <summary>

/// Summary description for ExportToExcel

/// </summary>

public class ExportToExcel

{

public ExportToExcel()

{

//

// TODO: Add constructor logic here

//

}

public void ExportGridView(GridView GridView1, String strFileName)

{

PrepareGridViewForExport(GridView1);

//string attachment = "attachment; filename=Contacts.xls";

HttpContext.Current.Response.ClearContent();

HttpContext.Current.Response.Buffer = true;

HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + strFileName);

HttpContext.Current.Response.ContentType = "application/ms-excel";

HttpContext.Current.Response.Charset = "";

//System.Web.UI.Page.EnableViewState = false;

StringWriter sw = new StringWriter();

HtmlTextWriter htw = new HtmlTextWriter(sw);

GridView1.RenderControl(htw);

HttpContext.Current.Response.Write(sw.ToString());

HttpContext.Current.Response.End();

}

private void PrepareGridViewForExport(Control gv)

{

LinkButton lb = new LinkButton();

Literal l = new Literal();

string name = String.Empty;

for (int i = 0; i < gv.Controls.Count; i++)

{

if (gv.Controls[i].GetType() == typeof(LinkButton))

{

l.Text = (gv.Controls[i] as LinkButton).Text;

gv.Controls.Remove(gv.Controls[i]);

gv.Controls.AddAt(i, l);

}

else if (gv.Controls[i].GetType() == typeof(DropDownList))

{

l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;

gv.Controls.Remove(gv.Controls[i]);

gv.Controls.AddAt(i, l);

}

else if (gv.Controls[i].GetType() == typeof(CheckBox))

{

l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";

gv.Controls.Remove(gv.Controls[i]);

gv.Controls.AddAt(i, l);

}

if (gv.Controls[i].HasControls())

{

PrepareGridViewForExport(gv.Controls[i]);

}

}

}

/*Use this commented function in all the pages where the above export function is used

//public override void VerifyRenderingInServerForm(Control control)

//{

//}*/

}

}

Calling the Function to export on button click

protected void btnexport_Click(object sender, EventArgs e)

{

ExportToExcel ex = new ExportToExcel();

ex.ExportGridView(grdtoexport, "Client.xls");

}



You can download the code from here


Regards, Meetu Choudhary
Microsoft MVP-ASP/ASP.NET

MsDnM My Forums My Blog

Monday, August 3, 2009

Progress Bar demo

Hi All,

I am Developing this Application just to help a newbie in the technology and even many of my students have asked me for the application which will demonstrate them how to use a progress bar in C#.net for a windows application. So here is a small application which will solve the purpose.

So Here Is the application and description how to develop the application.

1. Create a New Project in VS 2008 or above as per your convince I have installed VS 2008 so I am using that if you want to use VS 2005 you can even go with that also. For now VS2008


2. Create New Project : Select Windows Forms Application under the Visual C# tab and give the name to the project as prjProgressBar.

3. Now Place The ProgressBar Control and the Button Tool on the form from the tools box as shown in the figure below.

4. Set the following Properties of the progress bar:

  • Minimum =0 (By Default). This value will specify the lower bound for the progress bar.
  • Maximum =500 (Default value is 100). This is the upper bound value of the progress bar when progress is complete.
  • Step= 5 (Default is 10) This value is the value by which the progressbar will increase the current value with the next step when performstep function will be called. (in this case 500/5=100 i.e. in ten steps we will complete the progressbar.)
  • Value =0 (Default is 0) This will set or get the current value of the progressbar.
  • Style is the cosmetic property of the control default is blocks you may change it to marquee or continues. I am not changing it.
  • MarqueeanimationSpeed=100 (default is also 100): this is the speed in milisseconds set for the animation of the progressbar.

Now On the button click event we will start the progress bar and show a message at final step that in how many steps we have completed the progress bar. The code will be:

private void button1_Click(object sender, EventArgs e)
{
int i = 0;
while (progressBar1.Value < progressBar1.Maximum )
{
MessageBox.Show("Step : " + i);
}
}

>Now The above code I have written on the button click so you can write it at any place you needed. Suppose You want that as the data is begin added in the database then you need to perform a step in the database you can do that. But in that case you should set the maximum value of the progressbar to the total no. of records to be inserted and this will be set by the code at the event where you have calculated the total no. of records. with the help of this line.

progressBar1.Maximum=NoRecs;

and the step value should be 1 and when the insertion is completed in the database then use
progressBar1.PerformStep();
line of code there.

The Sample Code is attached.


Thanks and Regards
Meetu Choudhary
MVP || My Blog || MySite || My Forums

Thursday, July 30, 2009

How to use combo box in silverlight

After reading this article we will be able to use a comboobx in a Silverlight application as we are habitual of using it with the formal application. Normally we would like to have a combo box which will show the name of the article or any thing which we would like that our client should see but internally we like to use the ID the primary key or something else to use for the internal purpose. So here are the steps we are going to follow.

Creating the Design Page For the Combobox Application.
1. Open Visual Studio 2008 or above. Create new Project.
2. Select the language C#, Silverlight Project.
3.Name it Combox.
4.Click ok.
5.Leave the Rest Settings as default.
6.Now open MainPage.xaml. modify the grid add the HorizontalAlignment="Left"
VerticalAlignment="Top"
7. And now And now add the Textblock (Label) like this:
<TextBlock Height="17.09" Grid.Column="0" Grid.Row="0" Width="100.303" Canvas.Left="260" Canvas.Top="38.91" Text="Client Name" TextWrapping="Wrap"
Foreground
="#FF000000" FontSize="16" Margin="12,0,8,5" />
8. In the next column of grid Add the Combobox. like:
<ComboBox x:Name="cmbClient" Grid.Column="1" Grid.Row="0" SelectionChanged="cmbClient_SelectionChanged"></ComboBox>
9. Not going into more Designing Issues. Lets Finish it here. And Start Our Coding.
10. Creating a button so that onclick of that button we can get the
Information of the Client
<Button x:Name="btn" Click="btn_Click" Content="Get Info" Grid.Column="0" Grid.Row="1"></Button>

Now lets create a class with the following Member Properties
Client ID
Client Name
Client Address
Client Mobile number

Now open the MainPage.xaml.cs File And create the following Class
public class MyClients
{
#region Pubic Property
public int pkid;
public string ClientName { get; set; }
public string ClientAddress { get; set; }
public string ClientMobile { get; set; }
#endregion
}

In Next strep we will Creat a List<T> type of variables which will hold the List of MyClients to be displayed in the comboobx. Like:

public static List<MyClients> clientlist = new List<MyClients>();

Now next step is to create a function which will add the MyClients to the List Here is the function.

public voidAddClients()
{
MyClients mynewclient = new MyClients();
mynewclient.ClientAddress = "Jaipur";
mynewclient.ClientMobile = "1234567890";
mynewclient.ClientName = "Meetu Choudhary";
mynewclient.pkid = 1;
clientlist.Add(mynewclient);
//Adding 2nd CLient
mynewclient = newMyClients();
mynewclient.ClientAddress = "Jaipur";
mynewclient.ClientMobile = "1234567890";
mynewclient.ClientName = "Anita Choudhary";
mynewclient.pkid = 2;
clientlist.Add(mynewclient);
//Adding 3rd client
mynewclient = new MyClients();
mynewclient.ClientAddress = "Delhi";
mynewclient.ClientMobile = "1234567890";
mynewclient.ClientName = "Raman Mehta";
mynewclient.pkid = 3;
clientlist.Add(mynewclient);
//Adding 4th client
mynewclient = new MyClients();
mynewclient.ClientAddress = "Delhi";
mynewclient.ClientMobile = "1234567890";
mynewclient.ClientName = "Gaurav Arora";
mynewclient.pkid = 4;
clientlist.Add(mynewclient);
}

Now we need to call this function in the MainPage so the code of MainPage will now
look like
public MainPage()
{
InitializeComponent();
/*From here I added the code*/
AddClients();
//Telling the combobox which member to be displayed
cmbClient.DisplayMemberPath = "ClientName";
//Telling the Source of the List
cmbClient.ItemsSource = clientlist;
//This line will set the selected item
cmbClient.SelectedIndex = 1;
}

Now We will again declare a public static variable to access the object through out the page.
public static MyClients selectedcl;

Now setting the above variable on the selectionchanged event:
private void cmbClient_SelectionChanged(object sender,SelectionChangedEventArgs e)
{
selectedcl = (MyClients)cmbClient.SelectedItem;
}

and Finally the code for the click event:

private void btn_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Client Name : " + selectedcl.ClientName + Environment.NewLine
+ "Client Address : " + selectedcl.ClientAddress + Environment.NewLine
+ "Client Mobile : " + selectedcl.ClientMobile + Environment.NewLine
+ "ID : " + selectedcl.pkid);
}


Now run and see the combox in active Code is attached
Download Code

Subscribe via email

Enter your email address:

Delivered by FeedBurner

MSDotnetMentor

MSDotnetMentor My Website http://msdotnetmentor.com