Friday, February 01, 2008

C#.NET Code to send mail

C#.NET Code to send mail

This article covres following things

  1. Send mail using C#.NET 2.0
  2. Send mail using .NET 1.1 or below version
  3. Send mail using ASP (CDONET)
  4. Domain Validation
  5. Account Validation
  6. Email Address Validation (client side and server side both)

1. Send mail using C#.NET 2.0

In .NET 2.0 we can use new library system.Net.Mail, it provide configuration feature for mail setting. It is reliable and fast. Use following method to send mail.

Namespace

using System.Net.Mail;

C# Code

private bool SendMails(string fromEmailId)

{

try

{ string msgBody = string.Empty;

// Instantiate a new instance of MailMessage

MailMessage mMailMessage = new MailMessage();

// Set the sender address of the mail message

mMailMessage.From = new MailAddress(fromEmailId);

// Set the recepient address of the mail message

mMailMessage.To.Add(new MailAddress("ToEmailId"));

//Get subject from config file

mMailMessage.Subject = "MailSubject";

//encode subject optional

mMailMessage.SubjectEncoding = System.Text.Encoding.UTF8;

//Build Message body based on AccessPtypes

msgBody = BuildMessageBody(reqAccessPtypes);

// Set the body of the mail message

mMailMessage.Body = msgBody;

//encode body optional

mMailMessage.BodyEncoding = System.Text.Encoding.UTF8;

// Set the format of the mail message body as HTML

mMailMessage.IsBodyHtml = true;

// Set the priority of the mail message to normal

mMailMessage.Priority = MailPriority.Normal;

//Set attach files need to send optional

mMailMessage.Attachments.Add(new Attachment("C:\\test.pdf"));

// Instantiate a new instance of SmtpClient

SmtpClient mSmtpClient = new SmtpClient();

// Send the mail message

mSmtpClient.Send(mMailMessage);

}

catch (Exception ex)

{

return false;

}

return true;

}

Setting in web.config

<configuration>

<!-- Require settings to send email from this application -->

<system.net>

<mailSettings>

<smtp from="defaultEmail@yourdomain.com">

<network host="127.0.0.1" port="25" userName="yourUserName" password="yourPassword"/>

</smtp>

</mailSettings>

</system.net>

</configuration>

2. Send mail using .NET 1.1 or below version

Using .NET 1.1 or below version we use library System.Web.Mail, here also you can make mail setting configurable, write all setting in web.config file in AppSettings section. This library method now become obsolete in .NET 2.0 and above version. Use following method to send mail.

Namespace

using System.Web.Mail;

C# Code

private void SendMails(string fromEmailId)

{

try

{

// Instantiate a new instance of MailMessage

MailMessage msg = new MailMessage();

// Set the sender address of the mail message

msg.From = fromEmailId;

// Set the recepient address of the mail message

msg.To = "ToEmailId";

//Get subject from config file

msg.Subject = "MailSubject";

//Build Message body based on AccessPtypes

msg.Body = "Mail Body Text";

// Set the format of the mail message body as HTML

msg.BodyFormat = MailFormat.Html;

//set SMTPServer configuration IP address

SmtpMail.SmtpServer = "SMTPServer";

//send mail

SmtpMail.Send(msg);

}

catch (Exception ex)

{

throw ex;

}

}

3. Send mail using ASP (CDONET)

CDONTS (Collaborative Data Objects for Windows NT Server) provides you with objects and classes that enable you to send email from an ASP page. CDONTS only works on Windows NT/2000 Operating Systems. It supports following feature

  1. send email in HTML Format
  2. set email priority
  3. use the Carbon Copy(CC) and Blind Carbon Copy(BCC) functions as in any email client,
  4. attach files while sending email

You can use following code in ASP page to send mail

<%
Set Mail=Server.CreateObject("CDONTS.NewMail")
Mail.To="me@mydomain.com"
Mail.From="testing-my@SP-Script.com"
Mail.Subject="Just testing my script"
Mail.Body="This is test mail."
Mail.Send
Set Mail=nothing
%>

4. Domain Validation

After sending a mail we need to validate for domain as well as account whether "To" or "From" mail id and domain are valid or not, it can be validate from .NET code using System.Net.Sockets.

Note: Use of sockets requires a trust level above the default "Medium".

Namespace

using System.Net;

using System.Net.Sockets;

C# Code

string email = "recipient@domain.com";

string[] host = email.Split('@');

string hostName = host[1];

Socket socket;

try

{

IPHostEntry entry = Dns.GetHostEntry(hostName);

IPEndPoint endPoint = new IPEndPoint(entry.AddressList[0], 25);

socket = new Socket(endPoint.AddressFamily, SocketType.Stream,

ProtocolType.Tcp);

socket.Connect(endPoint);

}

catch (SocketException ex)

{

// Invalid email.

}

5. Account Validation

if (!CheckSmtpResponse(SmtpResponse.CONNECT_SUCCESS))

{ // invalid account }

//test TEST server

SendData(string.Format("TEST {0}\r\n", Dns.GetHostName()));

if (!CheckSmtpResponse(SmtpResponse.GENERIC_SUCCESS))

{ // invalid account }

//test for sender domain on blacklist

SendData(string.Format("MAIL From: {0}\r\n", _SenderEmail));

if (!CheckSmtpResponse(SmtpResponse.GENERIC_SUCCESS))

{ // invalid account }

//test send

SendData(string.Format("MAIL TO: {0}\r\n", email));

if (!CheckSmtpResponse(SmtpResponse.GENERIC_SUCCESS))

{ // invalid account }

//account is valid!

//utility funtions:

void SendData(string message)

{

byte[] bytes = System.Text.Encoding.ASCII.GetBytes(message);

socket.Send(bytes, 0, bytes.Length, SocketFlags.None);

}

enum SmtpResponse : int {

CONNECT_SUCCESS = 220,

GENERIC_SUCCESS = 250,

DATA_SUCCESS = 354,

QUIT_SUCCESS = 221

}

bool CheckSmtpResponse(SmtpResponse code) {

string responseString;

int responseCode;

byte[] bytes = new byte[1024];

while (socket.Available == 0) {

System.Threading.Thread.Sleep(100);

}

socket.Receive(bytes, socket.Available, SocketFlags.None);

responseString = System.Text.Encoding.ASCII.GetString(bytes);

responseCode = Convert.ToInt32(responseString.Substring(0, 3));

return responseCode.Equals(Convert.ToInt32(code));

}

6. Email Address Validation

Namespace

using System.Text.RegularExpressions;

C# Code

private bool EmailAddressIsValid(string email)

{

string regExPattern = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +

@"\.[0-9]{1,3}\.[0-9]{1,3}\.)(([a-zA-Z0-9\-]+\" +

@".)+))([a-zA-Z]{2,4}[0-9]{1,3})(\]?)$";

Regex regEx = new Regex(regExPattern);

return regEx.IsMatch(email);

}

JavaScript Code

For the client side email validation you can use following javascript function

//Validates the email address given.

var strEmailValidationRegExp = /^([a-zA-Z0-9_\-\.]+)@((\[?[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\]?)(([a-zA-Z0-9\-]+\.)+)([a-zA-Z]{2,4}))$/;

function ValidateEmailAddress()

{

var strEmailToValidate = document.getElementById('txtEmailAddress').value;

//Valid characters allowed in the id.

var regExp = new String();

regExp = strEmailValidationRegExp;

// chk for mandatory field

if(strEmailToValidate.length == 0)

{

alert("Please enter the eMail Address.");

document.getElementById("txtEmailAddress").focus();

retVal = false;

} // chk for valid email address

else if(!regExp.test(strEmailToValidate))

{

alert("Please enter a valid eMail Address.");

document.getElementById("txtEmailAddress").focus();

retVal = false;

}

return retVal;

}

Tuesday, January 15, 2008

How to move web page division on mouse scroll (up/down)

How to move web page division on mouse scroll (up/down)
Following code is an example to move left side portion of the web page on mouse scroll.
The division which you are going to move should be placed before java script; this code can implement in Java or .Net application, this java script function is compatible with Netscape, Mozilla and IE browsers.
Note: This code will activate only when you have horizontal scroll bar in your web page.
//Sample division to move
<div id="divTopLeft" style="position:absolute;left:10;top:200;width:167;">
<table border="1" width="159" height="550" bgcolor=Pink bordercolor="black" cellspacing="0" cellpadding="0">
<tr>
<td bordercolor="Pink">
<font color="blue">Your text should go here..</font>
</td>
</tr>
</table>
</div>
//Java script function to move above division up and down
<script type="text/javascript">
function FloatTopLeft()
{
//Set the start X and Y position for division
var startX = 622, startY = 220;
var ns = (navigator.appName.indexOf("Netscape") != -1);
var d = document;
var px = document.layers ? "" : "px";
function ml(id)
{
var el=d.getElementById?d.getElementById(id):d.all
?d.all[id]:d.layers[id];
if(d.layers)el.style=el
el.sP=function(x,y)
{
this.style.left=x+px;this.style.top=y+px;};
el.x = startX; el.y = startY;
return el;
}
window.stayTopLeft=function()
{
var pY = ns ? pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
var dY = (pY > startY) ? pY : startY;
ftlObj.y += (dY - ftlObj.y)/8 + 1;
ftlObj.sP(ftlObj.x, ftlObj.y);
setTimeout("stayTopLeft()", 20);
}
ftlObj = ml("divTopLeft");
stayTopLeft();
}
FloatTopLeft();
</script>

Sunday, December 09, 2007

Client Side Script Debugging in ASP.NET

Another good article for client side script debugging in ASP.NET

http://www.beansoftware.com/ASP.NET-Tutorials/Client-Script-Debugging.aspx

HTTP Handlers and HTTP Modules in ASP.NET

Good article posted by Mansoor Ahmed Siddiqui in 15Second on HTTP Handlers and HTTP Modules in ASP.NET, see below link

http://www.15seconds.com/issue/020417.htm

Monday, November 19, 2007

How to redirect parent iframe from child iframe

How to redirect parent iframe from child iframe
 
For example while working on child page (iFrame) if session timeout then error page should refect in complate application not only child page (iFrame), to achive this please see following solutions
 
Solution-1
 
On click of child iFrame page control write following lines of code in code behind
 
Response.Write("<script>window.open('Error.aspx','_parent');</script>");
 
Solution-2
 
Write java script function in child page (iFrame) to submit parent page and set some hidden variable Now in the parent page in page load events according to hidden variable value, redirect to error page.
 
Code in child page
 
Java script function in aspx file
 
//when the session is timeout, its redirected to the home page
function RedirectError(errorMsg)
{           
window.parent.document.getElementById('hdnErrorMsg').value=errorMsg;
window.parent.document.forms.frmHome.submit();
}
 
Note: "frmHome" is parent page and "hdnErrorMsg" hidden variable declared in child page
 
Call this java script function from child page code behind
 
C# code in code behind
 
try
{
      // Code logic
}
catch (System.Security.SecurityException ex)
{
StringBuilder activateHide = new StringBuilder();
activateHide.Append("<script language='javascript'>");                activateHide.Append("RedirectError('SessionTimeout');");
activateHide.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(), "Contents", activateHide.ToString());
}
 
Code in Parent page
 
In the parent page (Home.aspx) code bahind page_load event handle this in if..else loop
protected void Page_Load(object sender, EventArgs e)
{
if (hdnErrorMsg.Value != "")
{
Response.Redirect("Error.aspx?ErrorMsg=" + hdnErrorMsg.Value);
}
else
{
      // Code logic
}
}
 


Never miss a thing. Make Yahoo your homepage.

Thursday, October 11, 2007

How to get Zip files contents in C# using J# libraries

How to get Zip files contents in C# using J# libraries
Let's assume this example, how to know whether .xml file present inside requested zip file or not
Reference
Right click your project in Server Explorer and click on "Add Reference" -> Select the .Net tab -> Scroll down and select "vjslib" -> Click OK and you are there.
Namespace
using java.util;
using java.util.zip;
using java.io;
Source Code
private Boolean GetZipFiles(ZipFile zipfil)
{
Enumeration zipEnum = zipfil.entries();
while (zipEnum.hasMoreElements())
{
ZipEntry zip = (ZipEntry)zipEnum.nextElement();
if (zip.ToString().ToLower().IndexOf(".xml") != -1)
{
//folder have xml file inside
return true;
}
}
return false; //folder does NOT have xml file inside
}
How to Use
page_Load()
{
ZipFile zipfile = new ZipFile(@"C:\temp.zip");
GetZipFiles(zipfile)
}
Some more functionality using J# Library
Create a ZIP file
private void Zip(string zipFileName, string[]sourceFile)
{
FileOutputStream filOpStrm = new FileOutputStream(zipFileName);
ZipOutputStream zipOpStrm = new ZipOutputStream(filOpStrm);
FileInputStream filIpStrm = null;
  foreach (string strFilName in sourceFile)
{
    filIpStrm = new FileInputStream(strFilName);
    ZipEntry ze = new ZipEntry(Path.GetFileName(strFilName));
    zipOpStrm.putNextEntry(ze);
    sbyte[]buffer = new sbyte[1024];
    int len = 0;
    while ((len = filIpStrm.read(buffer)) >= 0)
    {      zipOpStrm.write(buffer, 0, len);    }
  }
  zipOpStrm.closeEntry();
  filIpStrm.close();
  zipOpStrm.close();
  filOpStrm.close();
}
Extract a ZIP file
private void Extract(string zipFileName, string destinationPath)
{
ZipFile zipfile = new ZipFile(zipFileName);
List < ZipEntry > zipFiles = GetZippedFiles(zipfile);
foreach (ZipEntry zipFile in zipFiles)
  {
    if (!zipFile.isDirectory())
    {
      InputStream s = zipfile.getInputStream(zipFile);
      try
      {
        Directory.CreateDirectory(destinationPath + "\\" +
        Path.GetDirectoryName(zipFile.getName()));
        FileOutputStream dest = new FileOutputStream(Path.Combine
          (destinationPath + "\\" + Path.GetDirectoryName(zipFile.getName()),
          Path.GetFileName(zipFile.getName())));
        try
        {
          int len = 0;
          sbyte[]buffer = new sbyte[7168];
          while ((len = s.read(buffer)) >  = 0)
          {
            dest.write(buffer, 0, len);
          }
        }
        finally
        {
          dest.close();
        }   }
      finally {
        s.close();
     }    }  }  }
Get the contents of a ZIP file
private List < ZipEntry > GetZipFiles(ZipFile zipfil)
{
  List < ZipEntry > lstZip = new List < ZipEntry > ();
  Enumeration zipEnum = zipfil.entries();
  while (zipEnum.hasMoreElements())
  {
    ZipEntry zip = (ZipEntry)zipEnum.nextElement();
    lstZip.Add(zip);
  }
  return lstZip;
}
Reference sites

1)
http://www.c-sharpcorner.com/UploadFile/neo_matrix/SharpZip04242007001341AM/SharpZip.aspx
2) http://aspalliance.com/articleViewer.aspx?aId=1269&pId=-1
 

Wednesday, October 10, 2007

How to do Iframe auto resize according to aspx page contain

How to do Iframe auto resize according to aspx page contain
 
Supose you have one Iframe "IFrmRightMenu" and inside you are setting target for different aspx page, In this case the content of aspx page can have different height and width, If you want to set Iframe size according to aspx page contain height and width then use below function in onload attribute of iframe.
 
Source code
 
<script language="javascript">
 
function autoIFrameResize(id)
{
   var newheight;
   var the_width=572; //Fixed width      
       
   if(navigator.appName == "Microsoft Internet Explorer")
{            newheight=document.getElementById(id).contentWindow.document.body.scrollHeight;
           
      if (newheight == 0)
      {
           newheight =584; //Fixed height           
       }
        else
        {
newheight = document.getElementById(id).contentDocument.height;
        }
        
document.getElementById(id).height= (newheight + 16) + "px";
      document.getElementById(id).style.width=the_width+"px";       
window.parent.document.getElementById("IFrmRightMenu").style.height= (newheight + 16) + "px";
    }
 
</script>
 
How to use
 
<iframe frameborder="no" width="100%" height="100%" onload="autoResize('iframe1');" scrolling ="no" style="visibility:hidden;" id=" iframe1"></iframe>
 
How to redirect to Parent page from Child page (IFrame)
 
Let say you have one aspx page with two iframe (LeftIframe and RightIframe in one aspx page), now if you click any button in "RightIframe" and you want to redirect some error page or your want to redirect in home page then you can't simply write Reponse.Redirect ("error.aspx") or Reponse.Redirect ("Home.aspx"), this will display the page in "RightIframe" only.
 
Use below line of code to redirect page to Home.aspx or Error.aspx
 
Response.Write("<script>window.open('Error.aspx','_parent');</script>") OR
Response.Write("<script>window.open('Home.aspx','_parent');</script>")
 


Check out the hottest 2008 models today at Yahoo! Autos.