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 :)

41 Comments

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

  • 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.

  • 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 :)

  • %110 zooming made the samples images readable

  • How can send an email using this to multiple recipients?

  • 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

  • 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

  • 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

  • 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);
    }

  • 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);

  • 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?

  • 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

  • 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.

  • 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.

  • 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.

  • how to embed images inside the mail body using c#
    the images and text will be read from a html file

  • 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!

  • 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

  • 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

  • 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

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

  • Hi stapes,

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

    Regards

  • 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

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

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

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

  • jBzOSR Enjoyed every bit of your blog post.Thanks Again. Keep writing.

  • I value the blog article. Cool.

  • A round of applause for your blog article.Much thanks again. Keep writing.

  • Im grateful for the post. Cool.

  • Thanks for the article post.Thanks Again.

  • Wow, great blog article. Great.

  • I appreciate you sharing this article.Much thanks again. Really Cool.

  • I really like and appreciate your blog article.Thanks Again. Really Great.

  • Yqs2mZ Fantastic article post.Really looking forward to read more. Really Cool.

  • Whats rough now is how the systematic method to life
    isn't fixed. You recognize what I mean? Its nearly because if we crawl through that the life experience with blinders on, not appreciating the true meaning of our own lives.

  • But wanna say that this is invaluable , Thanks for taking your time to write this.

  • Great post, I conceive website owners should discover a large amount from this web blog its rattling
    user genial .

  • This web page is usually a walk-through for all of that the details it suited you with this and didn’t recognize who
    to ask. Glimpse here, and you’ll definitely discover it.

  • QwjZ8n Thanks for sharing, this is a fantastic blog article.Much thanks again. Really Cool.

  • Please let me know if you're looking for a writer for your site. You have some really good articles and I think I would be a good asset. If you ever want to take some of the load off, I'd love to write some articles for your
    blog in exchange for a link back to mine. Please shoot me an email if interested.
    Cheers!

Comments have been disabled for this content.