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;
        }
    }
}

No comments:

Post a Comment