Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save an email instead of sending when using SmtpClient?

Tags:

c#

.net

email

smtp

I am using SmtpClient to send an email with an attachment. However for a certain batch we need to somehow save the MailMessage instead of sending them. We are then thinking/hoping to manually upload the messages to the users drafts folder.

Is it possible to save these messages with the attachment intact (impossible, I would have thought). Or alternatively upload the messages to a folder in the users account?

If anyone has any experience of this, I'd much appreciate a bit of help or a pointer.

like image 372
user17510 Avatar asked Feb 19 '09 23:02

user17510


2 Answers

When testing in ASP.NET we save our emails to a folder rather then send them through an email server. Maybe you could change yourweb.config settings like this for your batch?

<system.net>   <mailSettings>     <smtp deliveryMethod="SpecifiedPickupDirectory">       <specifiedPickupDirectory pickupDirectoryLocation="c:\Temp\mail\"/>     </smtp>   </mailSettings> </system.net> 

Additional Info:

  • MSDN: <specifiedPickupDirectory> Element (Network Settings)
  • Configuring SmtpClient to drop emails in a folder on disk
like image 154
Leah Avatar answered Oct 14 '22 18:10

Leah


As well as the SpecifiedPickupDirectory information of the other answers, if you want to ensure your emails are sent to a folder relative to the site root - handy in testing on build servers where you don't know the paths - you can add a quick check in your email sending code:

    SmtpClient client = new SmtpClient();     ...      // Add "~" support for pickupdirectories.     if (client.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory && client.PickupDirectoryLocation.StartsWith("~"))     {         string root = AppDomain.CurrentDomain.BaseDirectory;         string pickupRoot = client.PickupDirectoryLocation.Replace("~/", root);         pickupRoot = pickupRoot.Replace("/",@"\");         client.PickupDirectoryLocation = pickupRoot;     } 

And your tests will look something like this (make sure you use App_Data so IIS can write to the folder):

    // Arrange - get SitePath from AppDomain.Current.BaseDirectory + ..\     string pickupPath = Path.Combine(SitePath, "App_Data", "TempSmtp");     if (!Directory.Exists(pickupPath))         Directory.CreateDirectory(pickupPath);      foreach (string file in Directory.GetFiles(pickupPath, "*.eml"))     {         File.Delete(file);     }      // Act (send some emails)      // Assert     Assert.That(Directory.GetFiles(pickupPath, "*.eml").Count(), Is.EqualTo(1)); 
like image 44
Chris S Avatar answered Oct 14 '22 16:10

Chris S