Sie sind auf Seite 1von 11

Send Email Messages and Attachments Using C#

http://www.c-sharpcorner.com/uploadfile/scottlysle/send-email-messag...

In Focus

Delhi Chapter Hands On June 22: Limited Seats Register Now

manoj

Ask a Ques on
TECHNOLOGIES ANSWERS BLOGS VIDEOS INTERVIEWS BOOKS LINKS NEWS CHAPTERS CAREER ADVICE

Contribute

Create Outlook Add-in by MAPI Func onality ...

PREMIUM SPONSORS

ARTICLE
Send Email Messages and A achments Using C#
Posted by Sco Lysle in Ar cles | C# Language on August 05, 2008 Tags: Email, Email A achments, Regular Expressions, SMTP, System.Net.Mail, System.Net.Mime, Valida on This ar cle describes an approach to sending email messages with or without a achments. The code required to send the message is contained within a reusable class. In addi on to sending messages and messages with a achments, the class also validates the recipient email addresses using regular expression valida on.
Tweet 0 Share Share 2 Like 4

DynamicPDF Developer Components


DynamicPDF product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to exis ng PDF documents from within your applica ons.

TRENDING UP
Create Outlook Add-in by MAPI Func onality by Using Visual Studio 2010 Outlook Project Debugging jQuery in ASP.NET Top 10 HTML5 Interview Ques ons

214831

23

Reader Level:

Download Files: EmailA achments_CS.zip

How to Enable Sign in as Dierent User Op on in SharePoint 2013 How to Select Mul ple Rows in Grid Using LightSwitch 2012 Find and Delete Duplicate Records From SQL Table Encrypt and Decrypt in SQL Server: Part 2 Custom Paging With GridView in ASP.NET 4.5 Na ve Windows Dynamic Link Libraries (DLLs) Resolving Dependency Using Ninject

Introduction This article describes an approach to sending email messages with or without attachments. The code required to send the message is contained within a reusable class. In addition to sending messages and messages with attachments, the class also validates the recipient email addresses using regular expression validation.

View All

MOST LIKED ARTICLE


WCF Introduc on and Contracts - Day 1 Create SSRS Report Using Report Wizard CREATE READ UPDATE and DELETE - CRUD Opera on Using LINQ to SQL WCF - Data Contract - Day 4 Factory Design Pa ern
Follow @csharpcorner 4,341 followers

Find us on Facebook C# Corner


Like

Figure 1: Test Application Main Form SMTP Configuration Setting up IIS Your local IIS instance has to be properly configured in order to successfully send an email message through its SMTP mail server. Even if you install IIS, the SMTP mail server installation is optional and must be explicitly added to the installation. If you are not sure whether or not the SMTP mail server is installed, open up the IIS control panel and check for the installation; if it is installed you will see a reference to the Default SMTP Virtual Server in the tree view (Figure 2):

10,668 people like C# Corner.

Facebook social plugin

HOT KEYWORDS

Abstract Class ArrayList


Methods

Boxing

Console Constructors enum EventHandler Extension

FileStream Hashtable inheritance Interfaces List objectdatasource OOP Sorting StreamReader StreamWriter
Class Strings System.Text User Controls

Thread visual studio Visual

unboxing

1 of 11

25/05/2013 01:34

Send Email Messages and Attachments Using C#

http://www.c-sharpcorner.com/uploadfile/scottlysle/send-email-messag...

SPONSORED BY
DynamicPDF ReportWriter Suite
PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.

Studio 2005

Figure 2: Default SMTP Virtual Server Installed If the server is not installed, you will need to use the "Add and Remove Windows Components" function in the "Add and Remove Programs" control panel to add the SMTP server to your IIS installation. If you need to do this additional installation, once you've opened the "Add and Remove Windows Components", click on "Internet Information Services (IIS)" to highlight it and then click on the "Details" button (Figure 3). This will open an IIS dialog; examine this dialog to locate "SMTP Service" and click on it to place a check mark on the box (Figure 4). Once this item has been checked, click on the "OK" button to install the SMTP server.

WHITEPAPERS AND BOOKS


Interview Ques ons on SharePoint 2013 SharePoint 2010 Administra on & Development Ge ng Started with Managed Metadata Service in SharePoint 2010 Windows Phone 7 Hileleri Windows Phone Development Step by Step Tutorial Essen als of SharePoint 2010: Business Intelligence Capabili es Working with Directories in C# FileInfo in C# Programming List with C# Source Code: Graphics Programming with GDI+

View All
POLL RESULT ALL POLLS

What is the best product to build Mobile apps?

What is the best product to build Mobile apps PhoneGap Icenium Xamarin Studio Figure 3: Windows Components Wizard KendoUI Mobile JQueryMobile Na ve iOS/Android
Vote

Figure 4: Adding the SMTP Service to IIS Once the default SMTP server has been installed or verified; you can now configure it to send email. In order to configure the SMTP server, open the IIS control panel, locate the default SMTP server icon in the treeview, and select and right click the icon. Once the context menu has been displayed, locate "Properties" and click on it to open the properties menu.

2 of 11

25/05/2013 01:34

Send Email Messages and Attachments Using C#

http://www.c-sharpcorner.com/uploadfile/scottlysle/send-email-messag...

Once the Default SMTP Virtual Server Properties dialog is displayed click on the "Access" tab (Figure 5):

Figure 5: SMTP Property Dialog Select the "Authentication" button to display the authentication options (Figure 6):

Figure 6: Authentication Options Make sure that the Anonymous access option is checked and that all other options are unchecked; in some instances you may wish to use the other options but in most cases involving a public website this is the option you'd want. Once you have verified this setting, click "OK" to close this dialog. Back to the "Access" tab, locate and click on the "Relay" button to display the relay options. Note that the radio button for "Only the list below" is selected, and that the local host IP address has been added to the list of computers permitted to relay through the SMTP server. Naturally this is OK for a development machine but in deployment, you would use the actual IP address of the web server. If no IP addresses are shown in the list, click on the "Add" button and add the IP address. Once finished, click on the "OK" button to accept the changes and to dismiss the dialog. (Figure 7)

3 of 11

25/05/2013 01:34

Send Email Messages and Attachments Using C#

http://www.c-sharpcorner.com/uploadfile/scottlysle/send-email-messag...

Figure 7: Relay Restrictions Dialog Next, select the "Delivery" tab from the SMTP Server properties dialog (Figure 8):

Figure 8: Delivery Options Dialog From this dialog, select the "Advanced" button to reveal the advanced options dialog (Figure 10):

Figure 9: Advanced Delivery Dialog From this dialog there are two points to make; first, the "Fully qualified domain name" property

4 of 11

25/05/2013 01:34

Send Email Messages and Attachments Using C#

http://www.c-sharpcorner.com/uploadfile/scottlysle/send-email-messag...

should be pre-populated; you may click on the "Check DNS" button to validate the setting. The next option is probably the most critical item for the whole shooting match; the Smart Host property has to be set to point to a valid SMTP mail server that will permit you to relay mail. For most cases, you will key in the name of your internet provider's default SMTP mail server; the address is likely to be in the format of "mail.something.com" where "something" is the internet provider's domain name. There are two easy ways to get this, one is, if you are using Outlook, open up Outlook and pull up the information on your email account; the mail server will be listed there. The second option is to guess and you can qualify your guess by pinging the server. If your internet provider's name is "foxtrox", try pinging mail.foxtrot.com; if you get a response there, that is probably the one to use. If that does not work, contact your administrator and ask them for the information on the SMTP mail server; don't try to plug in an Exchange server, there will likely be an SMTP mail server out there even if your company is using an Exchange server. The only other hurdle is to make sure that the SMTP mail server will allow you to relay and again, you may need to talk to the administrator if the server bounces your mail. Once these settings are made, click on the "OK" button to save the settings and close the dialog. The last thing to do is to check the security tab to make sure the accounts are properly configured; once done your security settings should look something like this (Figure 10):

Figure 10: Security Settings for the SMTP Server Once everything is setup, click on the "OK" button to save the settings and to close the Default SMTP Virtual Server Properties dialog. Getting Started: In order to get started, unzip the included project and open the solution in the Visual Studio 2008 environment. In the solution explorer, you should note these files (Figure 11):

Figure 11: Solution Explorer The solution contains two projects; the EmailHandler project is a class library; it contains a class entitled, "Emailer.cs" which contains all of the code necessary to send email messages with and without attachments, and to validate email addresses. The second project is entitled, "EmailTestApp"; this is a win forms application which provides an interface that may be used to construct and send email messages using the Emailer class functions. Code: Emailer.cs The Emailer class is used to send email messages with or without attachments, and it contains the

5 of 11

25/05/2013 01:34

Send Email Messages and Attachments Using C#

http://www.c-sharpcorner.com/uploadfile/scottlysle/send-email-messag...

code used to validate the format of the email addresses used to define the email sender and recipient. The class begins with the default and added imports; note the addition of System.Net.Mail, System.Net.Mime, and System.Text.RegularExpressions.

using using using using using using using using using

System; System.Data; System.Configuration; System.Collections; System.Linq; System.Net.Mail; System.Net.Mime; System.Text.RegularExpressions; System.Web;

The next section contains the namespace and class declarations.

namespace EmailHandler { public class Emailer {


The first method contained in this class is used to send an email message without an attachment. The method collects the recipient email address, the sender's email address, the email subject line, and the message body as arguments. Within the code, the recipient's email address is validated, a new mail message is constructed using the passed in arguments, an instance of an SMTP client is created using the mail server (stored in the properties), a Boolean is set to enable the requests to include the default credentials, and then the message is sent. If the action succeeds, the method will return a string indicating that the submittal was successful, else, the exception message will be returned to the caller.

/// <summary> /// Transmit an email message to a recipient without /// any attachments /// </summary> /// <param name="sendTo">Recipient Email Address</param> /// <param name="sendFrom">Sender Email Address</param> /// <param name="sendSubject">Subject Line Describing Message</param> /// <param name="sendMessage">The Email Message Body</param> /// <returns>Status Message as String</returns> public static string SendMessage(string sendTo, string sendFrom, string sendSubject, string sendMessage) { try { // validate the email address bool bTest = ValidateEmailAddress(sendTo); // if the email address is bad, return message if (bTest == false) return "Invalid recipient email address: " + sendTo; // create the email message MailMessage message = new MailMessage( sendFrom, sendTo, sendSubject, sendMessage); // create smtp client at mail server location SmtpClient client = new SmtpClient(Properties.Settings.Default.SMTPAddress); // add credentials client.UseDefaultCredentials = true; // send message client.Send(message); return "Message sent to " + sendTo + " at " + DateTime.Now.ToString() + "."; } catch (Exception ex) { return ex.Message.ToString(); } }
That next method contained in the class is used to send an email message with an attachment. This method is the same as the previous with the exception being that it also accepts an array list containing the paths to files to be included as attachments to the message. The code is annotated and should be easy enough to follow.

/// /// /// ///

<summary> Transmit an email message with attachments </summary>

6 of 11

25/05/2013 01:34

Send Email Messages and Attachments Using C#

http://www.c-sharpcorner.com/uploadfile/scottlysle/send-email-messag...

/// /// /// /// ///

<param name="sendTo">Recipient Email Address</param> <param name="sendFrom">Sender Email Address</param> <param name="sendSubject">Subject Line Describing Message</param> <param name="sendMessage">The Email Message Body</param> <param name="attachments">A string array pointing to the location of each attachment</param> /// <returns>Status Message as String</returns> public static string SendMessageWithAttachment(string sendTo, string sendFrom, string sendSubject, string sendMessage, ArrayList attachments) { try { // validate email address bool bTest = ValidateEmailAddress(sendTo); if (bTest == false) return "Invalid recipient email address: " + sendTo; // Create the basic message MailMessage message = new MailMessage( sendFrom, sendTo, sendSubject, sendMessage); // The attachments array should point to a file location // where // the attachment resides - add the attachments to the // message foreach (string attach in attachments) { Attachment attached = new Attachment(attach, MediaTypeNames.Application.Octet); message.Attachments.Add(attached); } // create smtp client at mail server location SmtpClient client = new SmtpClient(Properties.Settings.Default.SMTPAddress); // Add credentials client.UseDefaultCredentials = true; // send message client.Send(message); return "Message sent to " + sendTo + " at " + DateTime.Now.ToString() + "."; } catch (Exception ex) { return ex.Message.ToString(); } }
The last method contained in the Emailer class is used to validate an email address; this is accomplished by validating the address against a regular expression.

/// <summary> /// Confirm that an email address is valid /// in format /// </summary> /// <param name="emailAddress">Full email address to validate</param> /// <returns>True if email address is valid</returns> public static bool ValidateEmailAddress(string emailAddress) { try { string TextToValidate = emailAddress; Regex expression = new Regex(@"\w+@[a-zA-Z_]+?\.[a-zAZ]{2,3}"); // test email address with expression if (expression.IsMatch(TextToValidate)) { // is valid email address return true; } else { // is not valid email address return false; } } catch (Exception) {

7 of 11

25/05/2013 01:34

Send Email Messages and Attachments Using C#

http://www.c-sharpcorner.com/uploadfile/scottlysle/send-email-messag...

throw; } } } }
Code: frmTestEmailer.cs This form class is the only class contained in the test application; it provides a simple interface for building an email message with attachments. The class begins with the default imports.

using using using using using using using using using

System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; EmailHandler;

The next section contains the namespace and class declarations.

namespace EmailTestApp { /// <summary> /// Test Application Form: /// This application is used to test sending /// email and email with attachments. /// </summary> public partial class frmTestEmail : Form {
Following the class declaration, an ArrayList is declared; this is used to contain the attachments added to the email message.

/// <summary> /// An arraylist containing /// all of the attachments /// </summary> ArrayList alAttachments;
The next bit of code in the application is the default constructor.

/// <summary> /// Default constructor /// </summary> public frmTestEmail() { InitializeComponent(); }
The next bit of code is the button click event handler used to add attachments to the email message. The code adds the file or files selected from an open file dialog to the array list used to store the file paths temporarily; the contents of the array list as written out and displayed in a text box contained on the form.

/// <summary> /// Add files to be attached to the email message /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnAdd_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { try { string[] arr = openFileDialog1.FileNames; alAttachments = new ArrayList(); txtAttachments.Text = string.Empty; alAttachments.AddRange(arr); foreach (string s in alAttachments) { txtAttachments.Text += s + "; "; } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } } }
That next method contained in the class is used to exit the application. It is the button click event

8 of 11

25/05/2013 01:34

Send Email Messages and Attachments Using C#

http://www.c-sharpcorner.com/uploadfile/scottlysle/send-email-messag...

handler for the cancel button.

/// <summary> /// Exit the application /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnCancel_Click(object sender, EventArgs e) { Application.Exit(); }
The last method contained in the test application form is used to send the email message. This is the button click event handler for the send button. This method verifies that all of the required elements of the message are available and then uses those form fields to supply each of the arguments used in the SendMessage or SendMessageWithAttachments methods contained in the Emailer class. Based upon whether or not the message contains any attachments, the appropriate method is called.

/// <summary> /// Send an email message with or without attachments /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSend_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(txtSendTo.Text)) { MessageBox.Show("Missing recipient address.", "Email Error"); return; } if (String.IsNullOrEmpty(txtSendFrom.Text)) { MessageBox.Show("Missing sender address.", "Email Error"); return; } if (String.IsNullOrEmpty(txtSubjectLine.Text)) { MessageBox.Show("Missing subject line.", "Email Error"); return; } if (String.IsNullOrEmpty(txtMessage.Text)) { MessageBox.Show("Missing message.", "Email Error"); return; } string[] arr = txtAttachments.Text.Split(';'); alAttachments = new ArrayList(); for (int i = 0; i < arr.Length; i++) { if (!String.IsNullOrEmpty(arr[i].ToString().Trim())) { alAttachments.Add(arr[i].ToString().Trim()); } } // if there are attachments, send message with // SendMessageWithAttachment call, else use the // standard SendMessage call if (alAttachments.Count > 0) { string result = Emailer.SendMessageWithAttachment(txtSendTo.Text, txtSendFrom.Text, txtSubjectLine.Text, txtMessage.Text, alAttachments); MessageBox.Show(result, "Email Transmittal"); } else { string result = Emailer.SendMessage(txtSendTo.Text, txtSendFrom.Text, txtSubjectLine.Text, txtMessage.Text); MessageBox.Show(result, "Email Transmittal"); } }

} }
Summary

9 of 11

25/05/2013 01:34

Send Email Messages and Attachments Using C#

http://www.c-sharpcorner.com/uploadfile/scottlysle/send-email-messag...

The article provide a simple description of the process required to send an email message with our without attachments. Further, the procedure for configuring IIS and the STMP mail server is described. Add your contents and source code to this ar cle

THIS FEATURE IS SPONSORED BY

DynamicPDF Merger is a developers dream for interac ng with any exis ng PDF documents. Merge, append, split, form ll, a en stamp and so much more.

Power of Yield, Generics and Array in C#


Tags: generics, Generics and Array in csharp (C#), Power of Yield, yield

Dierence between C++ and C#


Tags: c#, c++, c++ and c# syntax

RELATED ARTICLES
Send Email From C# Windows Applica on Using Gmail SMTP How to send Email with an A achment in C# Send an Email with a achment from Outlook, Yahoo, Hotmail, AOL and Gmail Using .NET Framework Mul threading and GDI+ to Enrich the user experience How to Send an Email with A achment Email Sending in ASP.net 2.0 Construct and Send an ICS le as an a achment in the Email SmtpMail and Mail Message : Send Mails in .NET How to Send Email Using Send Mail Task of SSIS Using Microso Message Queues to build Scalable Solu ons

POST COMMENT

Hi I am not able to send mul ple a achments.now i can send only one a achment le.my email id is chandran.nr@gmail.com.please help me to send mul ple a achments Thanks nr

Posted by Narayanan Ramachandran on Feb 27, 2013 I downloaded the sample code, but its always giving Failure sending email. I am using Win7. Can anybody help?

Posted by Pallavi J on Aug 14, 2012 Hi ,i downloaded your code but it is always genera ng error that there is a failure in sending email.So please can you help me in how to congure my smtp in windows 7 ?please help me.Thanks in advance.

Posted by mhamad zarif on Feb 24, 2011 Hi sco , a messagebox promp ng Failure Sending Mail when I execute the code, is there something I missed to congure? Your reply is a great help. Thanks. Posted by Christopher Agunod on Nov 04, 2010 Try to verufy the stack trace, because this excep on message is general and didnt give the exact problem

Posted by Bechir Bejaoui on Aug 21, 2010 View All Comments

COMMENT USING
Add a comment...

Comment using...

Riyaz Quraishi IGNOU SEE THIS, WHAT I LIKE? Reply


Facebook social plugin

2 Like December 24, 2012 at 8:36am

MVPs

MOST VIEWED

LEGENDS

NOW

PRIZES

AWARDS

REVIEWS

SURVEY

CERTIFICATIONS

DOWNLOADS

Hosted By CBeyond Cloud Services

PHOTOS

TIPS

CONSULTING

TRAINING

STUDENTS

MEMBERS

MEDIA KIT

SUGGEST AN IDEA

10 of 11

25/05/2013 01:34

Send Email Messages and Attachments Using C#

http://www.c-sharpcorner.com/uploadfile/scottlysle/send-email-messag...

PRIVACY POLICY | TERMS & CONDITIONS | SITEMAP | CONTACT US | ABOUT US | REPORT ABUSE

2013 C# Corner. All contents are copyright of their authors.

11 of 11

25/05/2013 01:34

Das könnte Ihnen auch gefallen