Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Nadine Fisch 159 posts 429 karma points
    Jun 06, 2018 @ 15:11
    Nadine Fisch
    1

    send Email via Controller and get SMTP Client Settings

    Hi,

    I want to save the SMTP CLient Setting in the Web Config and send my emails via a controller. So I use this code fragment

            MailMessage message = new MailMessage("mail1@test.de", "from@example.de");
            message.Subject = "Subject";
            message.Body =   EmailRenderer.Renderer("Reminder", modul);
            SmtpClient client = new SmtpClient("127.0.0.1", 25);
            client.Send(message);
    

    I don't want to set my SmtpClient-Settings here. Is this possible? How can I retrieve the credentials from the web.config?

    Thank you in advance, Nadine

  • Søren Gregersen 441 posts 1884 karma points MVP 2x c-trib
    Jun 06, 2018 @ 15:24
    Søren Gregersen
    102

    The configuration documentation is here: https://docs.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/network/smtp-element-network-settings

    You just create a new SmtpClient and the settings will already be read.

  • Nadine Fisch 159 posts 429 karma points
    Jun 06, 2018 @ 15:36
    Nadine Fisch
    0

    I just need to call an empty constructor, am I right?

                SmtpClient client = new SmtpClient();
    
  • Anders Bjerner 487 posts 2996 karma points MVP 8x admin c-trib
    Jun 06, 2018 @ 15:39
    Anders Bjerner
    1

    If you have configured the <smtp> element in your Web.config, then yes ;)

  • Nadine Fisch 159 posts 429 karma points
    Jun 06, 2018 @ 15:47
    Nadine Fisch
    0

    ok, thanks this was the question ;)

  • Nicholas Westby 2054 posts 7104 karma points c-trib
    Jun 06, 2018 @ 16:46
    Nicholas Westby
    4

    FYI, the SmtpClient is IDisposable. You may get some dropped emails unless you dispose of it properly. Here's one way of doing that:

    using (var client = new SmtpClient())
    {
        // Your code here.
    }
    

    The using statement will dispose of the SmtpClient for you.

  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies