Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

This might seems a naive post about sending email, especially when there are hundreds of posts out there. However, most of these posts don't show a complete or comprehensive example for the beginners on how to send email with more options. I'm sure when you search for the phrase "Sending email using C#" you will find a plenty of results, but if you look closely you will see every post focuses on one thing perhaps attachment, multiple recipients, etc.


Note: This post is intended for beginners and folks who want to copy the class and use it directly in their application :)


I remember that I wrote a class for sending email, which I still use till today, and I thought to share it with you.  This class provides most of the basic functionalities that I need and it covers:

  •  Send Sync and Async emails.
  •  Attachments.
  •  Send email to multiple recipients.
  •  Send text and HTML email.

The class provide many overloading methods for the send email, we will just focus here on two basic methods one for Sync and the other for Async. To switch between Sync and Async I created a delegate method as follow
 
Send delegate method

The synchronous send email method would look like this
 
Synchronuos send email method

The Asynchronous send email method would look like this
 
Asynchronuos send mail method

The main method that will do the sending is the following
 
 The main send email method
 

In the config file configure the SMTP server host

SMTP Cofig Section

if you want you can add the follwing code to the main method above to explicitly set the SMTP host as follow

set the SMTP server host

 

Hope this help :)

Attachment: Utilities.zip
Published Friday, December 07, 2007 1:08 PM by nawaf227
Filed under: , ,

Comments

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Saturday, December 08, 2007 3:14 AM by Pieter

Your code examples are illegible. But when the Internet browser view is set on 150% there's no problem.

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Saturday, December 08, 2007 5:36 AM by nawaf227

Yah, I noticed that now!!!

I have posted it using a laptop display set to 1400 * 1050, I’m truly sorry,  

Thank you very much for the notice, I will correct that as soon I get home.

Thanks a lot.

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Saturday, December 08, 2007 8:07 AM by nawaf227

That’s really weird, when I saw it from my 1280 * 800 work’s display monitor it wasn’t so clear, but now I’m using my laptop which is set to the same resolution, yet it seems fairly clear except the last two big images.

Anyway, you can download the code for clear view :)

# Link Listing - December 7, 2007

Saturday, December 08, 2007 10:52 AM by Christopher Steen

Link Listing - December 7, 2007

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Thursday, May 15, 2008 2:12 AM by Ozan BAYRAM

%110 zooming made the samples images readable

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Friday, May 30, 2008 5:53 AM by Paolo

How can send an email using this to multiple recipients?

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Friday, May 30, 2008 6:06 AM by nawaf227

Hi,

You can do like this:

Utiltiies.Mail.SendMail.SendSync("from@sample.com",

               new string[] { "to1@sample.com", "to2@sample.com" },

               "Subject", "message body");

Hope this helps

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Wednesday, July 23, 2008 11:08 AM by Paul Hernández

I'm trying to use your code, but I can't make an attachment[] to call the function. I'm trying this:

AttachmentCollection aCollection;

if (FileUpload.HasFile){

Attachment a1 = new Attachment(FileUpload.Content, FileUpload.Name);

aCollection.Add(a1)}

I tried with Attachment[] aCollection, but it doesn't work too

Regards

Paul

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Wednesday, July 30, 2008 7:25 AM by nawaf227

Hi Paul,

I'm not 100% sure, but I think your problem has to do with disposing the IO stream. Try to make sure not to close the file stream "FileUpload" untill you send the email, and close it right after sending the email like this

               if (aCollection!= null)

               {

                   // Release any resource used by the attchement.

                   foreach (System.Net.Mail.Attachment att in aCollection)

                   {

                       try { att.Dispose(); }

                       catch { }

                   }

               }

Also try to set FileUpload.FileContent.Position = 0;

Hope this helps

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Thursday, July 31, 2008 10:21 AM by Scott Kellman

I am trying to send attachments using the following code but the attachment will not attach even though it shown up in the message.attachments. Any help would be greatly appreciated.

private void EmailForm()

       {

           SmtpClient smtp = new SmtpClient("smtp host name");

           MailMessage msg = new MailMessage();

           //create the render engine

           RenderEngine re = new RenderEngine();

           //create the bitmap and populate the first page

           Bitmap image = re.RenderPage((FormPage)form.Pages[0], 38);

           //traverse the pages and render them

           if (form.Pages.Count > 1)

           {

               for (int i = 1; i < form.Pages.Count; i++)

               {

                   //create the bitmap

                   image = re.RenderPage((FormPage)form.Pages[i], 38);

               }

           }

           byte[] byteMe = imageToByteArray(image);

           MemoryStream ms = new MemoryStream(byteMe);

           Attachment att = new Attachment(ms, "image/jpeg");

           try

           {

               msg.Attachments.Add(att);

           }

           catch (Exception ex)

           {

               ErrorLogger.LogMessage("Attachment add failed" + ex);

           }

           //populate the body and subject

           msg.Body = "Image is attached";//ms.ToArray().ToString();

           msg.Subject = "Image of Form With Session Id " + this.SessionId;

           smtp.Send("skellman@rovertechfusions.com", "skellman@rovertechfusions.com", msg.Subject, msg.Body);

       }

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Thursday, July 31, 2008 1:15 PM by nawaf227

Hi Scott,

in your code at the last line, you don't seem to send the attachment. I think you should write instead

smtp.Send(msg);

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Wednesday, August 06, 2008 12:45 AM by Fat

I have tried to utilise this in VS 2008 and have experienced difficulties to get the APPsettings from here.

SmtpSection smtpSec = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");

everything is null.

any hint?

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Wednesday, August 06, 2008 2:41 AM by nawaf227

Hi

I have tested it on VS 2008 SP1 beta, and no problems. I have no clue really what's wrong but try to make sure you have mailSettigs in the config there.

Hope this helps

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Wednesday, August 06, 2008 8:57 PM by Fat

Thanks for the reply.  One thing I have realised is that in VS2008, it requires the FROM address to be specified while you only had SENDER.  Not sure why things changed, but that is the something you may like to consider update for 2008 compatibility.

Thanks.

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Wednesday, August 06, 2008 9:11 PM by Fat

Sorry, another question.

I am trying to utilise your code to send email from Gmail.

it works if I add an extra line at the end, please see in code comments

---------------

emailClient.Send(message);  // this will do the sending

// Call the send delegate method

sendDelegate(emailClient, message); // it goes to the delegate and the server always timeout from here, with or without the extra send prior to this.

---------------

do you have any idea what I have done wrong?

Thanks.

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Wednesday, August 06, 2008 9:38 PM by Fat

Sorry, it was timed out because I was in my debug mode and the stepping through was too slow.  All good now, have to think of ways to utilise the config file from different project and to get Async to work.

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Tuesday, August 26, 2008 7:49 AM by hi

how to embed images inside the mail body using c#

the images and text will be read from a html file

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Monday, September 08, 2008 3:49 AM by ranjith

I need a email application with multiple attachment.Iam developing my application in asp.net+c#.Main problem that iam facing is it should work as in GMail.help me

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Tuesday, September 09, 2008 6:23 AM by Phillip

Can someone advise me on what to put in the USEING section at the top, i have the following:

using System;

using System.ComponentModel;

using System.Collections.Generic;

using System.Diagnostics;

using System.Text;

using System.Net;

using System.Net.Mail;

using System.Media;

using System.Windows.Forms;

I'm i missing some thing?

Also i'm getting the following error:

Error 2 The name 'Send' does not exist in the current context

Please Help!

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Monday, September 22, 2008 2:43 AM by Philip

I'm sooooo dumb, sorry.

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Wednesday, October 01, 2008 6:19 AM by Elmanuel Minh Duong

Hello Every body !!!

Sorry everybody. help me, i'm begining learn C#. i can;t understand "UtilityException". Who can help me now; and  SmtpSection , how can use it ??/

Thank's so much

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Wednesday, October 01, 2008 11:40 AM by nawaf.albadia

Hi Elmanuel,

UtilityException is  custom Exception, you can change it to System.Exception or whatever you exception you want. But if you do then make sure you change all the methods.

As for the SmtpSection you need to add reference to the System.Configuration from the references menu.

Also you can remove the smtpSection section, because the framework will read the default settings automatically.

Hope this helps

Nawaf

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Monday, October 06, 2008 1:02 AM by urname

comments

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Friday, October 10, 2008 5:29 AM by Jarred

Hi everyone, im quite new to this and im starting a project. I just want to find out if its possible to implement this code in a c# Windows Application. Iv done something similar when working with web developer but im not sure if i can do the same in a windows form. Any help would be much appreciated

Thanks in Advance

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Tuesday, November 11, 2008 8:43 AM by stapes

Why is your code displayed as a picture? It makes it impossible to cut + paste. Prat.

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Tuesday, November 18, 2008 12:19 PM by nawaf.albadia

Hi stapes,

Why do you need to copy and paste, where you can get the entire source code. Please check the attachment section.

Regards

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Friday, January 08, 2010 5:44 AM by neha

I need to send a mail in C# wherein the sender is stored in a variable ...

e.g MailMessage msg=new MailMessage();

msg.from = new MailAddress("asd@sfdf.com")

Instead of asd@sfdf.com I need to pass a variable..

please help

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Monday, January 11, 2010 4:08 PM by Cire1507

Sad that I cannot read the images on your web page. I was very much interested in seeing the code. Regards

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Friday, March 26, 2010 12:05 PM by fei

there are no images at all. I'm eager to see your codes.

Thanks

# re: Sending Email in C# (Sync/Async, Multiple recipients, Attachments, etc).

Thursday, April 29, 2010 5:17 PM by red

how can we get back the undelivered email information when we are sending emails through SMTP?

Leave a Comment

(required) 
(required) 
(optional)
(required)