SmtpDeliveryMethod.PickupDirectoryFromIis strange

2019-08-16 07:41发布

问题:

I think i need some guru lights!

public void SendEndingMail(string fileName)
        {
            SmtpClient client;
            client = new SmtpClient("smtp.myserver.com", 25);
            //client = new SmtpClient();
            if (!string.IsNullOrEmpty(""))
            {
                System.Net.NetworkCredential credential = new NetworkCredential("", "");
                client.Credentials = credential;
            }
            client.UseDefaultCredentials = true;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            //client.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;

            MailAddress fromAddress = new MailAddress("mailing@mydom.com", "Elec");
            MailAddress toAdrress = new MailAddress("mailing@mydom.com");

            using (System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(fromAddress, toAdrress))
            {

                mailMessage.Attachments.Add(new System.Net.Mail.Attachment(fileName));
                mailMessage.IsBodyHtml = false;
                mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                try
                {
                    client.Send(mailMessage);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
            }
        }

Is that true that: when i set client.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis; It does not matter whichever smtp server i use

        client = new SmtpClient("smtp.myserver.com", 25);
        //client = new SmtpClient();

The both lines are the same since it will use LOCAL IIS ?!!!

Is this is true, it is not normal that the API is build this way!? it is very confusing...

Thanks Jonathan

回答1:

IIRC, when the SmtpClient sends the email, it looks at the .DeliveryMethod value. If the value is Network, then it sends via network. If it is PickupDirectoryFromIis, then it ignores any specified SMTP server (because it just writes and the email to the filesystem), and writes it to the Pickup directory. No network communication takes place.



回答2:

That is a bug in the Send routine - it creates an smtp server object even if one isn't specified, and when it later (after Send) tries to dispose it, it throws an exception. This happens AFTER the mail is successfully placed in the pickup directory, so the mail will be sent.

Workarounds:

  1. Specify localhost as SMTP server. It won't be used, but prevents the exception.

  2. A blind try/catch around the Send method (BAD solution).



标签: c# iis smtp