Geeks With Blogs
Gabriel Lozano-Morán blog

Part of my job is to provide guidance and take on the role of problem solver. Today I got visited by one of our .NET developers with the following problem:

I need to create e-mail (.eml) files based on data I receive from a legacy system. Regarding the complexity of the file format I wonder if there is a way to do this using the Base Class Library (BCL) instead of writing a custom EML file writer.

There is an easy solution but with some drawbacks. What you need to do is wrap all this data in a System.Net.Mail.MailMessage object, change the smtp delivery to use a pickup directory and then set the pickup directory to the folder where you want these .eml files created. Then when you call Send() on the smtp client a new .eml file will be generated. Here is the code:

using System.Net.Mail;

...

MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress("gabriel@pointerx.net", "Gabriel Lozano-Morán");
mailMessage.To.Add("info@pointerx.net");
mailMessage.Subject = "FYI: How to save mail messages to .eml files";
mailMessage.Body = "This can be accomplished by changing the smtp delivery method to a pickup directory...";

SmtpClient smtpClient = new SmtpClient();
smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
smtpClient.PickupDirectoryLocation = @"c:\temp";
smtpClient.Send(mailMessage);

One of the drawbacks is that you can't choose the name of the file instead behind the scenes a new guid will be generated and used as the file name and if that is a problem you need to start working with a System.IO.FileSystemWatcher and rename the files accordingly.

The .EML file created looks as follows:

x-sender: "=?utf-8?Q?Gabriel Lozano-Mor=C3=A1n?=" <gabriel@pointerx.net>
x-receiver: info@pointerx.net
mime-version: 1.0
from: "=?utf-8?Q?Gabriel Lozano-Mor=C3=A1n?=" <gabriel@pointerx.net>
to: info@pointerx.net
date: 16 Nov 2006 08:42:08 +0100
subject: FYI: How to save mail messages to .eml files
content-type: text/plain; charset=us-ascii
content-transfer-encoding: quoted-printable

This can be accomplished by changing the smtp delivery method to a pickup=
directory...


Cross-posted from The .NET Aficionado Posted on Thursday, November 16, 2006 8:12 AM Tips & Tricks | Back to top


Comments on this post: How to: create e-mail message files (.eml)

# re: How to: create e-mail message files (.eml)
Requesting Gravatar...
How to: create e-mail message files (.eml)
Left by Devi on Nov 17, 2012 3:24 AM

# re: How to: create e-mail message files (.eml)
Requesting Gravatar...
I can not able to change the display name for from address
mailMsg.From = new MailAddress("Project Team <APT@domain.com>");

How do i change the display name for From Address of System.Net.Mail.MailMessage

using send email using eFax Server

Urgent
Left by shiv on Apr 15, 2013 6:43 AM

Your comment:
 (will show your gravatar)


Copyright © Gabriel Lozano-Morán | Powered by: GeeksWithBlogs.net