4

I'm trying to send and save the send email using C# code. But i can't get this done. I can either save the mail, or send it. But i can't get both done.

This is what i have:

public ActionResult Index()
{
    MailMessage message = new MailMessage();

    message.From = new MailAddress("test@mail.com");
    message.To.Add(new MailAddress("mymail@gmail.com"));
    message.Subject = "Test Subject";
    message.Body = "This is a test message";
    message.IsBodyHtml = true;

    // Setup SMTP settings
    SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
    smtp.EnableSsl = true;
    NetworkCredential basicCredential = new NetworkCredential("mymail@gmail.com", "******");

    smtp.UseDefaultCredentials = false;
    smtp.Credentials = basicCredential;
    smtp.Send(message);

    // save
    smtp.EnableSsl = false;
    smtp.PickupDirectoryLocation = @"C:\Temp";
    smtp.Send(message); 

    return View();
}

So first i try to send the email. That works. Then i'm trying to save the email to my HDD. But it never gets saved. It does work when i don't send out the email and try to save it to my HDD right away. But i need to do both.

Anyone any idea how i can get this done? I just simply need to log the send messages.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
w00
  • 26,172
  • 30
  • 101
  • 147

2 Answers2

5

Mail messages in the pickup directory are automatically sent by a local SMTP server (if present), such as IIS. (SmtpClient.PickupDirectoryLocation)

If you want to save to file system, you need to set the DeliveryMethod to SmtpDeliveryMethod.SpecifiedPickupDirectory:

client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory; 
client.PickupDirectoryLocation = @"C:\Temp"; 
client.Send(message); 

See How to save MailMessage object to disk as *.eml or *.msg file

Community
  • 1
  • 1
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
1

You have to change the property DeliveryMethod to SmtpDeliveryMethod.SpecifiedPickupDirectorynot to not send the email.

Just changing the PickupDirectoryLocation will not work, because the property is not used when DeliveryMethod is set to Network (which is the default value).

See MSDN.

tbolon
  • 618
  • 9
  • 17