Click here to Skip to main content
15,888,454 members
Articles / Programming Languages / C#
Article

A class for sending emails with attachments in C#.

Rate me:
Please Sign up or sign in to vote.
4.82/5 (62 votes)
28 Feb 20032 min read 490.1K   5.2K   127   141
A class for sending emails with attachments in C#.

Introduction

This is a SMTP client implementation in C#. It handles attachments and sending the body as HTML. It can also do basic (AUTH LOGIN PLAIN) and Base64 (AUTH LOGIN) authentication.

A little while back, I went looking for a (free) class/library to send email with in C#. I found several examples, but none fit my needs. They mostly demonstrated the basics and did not get into attachments. So, I decided to write my own implementation.

I reviewed several RFCs (821,822 mostly) and set about the task. The initial process was pretty straight forward and proved a good lesson in Tcp communication in C#. The attachment process was a little confusing. I understood how to do what I needed to, but was unsure of exactly what, and in what order, to do. The RFC for that and the MIME related ones aren't exactly crystal clear. That's when I found PJ Naughter's CSMTPConnection class. His implementation helped me to see the correct sequencing/structure of the MIME parts and was overall very useful. The version on The Code Project is a little old however, I would recommend getting it from PJ's site. Many thanks to him for a great example.

There is a second project in the solution which is a basic email form that uses this class.

The main class can be used as follows

Example usage of class:

C#
SmtpEmailer emailer = new SmtpEmailer();
emailer.Host = "mymail.host.com";			
emailer.From = "someone@somwhere.com";
emailer.AuthenticationMode = AuthenticationType.Base64;
emailer.User = "myuserid";
emailer.Password = "mypassword";
emailer.Subject = "a test message";
emailer.Body = "this is only a test";
emailer.To.Add("toperson1@nowhere.com");
emailer.To.Add("toperson2@nowhere.com");
emailer.Attachments.Add(new SmtpAttachment(@"c:\file1.exe"));
emailer.Attachments.Add(new SmtpAttachment(@"c:\file2.txt"));      
emailer.SendMessage();

You can also send the body as HTML and include inline images by adding:

C#
emailer.SendAsHTML = true;

When you send as HTML and you want to include images inline in the HTML, you would add the attachment as follows:

C#
emailer.Attachments.Add(new SmtpAttachment(@"c:\mypicture.jpg", 
                        "image/jpg", AttachmentLocation.Inline));

The image will be given an ID that is it filename without extension. You then refer to the image in the html as

<img src="cid:MY_FILENAME_WITHOUT_EXTENSION">

There is also an event, OnMailSent for use with the SendMessageAsync method. If people find this useful, then I will post updates/enhancements along the way. Enjoy.

Version History

1.4 - Added plain text (AUTH LOGIN PLAIN) and base64 (AUTH LOGIN) authentication.
Added CC/BCC properties.

1.3 - Fixed MIME header sequences and several issues with Outlook vs Outlook Express.

1.2 - Fixed quoted-printable encoding problem and an issue with Outlook.

1.1 - Added HTML body support, better MIME handling.

1.0 - Initial release.

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


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
AnswerRe: Mail subject whithout correct iso-8859-1 ponctuation Pin
gabrielbur14-Nov-07 4:17
gabrielbur14-Nov-07 4:17 
GeneralLittle bug with big effect Pin
93Current6-Jul-05 23:04
93Current6-Jul-05 23:04 
QuestionCan you see the image in your mail? Pin
handlim26-Apr-05 0:17
handlim26-Apr-05 0:17 
AnswerRe: Can you see the image in your mail? Pin
The_Mega_ZZTer27-Sep-05 7:05
The_Mega_ZZTer27-Sep-05 7:05 
GeneralRe: Can you see the image in your mail? Pin
sanish197914-Sep-07 0:34
sanish197914-Sep-07 0:34 
GeneralRe: Can you see the image in your mail? Pin
hustyang17-Jun-13 16:52
hustyang17-Jun-13 16:52 
GeneralBCC in Header Pin
stilton@cheese.com13-Apr-05 3:03
stilton@cheese.com13-Apr-05 3:03 
GeneralNice but Spam filters let the Emails not pass Pin
93Current5-Apr-05 14:26
93Current5-Apr-05 14:26 
Hi!

I tested the library in different ways. It seems to be very safe. But after turning on a Spam filter at my Email account I saw that the Emails not passed anymore. I fixed (till now) 3 scored points of search, which takes Emails to Spam Mails:

1. NO_REAL_NAME:
------------------------
The filter looks for Name and Email address in the 'From:'-line. The library do not support this. To fix this, you should declare another property say 'FromName' in the SmtpEmailer.cs and extend (go to the point where you build the headers) 'buf.Append("FROM: ");buf.Append(from);'. You get something like this: 'buf.Append("FROM: " + from_name + "<");buf.Append(from + ">");'. This solves the first not high scored Spam filter search point.

2. INVALID_DATE:
------------------------
This one applies to all who use other system languages than (US) English, e.g. myself. My system setting is German. The library build a header for date: 'DateTime today = DateTime.Now;buf.Append("DATE: ");buf.Append(today.ToLongDateString());'. This affects in sending a No-Standard-Date. Standard would be 'Tue, 05 Apr 2005 22:26:58 (GMT)' or 'Tue, 05 Apr 2005 22:26:58 +0200'. I get at this point 'Dienstag, 5. April 2005'. I modified this as follows: 'DateTime today = DateTime.Now;string strToday = today.ToString("r");strToday=strToday.Replace(strToday.Substring(strToday.Length-3,3),"+0200");buf.Append("DATE: ");buf.Append(strToday);'. Now I get a standard date format for this Email header.

3. RATWARE_HASH_2_V2
------------------------
This is a very high scored search point and belongs to the header 'X-Mailer'. I would not swear to that, but I think the spam filter software goes through a list with known Email software names and if the name you specify at 'con.SendCommand("X-Mailer: smw.smtp.SmtpEmailer");' do not match this list... I don't know another solution but: '//con.SendCommand("X-Mailer: smw.smtp.SmtpEmailer");'. (This header is optional).

MIME_BASE_64_BLANKS (Extra blank lines in base64 encoding): High scored, No solution.
BAYES_00 (Bayesian spam probability is 0 to 1%): No solution.


Every comments are welcome!
Sebastian.
GeneralRe: Nice but Spam filters let the Emails not pass Pin
Denis Kozlov3-Jan-06 10:37
Denis Kozlov3-Jan-06 10:37 
GeneralRe: Nice but Spam filters let the Emails not pass Pin
93Current3-Jan-06 12:02
93Current3-Jan-06 12:02 
GeneralError message handling Pin
93Current16-Feb-05 2:05
93Current16-Feb-05 2:05 
GeneralDisplayName Pin
Dekkie27-Jan-05 9:44
Dekkie27-Jan-05 9:44 
GeneralRe: DisplayName Pin
Anonymous16-Feb-05 1:50
Anonymous16-Feb-05 1:50 
GeneralDisplayName 2 Pin
Anonymous16-Feb-05 1:55
Anonymous16-Feb-05 1:55 
GeneralRe: DisplayName 2 Pin
Anonymous27-Feb-05 1:30
Anonymous27-Feb-05 1:30 
GeneralRe: DisplayName 2 Pin
93Current5-Apr-05 15:00
93Current5-Apr-05 15:00 
QuestionNice component. But how to set time? Pin
tracerken18-Jan-05 21:55
tracerken18-Jan-05 21:55 
AnswerRe: Nice component. But how to set time? Pin
93Current11-Apr-05 12:47
93Current11-Apr-05 12:47 
GeneralRe: Nice component. But how to set time? Pin
tracerken11-Apr-05 22:21
tracerken11-Apr-05 22:21 
GeneralAttachments Pin
Hugo Migneron25-Oct-04 7:31
Hugo Migneron25-Oct-04 7:31 
GeneralRe: Attachments Pin
Sascha Sertel28-Oct-04 6:02
Sascha Sertel28-Oct-04 6:02 
GeneralRe: Attachments Pin
Hugo Migneron28-Oct-04 6:41
Hugo Migneron28-Oct-04 6:41 
QuestionOnMailSent event in Visual Basic .Net ? Pin
Mark Sanchez12-Oct-04 20:45
Mark Sanchez12-Oct-04 20:45 
AnswerRe: OnMailSent event in Visual Basic .Net ? Pin
mr_jimmybob14-Oct-04 12:36
mr_jimmybob14-Oct-04 12:36 
GeneralInline Images not rendering correctly Pin
s3mt3x22-Aug-04 3:17
s3mt3x22-Aug-04 3:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.