Friday, 19 October 2012

How to send EMail using C#


System.Net.Mail Namespace
The System.Net.Mail namespace contains classes used to send electronic mail to Simple Mail Transfer Protocol (SMTP) server for delivery.
Classes
1.       MailAddress: Represents the address of an electronic mail sender or recipient.
Inheritance Hierarchy:
System.Object
                System.Net.Mail.MailAddress

Constructors:
I.                    MailAddress(String emailAddress): Initializes a new instance of the MailAddress class using the specified address.

2.       MailMessage: Represents an e-mail message that can be sent using the SmtpClient class.
Inheritance Hierarchy:
System.Object
                System.Net.Mail.MailMessage

Constructors:
I.                    MailMessage(): Initializes an empty instance of the MailMessage class.
II.                  MailMessage(MailAddress from,  MailAddress to): Initializes a new instance of the MailMessage class by using the specified MailAddress class objects.
Properties:
I.                    AlternateViews: Gets the attachment collection used to store alternate forms of the message body.
II.                  Attachments: Gets the attachment collection to store data attached to this e-mail message.
III.                Bcc: Gets the address collection that contains the blind carbon copy (BCC) recipients for this e-mail message.
IV.                Body: Gets or sets the message body.
V.                  CC: Gets the address collection that contains the carbon copy (CC) recipients for this e-mail message.
VI.                From: Gets or sets the from address for this e-mail message.
VII.              IsBodyHtml: Gets or sets a value indicating whether the mail message body is in Html.
VIII.            Priority: Gets or sets the priority of this e-mail message.
IX.                ReplyTo: Obsolete. Gets or sets the ReplyTo address for the mail message.
X.                  Sender: Gets or sets the sender’s address for this e-mail message.
XI.                Subject: Gets or sets the subject line for this e-mail message.
XII.              To: Gets the address collection that contains the recipients of this e-mail message.

3.       Attachment: Represents an attachment to an e-mail.
Inheritance Hierarchy:
System.Object
                System.Net.Mail.AttachmentBase
                                System.Net.Mail.Attachment

Constructors:
I.                    Attachment(String filename): Initializes a new instance of the Attachment class with the specified content string.
Methods:
I.                    CreateAttachmentFromString(String filename, ContentType mimetype): Creates a mail attachment using the content from the specified string, and the specified ContentType.

4.       LinkedResource: Represents an embedded external resource in an email attachment, such as an image in an HTML attachment.
Inheritance Hierarchy:
System.Object
                System.Net.Mail.AttachmentBase
                                System.Net.Mail.LinkedResource

Constructors:
I.                    LinkedResource(String filename): Initializes a new instance of LinkedResource using the specified file name.
Properties:
I.                    ContentId:  Gets or Sets the MIME content ID for this attachment.
II.                  TransferEncoding:  Gets or Sets the encoding of this attachment.
Methods:
I.                    CreateLinkedResourceFromString(String filename): Creates a LinkedResource object from a string to be included in an email attachment as an embedded resource. The default media type is plain text, and the default content type is ASCII.

5.       AlternateView: Represents the format to view an email message.
Inheritance Hierarchy:
System.Object
                System.Net.Mail.AttachmentBase
                                System.Net.Mail.AlternateView

Constructors:
I.                    AlternateView(String filename, ContentType mimetype): Initializes a new instance of AlternateView with the specified file name and content type.
Properties:
I.                    ContentType:  Gets the Content type of this attachment.
Methods:
I.                    CreateAlternateViewFromString(String filename): Creates a AlternateView of an email message using the content specified in a String.

6.       SmtpClient: Allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).
Inheritance Hierarchy:
System.Object
                System.Net.Mail.SmtpClient

Constructors:
I.                    SmtpClient(): Initializes a new instance of the SmtpClient class by using configuration file settings.
II.                  SmtpClient(String smtpserver, Int32 port): Initializes a new instance of the SmtpClient class that sends e-mail by using the specified SMTP server and port.
Properties:
I.                    Credentials: Gets or sets the credentials used to authenticate the sender.
II.                  EnableSsl: Specify whether the SmtpClient uses Secure Sockets Layer(SSL) to encrypt the connection.
III.                Host: Gets or sets the name or IP address of the host used for SMTP transactions.
IV.                Port: Gets or sets the port used for SMTP transactions.
V.                  UseDefaultCredentials: Gets or sets a Boolean value that controls whether the DefaultCredentials are sent with requests.
VI.                DeliveryMethod: Specifies how outgoing email messages will be handled.
Methods:
I.                    Send(MailMessage): Sends the specified message to an SMTP server for delivery.
II.                  Send(String sender, String recipients, String subject, String message): Sends the specified e-mail message to an SMTP server for delivery. The message sender, recipients, subject, and message body are specified using String objects.

Events:
I.                    SendCompleted: Occurs when an asynchronous e-mail send operation completes.

7.       SmtpException: Represents the exception that is thrown when the SmtpClient is not able to complete a Send or SendAsync operation.
Inheritance Hierarchy:
System.Object
                System.Exception
                                System.Net.Mail.SmtpException
                                                System.Net.Mail.SmtpFailedRecipientException

8.       SmtpFailedRecipientException: Represents the eception that is thrown when the SmtpClient is not able to complete a Send or SendAsync operation to a particular recipient.
Inheritance Hierarchy:
System.Object
                System.Exception
                                System.Net.Mail.SmtpException
                                                System.Net.Mail.SmtpFailedRecipientException
                                                                System.Net.Mail.SmtpFailedRecipientsException
Enumerations:
1.       MailPriority: Specifies the priority to the MailMessage
Members:
I.                    Normal                 -              The email has normal priority
II.                  Low                        -              The email has low priority
III.                High                       -              The email has high priority

Web.config:
1.       <smtp>:  Configures the delivery method and from address for sending mails.
Syntax:                 <smtp
                                                                deliveryMethod = “method”
                                                                from = “fromAddress”> </smtp>

2.       <network>:  Configures the network options for external SMTP Server.
Syntax:                 <network
                                                defaultCredentials = “true | false”
                                                enableSsl = “true | false”
                                                host = “string”
                                                password = “string”
                                                port = “integer”
                                                username = “string” />

Example:
               
<configuration>
  <system.net>
    <mailSettings>
      <smtp
        deliveryMethod="Network"
        from="from.address@gmail.com">
        <network
          defaultCredentials="false"
          host="smtp.gmail.com"
          port="587"
          enableSsl="true"
          userName="from.address@gmail.com"
          password="password"/>
      </smtp>
    </mailSettings>
  </system.net>
</configuration>

Sample SMTP Server Settings:

1.       Gmail: 
Host
smtp.gmail.com
Port
587
2.       Yahoo:
Host
smtp.mail.yahoo.com
Port
995


Example:

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SmtpClientWithoutWebConfig._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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Click the button to send the mail...
        <asp:Button Text="Send EMail" runat="server" ID="btnSendEMail"
            onclick="btnSendEMail_Click" />
        <br />
        <br />
        <asp:Label ID="lblMsg" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>


Default.aspx.cs

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

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

        }

        protected void btnSendEMail_Click(object sender, EventArgs e)
        {
            SendEMail();
        }

        protected void SendEMail()
        {
            // declaring the email addresses...
            // from email address
            MailAddress fromAddress = new MailAddress("from.address@gmail.com");
            // to email address
            MailAddress toAddress = new MailAddress("to.address@gmail.com");
            // bcc email address
            MailAddress bccAddress = new MailAddress("bcc.address@gmail.com");
            // cc email address
            MailAddress ccAddress = new MailAddress("cc.address@gmail.com");

            // declaring the attachments...
            Attachment simpleAttachment = new Attachment(@"F:\SA.txt");

            // declaring the linked resources...
            LinkedResource simpleLinkedResource = new LinkedResource(@"F:\Desert.jpg");
            simpleLinkedResource.ContentId = "DesertImage";
            simpleLinkedResource.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;

            // declaring the alternate views...
            string strHtmlView = "<img src=cid:DesertImage height='200' width='200' /><br /><b>Hai...This mail is sent using C#</b>";
            AlternateView htmlView = AlternateView.CreateAlternateViewFromString(strHtmlView);
            htmlView.ContentType = new System.Net.Mime.ContentType("text/html");
            htmlView.LinkedResources.Add(simpleLinkedResource);

            // declaring the mail message...
            MailMessage msg = new MailMessage();
            msg.From = fromAddress;
            msg.To.Add(toAddress);
            msg.Bcc.Add(bccAddress);
            msg.CC.Add(ccAddress);
            msg.Subject = "Simple Mail";
            msg.AlternateViews.Add(htmlView);
            msg.Attachments.Add(simpleAttachment);
            msg.IsBodyHtml = true;
            msg.Priority = MailPriority.High;
            msg.Body = "Hai...This mail is sent using C#";

            // setting up the smtpclient and sending the mail...
            SmtpClient sc = new SmtpClient();
            sc.Host = "smtp.gmail.com";
            sc.Port = 587;
            sc.EnableSsl = true;
            sc.UseDefaultCredentials = false;
            sc.Credentials = new NetworkCredential(fromAddress.Address, "password");
            sc.DeliveryMethod = SmtpDeliveryMethod.Network;

            // now sending the mail...
            sc.Send(msg);
            lblMsg.Text = "Mail successfully sent to: " + toAddress.Address;
        }
    }
}

Generating a GUID using C#

GUID (Global Unique Identifier) - A GUID is a unique reference number used as an identifier in computer software. GUIDs are usually stored as 128-bit values, and are commonly displayed as 32 hexadecimal digits with groups separated by hyphens, such as 21EC2020-3AEA-1069-A2DD-08002B30309D.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GeneratingGUID
{
    class Program
    {
        public static void Main(string[] args)
        {
            Guid g = Guid.NewGuid();
            Console.WriteLine("GUID: " + g.ToString());
            Console.ReadLine();
        }
    }
}

Sunday, 20 May 2012

Turning Num lock ON/OFF after the logon


  1. Open 'Run' and type 'regedit' and press enter...
  2. Select 'HKEY_CURRENT_USER' from the left pane...
  3. Select 'Control Panel'...
  4. Select 'Keyboard'...
  5. Double click on 'InitialKeyboardIndicators'...
Enter '0' to turn OFF Num lock after logon...
Enter '2' to turn ON Num lock after logon...
Enter '1' to disable Num lock...

Saturday, 19 May 2012

CSS Styles for custom margins while printing


  1. Create a CSS file and include some margins styles in it (say style.css)
@page {


margin-top: 1in;
margin-right: 1in;
margin-bottom: 1in;
margin-left: 1in;
}
  1. Create a HTML file and include the above stylesheet (say index.html)
<html>
<head>
<title> coldsoftmail </title>
<link rel="stylesheet" type="text/css" href="style.css" media="all">
</head>
<body>
<img src="Desert.jpg">
<input type="button" name="print" value="Print" onClick="javascript: window.print();">
</body>
</html>

CSS Styles for Scrollbars (Google Chrome)


  1. Create a CSS file and include some scrollbar styles in it (say style.css)...
::-webkit-scrollbar {
height: 12px;
width:12px;
background: #A3C1F7;
-webkit-border-radius: 1ex;
}
::-webkit-scrollbar-thumb {
/*chrome 10*/
background-image: -webkit-gradient(radial, center center, 0, center center, 437, color-stop(0, #0053FA), color-stop(1, #A49FF4));
/*chrome 11+ */
background-image: -webkit-radial-gradient(center, circle cover, #0053FA 0%, #A49FF4 100%);
-webkit-border-radius: 1ex;
-webkit-box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.75);
}
::-webkit-scrollbar-corner {
background: #A3C1F7;
}
  1. Create a HTML file and include the above stylesheet (say index.html)
<html>
<head>
<title> coldsoftmail </title>
<link rel="stylesheet" href="style.css" type="text/css" media="all">
</head>
<body>
<p style="font-size: 100px;">
Hai this is coldsoftmail <br>
Hai this is coldsoftmail <br>
Hai this is coldsoftmail <br>
Hai this is coldsoftmail <br>
Hai this is coldsoftmail
</p>
</body>
</html>

Locking a Folder


  1. Download 'LocK-A-FoLdeR' from ' http://code.google.com/p/lock-a-folder/'...
  2. Install 'LocK-A-FoLdeR'...
  3. Set Master password...
  4. Select the folder you want to lock...
  5. After locking the locked folder will be permanently hidden...
  6. We can see the locked folder until or unless we unlock the folder...

Friday, 18 May 2012

How to upload large files onto the web server using PHP


  1. Go to the folder of web server and search for 'php.ini' file in 'bin\php' folder...
  2. Open 'php.ini' file with administrator permissions...
  3. Search for 'file_uploads' in the file and set it as 'on'...
  4. Search for 'upload_max_filesize' in the file and set it as required...
  5. Save the file and close it...
  6. Write code for html form for uploading file (say index.html)...
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
</body>
</html>
  1. Write code for php to upload file (say upload.php)
<?php
$filename = "Image00.jpg";
move_uploaded_file($_FILES['file']['tmp_name'], $filename);
echo "File uploaded successfully";
?>
  1. Now open 'index.html' file in your web server...