Microsoft KB Archive/310273

= How to send e-mail programmatically by using System.Web.Mail in Visual C# 2005 or in Visual C# .NET =

Article ID: 310273

Article Last Modified on 12/11/2006

-

APPLIES TO


 * Microsoft Visual C# 2005
 * Microsoft Visual C# .NET 2003 Standard Edition
 * Microsoft Visual C# .NET 2002 Standard Edition

-



This article was previously published under Q310273



SUMMARY
This article demonstrates how to use the System.Web.Mail namespace to send an e-mail message in Microsoft Visual C# .NET.



MORE INFORMATION
 Start Microsoft Visual Studio 2005 or Microsoft Visual Studio .NET. On the File menu, click New and then click Project. Click Visual C# Projects, click the Console Application template, and then click OK. By default, Class1.cs is created.

Note In Visual Studio 2005, click Visual C# instead of Visual C# Projects. By default, Program.cs is created. Add a reference to the System.Web.dll namespace. To do this, follow these steps:  On the Project menu, click Add Reference. On the .NET tab, locate System.Web.dll, and then click Select.

Note In visual Studio 2005, you do not have to click Select. Click OK in the Add References dialog box to accept your selections. If you receive a prompt to generate wrappers for the libraries that you selected, click Yes.   In the code window, replace the whole code with: using System; using System.Web.Mail;

namespace WebMail {   class Class1 {       static void Main(string[] args) {           try {               MailMessage oMsg = new MailMessage; // TODO: Replace with sender e-mail address. oMsg.From = &quot;sender@somewhere.com&quot;; // TODO: Replace with recipient e-mail address. oMsg.To = &quot;recipient@somewhere.com&quot;; oMsg.Subject = &quot;Send Using Web Mail&quot;; // SEND IN HTML FORMAT (comment this line to send plain text). oMsg.BodyFormat = MailFormat.Html; // HTML Body (remove HTML tags for plain text). oMsg.Body = &quot;<HTML><BODY><B>Hello World!</B></BODY></HTML>&quot;; // ADD AN ATTACHMENT. // TODO: Replace with path to attachment. String sFile = @&quot;C:\temp\Hello.txt&quot;; MailAttachment oAttch = new MailAttachment(sFile, MailEncoding.Base64); oMsg.Attachments.Add(oAttch);

// TODO: Replace with the name of your remote SMTP server. SmtpMail.SmtpServer = &quot;MySMTPServer&quot;; SmtpMail.Send(oMsg);

oMsg = null; oAttch = null; }           catch (Exception e)            { Console.WriteLine(&quot;{0} Exception caught.&quot;, e); }       }    } }                     </li> Modify the code where you see &quot;TODO&quot;.</li> Press F5 to build and run the program.</li> Verify that the e-mail message has been sent and received.</li></ol>

Keywords: kbhowto KB310273

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.