Click here to Skip to main content
15,743,541 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Visual Studio 2008
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net;
using System.Net.Mail;

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

    protected void Button1_Click(object sender, EventArgs e)
        MailMessage msg = new MailMessage();
        msg.From = new MailAddress(txtGAddress.Text, "Sender's Name");
        msg.To.Add(new MailAddress(txtToAddress.Text));
        msg.Subject = txtSubject.Text;
        msg.Body = txtMessage.Text;
        msg.IsBodyHtml = true;

        if (fluattachment.HasFile)
            msg.Attachments.Add(new Attachment(fluattachment.PostedFile.InputStream, fluattachment.FileName));

        SmtpClient smtp = new SmtpClient();
        smtp.Host = "";
        smtp.Credentials = new System.Net.NetworkCredential(txtGAddress.Text, txtGPassword.Text);
        LblReason.Visible = true;
        smtp.EnableSsl = true;
            smtp.send(msg);//Getting the error over here//
            LblReason.Text = "Mail Sent";

        catch (Exception ex)
            LblReason.Text = ex.Message;

Error is

Error 1 'System.Net.Mail.SmtpClient' does not contain a definition for 'send' and no extension method 'send' accepting a first argument of type 'System.Net.Mail.SmtpClient' could be found (are you missing a using directive or an assembly reference?) C:\Documents and Settings\SALMAN\My Documents\Visual Studio 2008\WebSites\Excel1\FrmSendMail.aspx.cs 44 18 C:\...\Excel1\
Updated 7-Dec-12 22:02pm

smtp.Send(fromAddress, toAddress, subject, body);

or else read Sending Email with attachment in ASP.NET using SMTP Server[^]
Share this answer
Salman Farooqui 8-Dec-12 4:16am    
This worked but what about the attachment file
[no name] 8-Dec-12 4:20am    
You've already written for that...
Salman Farooqui 8-Dec-12 4:25am    
smtp.Send(txtGAddress.Text, txtToAddress.Text, txtSubject.Text, txtMessage.Text);

i have added this but i am not getting the attachment
[no name] 8-Dec-12 4:29am    
I've updated solution... take a look :) Cheers...
Salman Farooqui 8-Dec-12 4:37am    
plz can u explain what u added i request you for that plz
Refer this Article this article will solve your problem of sending mail with attachment-[^]
Share this answer
Salman Farooqui 8-Dec-12 12:17pm    
Surendra0x2 8-Dec-12 12:29pm    
Accept the solution bro if this Helped You :)
and happy coding :)
Check this example

<add key="MAILEnvioCorrreo" value=" Hola {0},<br></br> hemos creado una cuenta de Usuario con los siguientes datos:<br></br> Usuario: {1} <br></br> Contraseña: {2}">
private void EnvioCorreo(Empleado empleado, string clave)
#region Cargando configuración del servidor de correo
string MailServer = "name server example";
string MailServerPort = ""587;
string MailServerUser = "email or user";
string MailServerPassword = "example";
string MailServerEnableSSL = " if use server hotmail, gmail,yahoo this value is false ";

SmtpClient smtp = new SmtpClient(MailServer, MailServerPort);
smtp.Credentials = new System.Net.NetworkCredential(MailServerUser, MailServerPassword);
smtp.EnableSsl = MailServerEnableSSL;
MailAddress sender = new MailAddress(MailServerUser, "any thing");
StringBuilder mensaje = new StringBuilder();
StringBuilder mensajeMail = new StringBuilder();
string formatoAvisoMail = System.Configuration.ConfigurationManager.AppSettings["MAILEnvioCorrreo this in app congig"].ToString();
MailMessage msjMail = new System.Net.Mail.MailMessage();
msjMail.Subject = "Bienvenido a Kanan";
msjMail.From = sender;
msjMail.IsBodyHtml = true;
mensaje.AppendFormat(formatoAvisoMail, empleado.Nombre, empleado.Usuario.Nombre, clave);
mensajeMail.AppendFormat(formatoAvisoMail, empleado.Nombre, empleado.Usuario.Nombre, clave);
msjMail.Body = mensajeMail.ToString();
if (msjMail.To.Count > 0)
Share this answer
Share this answer

System.Net.Mail - How to add Alternate views and Embed Images

System.Net.Mail provides us with a very intuitive object model to construct
and send an email message.

These days almost all the web and windows email clients gives us more
control over the email content we wish to view (a.k.a HTML view, plain text
view). This is to make us aware that the email content we are viewing may
contain explicit images or externally linked images. Now imagine the
recipient have disabled HTML content in his/her settings then the email
content will be displayed as is(with HTML tags).

We definitely don't want garbled text to be viewed by the recipient, now
here is where the Alternate view comes to our rescue. As the name suggests
it allows us to add alternate content that can be viewed by the receipient
in case HTML content is disabled in his/her settings.

Similarly many web/windows email clients disable external images in the mail
message to avoid linking of external images we can use the LinkedResource to
embed images in our email message.

Although the core topic is about adding alternate views and embedding
resources(images, etc) to an email, I will also touch upon configuration
settings in web.config and Network Credentials.


The MailMessage class plays a key role by wrapping all the email details

- From address
- To address (collection)
- CC address (collection)
- BCC address (collection)
- Email Subject
- Email Body
- Priority
- Delivery notification options
- Alternate views (Plain text, HTML)
- Linked Resources (images, etc)

Below given is a typical code used to send an email, the code is pretty
straight forward apart from the AlternateViews, LinkedResources and some
SMTPClient config section.

MailMessage objMailMessage = new MailMessage();

//File Attachment
if (fileUploadEmailAttachment.HasFile)
new Attachment(


objMailMessage.From = new MailAddress(txtEmailFrom.Text,

objMailMessage.To.Add(new MailAddress(txtEmailTo.Text));

if (txtEmailCC.Text.Length > 0)
objMailMessage.CC.Add(new MailAddress(txtEmailCC.Text));

if (txtEmailBCC.Text.Length > 0)
objMailMessage.Bcc.Add(new MailAddress(txtEmailBCC.Text));

objMailMessage.Subject = txtSubject.Text;

//Plain Text Alternative Email Content
AlternateView objPlainAltView = AlternateView.CreateAlternateViewFromString(

//HTML Alternative Email Content
LinkedResource objLinkedRes = new LinkedResource(
+ "\\fuzzydev-logo.jpg", "image/jpeg");
objLinkedRes.ContentId = "fuzzydev-logo";

AlternateView objHTLMAltView = AlternateView.CreateAlternateViewFromString(
new System.Net.Mime.ContentType("text/html"));


//High Priority
objMailMessage.Priority = MailPriority.High;

//Notify On Sucessfull Delivery
objMailMessage.DeliveryNotificationOptions =
SmtpClient objSMTPClient = new SmtpClient(txtHostName.Text);
objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.Network;

objSMTPClient.EnableSsl = true;

//Credentials (username, password)
string sUserName = txtEmailFrom.Text.Split('@')[0];
objSMTPClient.Credentials = new System.Net.NetworkCredential(
sUserName, txtEmailFromPassword.Text);

//Send Email


Now let me concentrate on the Alternateview, adding an alternate view is
very easy, just create an object of the AlternateView class using the static
method of the *AlternateView* class called
*CreateAlternateViewFromString*passing the email text and the MIME

*For example if we want to create a plain text view then we will do
something like this*

AlternateView objPlainAltView = AlternateView .CreateAlternateViewFromString(

*Now if we need HTML view then*

AlternateView objHTLMAltView = AlternateView.CreateAlternateViewFromString(
new System.Net.Mime.ContentType("text/html"));

That looks pretty simple, now the good news is the recipient will view the
email message based on the email clients settings. So if HTML content is
disabled then plain text message is displayed otherwise the HTML content is

Let us move forward and get our hands dirty by embedding an image in an HTML
content message. In order to embed an image in our email we can use
LinkedResource class, we can add this object to the LinkedResource
collection of the AlternateView object.

LinkedResource objLinkedRes = new LinkedResource(
+ "\\fuzzydev-logo.jpg",
objLinkedRes.ContentId = "fuzzydev-logo";

AlternateView objHTLMAltView = AlternateView.CreateAlternateViewFromString(
new System.Net.Mime.ContentType("text/html"));

In the above code we are passing an image file path and also specifying the
content type as an jpeg image to the LinkedResource object. Next line of
code is very interesting, we are assigning a unique ContentId which will be
used to set the src of our HTML image tag. In our case the content id is
fuzzydev-logo and if you look at the HTML alternate view object in the
constructor section we are having an image tag which refers to the same
content id.

Now it's the email clients responsibility to understand the embedded
resource and the reference in the image tag and display the image.


Now coming to the SMTP client configuration, let's just look in to what is
the minimum configuration settings that SMTP client object expects from us.

- Host name or IP address
- Delivery Method (Network, Pick up directory from IIS, custom pickup
- EnableSsl (whether Secured Socket Layer is required)
- Credentials (user name, password)

*SMTPClient configuration in web.config:*

<smtp deliverymethod="Network" from="">
<network host="">
userName="email user name"
password="email passowrd"

<compilation debug="false">
<pages validaterequest="false">

The above configuration helps us in quickly changing the delivery method,
from mail address, host name (or IP address) , user name and password.
Although the configuration is not mandatory it is the recommended way of
implementing the email functionality.

Below given code doesn't depend on the web.config for it's configuration

SmtpClient objSMTPClient = new SmtpClient(txtHostName.Text);
objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.Network;
objSMTPClient.EnableSsl = true;

//Credentials (username, password)
string sUserName = txtEmailFrom.Text.Split('@')[0];
objSMTPClient.Credentials = new System.Net.NetworkCredential(
sUserName, txtEmailFromPassword.Text);

//Send Email

We don't need to specify the host name, etc if it's available in the
web.config, this is usefull as in different part's of our application we can
just use the specified configuration and if required then specify manually.

Now that deserves a round applause for those involved in the development of
System.Net.Mail classes.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900