5,427,303 members and growing! (20,449 online)
Email Password   helpLost your password?
Web Development » ASP.NET » Howto     Intermediate

Sending Email with attachment in ASP.NET using SMTP Server

By Sivakumar Ramadoss

This article explains how to send a mail with attachment using SMTP server and how to configure the SMTP server.
C#, HTMLWindows, .NET, .NET 1.1, Win2K, WinXP, Win2003, ASP.NET, IIS 5.1, VS.NET2003, IE 5.5, IIS, Visual Studio, IE, Dev

Posted: 28 Jun 2005
Updated: 28 Jun 2005
Views: 82,283
Bookmarked: 40 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
19 votes for this Article.
Popularity: 4.07 Rating: 3.18 out of 5
5 votes, 26.3%
1
2 votes, 10.5%
2
1 vote, 5.3%
3
1 vote, 5.3%
4
10 votes, 52.6%
5

Introduction

This application demonstrates how to send mail with attachments using SMTP server and how to configure the default SMTP server. The System.Web.Mail namespace provides classes for sending email in .NET. The classes involved are MailMessage which manages the content of the mail message and MailAttachment which manages the mail attachments.

Setting SMTP server

Before running the application you need to confirm these server settings:

  1. Make sure that the SMTP server is running, only then it can relay mail. If not, open the IIS window, in IIS look for the "local computer" on the left side tree view under which you will see the "Default SMTP Virtual Server", if it is not available, then you need to install it.
  2. To configure "Default SMTP Virtual Server", right-click on it, go into "Properties", and select "Access" tab, and then click the "Relay" button. With "only the list below" radio button selected, you should see the local IP address: "127.0.0.1", if it's not there, you need to add it.
  3. If you are using "localhost" or "127.0.0.1" as the SmtpMail.SmtpServer, make sure "Anonymous access is allowed". To allow access, open up the IIS. Locate the SMTP virtual server, and right-click select Properties. On the Access tab, click the Authentication button. Make sure "Anonymous Access" is the only checkbox checked.
  4. Use real from and to addresses that exist on the SmtpMail.SmtpServer. Do not use invalid address.

Getting objects

Initially, we need to create a new object for the MailMessage class, we will call it "mailMessage". Then we set the From, To, Cc, Bcc, Subject and Body properties as well as the BodyFormat of this object to the values on our web form:

 /* Create a new blank MailMessage */
 MailMessage mailMessage = new MailMessage ();  
 mailMessage.From = txtSender.Text;
 mailMessage.To = txtReceiver.Text;
 mailMessage.Cc = txtCc.Text;
 mailMessage.Bcc = txtBcc.Text;
 mailMessage.Subject = txtSubject.Text;
 mailMessage.Body = txtBody.Text;
 /* Set the properties of the MailMessage to the
    values on the form  */
 if (rblMailFormat.SelectedItem.Text == "Text")
    mailMessage.BodyFormat = MailFormat.Text;
 else
    mailMessage.BodyFormat = MailFormat.Html;

Making attachments

To make attachments we need to use the MailAttachment class and for this we create an object attach. The following block of code checks the Open File Dialogs of our web form (the Open File Dialog is an HTML file field control to which we've added the runat="server" property). If there is a value, the file is uploaded, saved on the server and added as an attachment to the email.

/* Beginning 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 */
 MailAttachment attach = new MailAttachment(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;
 }
}

Now, we send the email with the attachments:

SmtpMail.SmtpServer = "127.0.0.1";
(Or)
SmtpMail.SmtpServer.Insert(0,"127.0.0.1");
SmtpMail.Send (mailMessage);

Finally, if the attachments are available then we need to delete it:

/* Delete the attachements if any */
 if (attach1 != null)
  File.Delete(Server.MapPath(attach1));
 if (attach2 != null)
  File.Delete(Server.MapPath(attach2));
 if (attach3 != null)
       File.Delete(Server.MapPath(attach3));

Various ways to set the SMTP Mail server:

SmtpMail.SmtpServer = "localhost"

or

SmtpMail.SmtpServer = "127.0.0.1"

or

SmtpMail.SmtpServer.Insert( 0, 
    "127.0.0.1 or your mail server name here")

You need to replace "localhost" with the name or IP address of your SMTP Mail server on a Windows desktop computer or you can insert the server but "localhost" is the default value and it usually works.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Sivakumar Ramadoss


Sivakumar Ramadoss (SIVA) is a Software Engineer for Adea International Pvt Ltd, Bangalore. His background is in developing relational databases and n-tier applications in Microsoft Technologies.


Occupation: Web Developer
Location: India India

Other popular ASP.NET articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 30 (Total in Forum: 30) (Refresh)FirstPrevNext
Subject  Author Date 
Generalerror...memberBruceInFTL7:41 15 Jan '08  
QuestionSending attachment in Winforms appmemberjlo14319:09 8 Mar '07  
GeneralHelp for understand - UrgentmemberYamiyahoo23:17 3 Dec '06  
Generalerror help- The server respond 5.7.1 unable to relay...memberYamiyahoo23:12 3 Dec '06  
GeneralMail Servermemberanisha1969:05 5 Nov '06  
GeneralRe: Mail Servermembermanish srivastava10:20 11 Jan '07  
GeneralHelp mememberprinceamrooo13:34 7 Aug '06  
GeneralThanxmemberyourasp.net4:49 4 Jul '06  
GeneralInvalid Mail Attachment ' '.memberhexOffender6:20 22 May '06  
GeneralRe: Invalid Mail Attachment ' '.memberSivakumar_Ramadoss4:03 3 Jun '06  
GeneralHow to retrieve an Attachment file from mail server.memberHendrik (Chrysonite)0:47 3 May '06  
GeneralSMTP server running on remote machinememberf_baig786@hotmail.com20:03 9 Feb '06  
GeneralDelete files errormemberaltug20058:49 22 Dec '05  
GeneralRe: Delete files errormemberthaiasp1:38 21 Mar '06  
GeneralRe: Delete files errormembermusicdsign21:39 19 Oct '06  
QuestionRe: Delete files errormemberVikram kshatriya18:47 13 Apr '08  
AnswerRe: Delete files errormemberpradeep841:56 23 May '08  
AnswerRe: Delete files error [modified]membergrossbommi2:06 4 Jun '08  
Generalhow to check SMTP server is alive using codemembertiwari piyush3:22 24 Nov '05  
Generalnot delivering to addressmembersam_ten200123:52 27 Oct '05  
GeneralRe: not delivering to addressmembercdotpal3:38 9 Mar '06  
GeneralRe: not delivering to addressmemberHemant K Jangid4:56 24 Apr '06  
GeneralRe: not delivering to addressmemberyourasp.net4:52 4 Jul '06  
GeneralThanks for the codesussRinda Kotagiri0:13 12 Jul '05  
GeneralSmtpServer.Insert -- mistakesussJakub Snopek6:46 11 Jul '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 28 Jun 2005
Editor: Rinish Biju
Copyright 2005 by Sivakumar Ramadoss
Everything else Copyright © CodeProject, 1999-2008
Web12 | Advertise on the Code Project