1

Hi i'll try to do the TournamentTracker and it works fine until when im stocked with the mailing lesson. Got problems in app.config when i add the lines: <system.net> and <mailsettings>

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="filePath" value="C:\Users\gertl\Source\Repos\TournamentTracker\TextData"/>
    <add key="greaterWins" value="1"/>
    <add key="senderEmail" value="me@outlook.com "/>
    <add key="senderDisplayName" value="TournamentTracker "/>    
  </appSettings>
  <connectionStrings>    
    <add name="Tournaments" connectionString="Server=xxx;Database=Tournaments;Trusted_Connection=True;" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <system.net>
    <mailSettings>
      <smtp deliveryMethod="Network">
        <network host="127.0.0.1" userName="Tim" password="testing" port="25" enableSsl="false"/>        
      </smtp>
    </mailSettings>
  </system.net>
  <!--<startup>
    <supportedRuntime version="v4.0" sku=".NETFrameWork,Version=v4.5.2"/>
  </startup>-->
</configuration>

When i comment away the system.net section the connectionString works again.

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
Gert Lindholm
  • 19
  • 1
  • 2
  • Does your local machine (_127.0.0.1_) have a SMTP server with unblocked port 25 and credentials Tim:testing? If no, maybe the better solution is using external SMTP - check https://stackoverflow.com/a/31356582/1385292 – 1_bug Mar 17 '22 at 08:10
  • The project fail when i came to line trying to read the connectionString Name Tournaments.. – Gert Lindholm Mar 17 '22 at 10:33
  • In the lesson we are suggested to use Papercut as Mail tester before we put external smtp server. – Gert Lindholm Mar 17 '22 at 10:34
  • It's odd. That configuration section should be defined by your machine's `machine.config`. Are you able to check that for whichever version of the .NET CLR you're working with (under `C:\Windows\Microsoft.Net\Framework\\Config` (or `Framework64` if appropriate)) – Damien_The_Unbeliever Mar 17 '22 at 12:13

2 Answers2

0

See if the following helps.

  • Reads email settings
  • Reads connection string
  • Reads one AppSetting value

enter image description here

app.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="mailSettings">
            <section name="smtp_1" type="System.Net.Configuration.SmtpSection"/>
            <section name="smtp_2" type="System.Net.Configuration.SmtpSection"/>
        </sectionGroup>
    </configSections>

    <appSettings>
        <add key="filePath" value="C:\Users\gertl\Source\Repos\TournamentTracker\TextData"/>
        <add key="greaterWins" value="1"/>
        <add key="senderEmail" value="me@outlook.com "/>
        <add key="senderDisplayName" value="TournamentTracker "/>
    </appSettings>

    <connectionStrings>
        <add name="Tournaments" connectionString="Server=xxx;Database=Tournaments;Trusted_Connection=True;" providerName="System.Data.SqlClient"/>
    </connectionStrings>

    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>

    <mailSettings>
        <smtp_1 from="someone@gmail.com">
            <network
              host="smtp.gmail.com"
              port="587"
              enableSsl="true"
              userName="MssGMail"
              password="!@45cow"
              defaultCredentials="false" />
            <specifiedPickupDirectory pickupDirectoryLocation="MailDrop"/>
        </smtp_1>

        <smtp_2 from="karenpayneoregon@gmail.com">
            <network
              host="smtp.gmail.com"
              port="587"
              enableSsl="true"
              userName="oregon@gmail.com"
              password="password"
              defaultCredentials="false" />
            <specifiedPickupDirectory pickupDirectoryLocation="MailDrop"/>
        </smtp_2>

    </mailSettings>

    <system.net>
        <mailSettings>
            <smtp  from="Someone@comcast.net">
                <network
                  host="smtp.comcast.net"
                  port="587"
                  enableSsl="true"
                  userName="MissComcast"
                  password="d@45cat"
                  defaultCredentials="true" />
                <specifiedPickupDirectory pickupDirectoryLocation="MailDrop"/>
            </smtp>
        </mailSettings>
    </system.net>

</configuration>

Class for getting email settings

using System;
using System.Configuration;
using System.IO;
using System.Net.Configuration;

namespace SmtpConfigurationExample.Classes
{
    public class MailConfiguration
    {
        private readonly SmtpSection _smtpSection;


        public MailConfiguration(string section = "system.net/mailSettings/smtp")
        {
            _smtpSection = (ConfigurationManager.GetSection(section) as SmtpSection);
        }

        public string FromAddress => _smtpSection.From;
        public string UserName => _smtpSection.Network.UserName;
        public string Password => _smtpSection.Network.Password;
        public bool DefaultCredentials => _smtpSection.Network.DefaultCredentials;
        public bool EnableSsl => _smtpSection.Network.EnableSsl;
        public string PickupFolder
        {
            get
            {
                var mailDrop = _smtpSection.SpecifiedPickupDirectory.PickupDirectoryLocation;

                if (mailDrop != null)
                {
                    mailDrop = Path.Combine(
                        AppDomain.CurrentDomain.BaseDirectory,
                        _smtpSection.SpecifiedPickupDirectory.PickupDirectoryLocation);
                }

                return mailDrop;
            }
        }
        /// <summary>
        /// Determine if pickup folder exists
        /// </summary>
        /// <returns></returns>
        public bool PickupFolderExists() => Directory.Exists(PickupFolder);

        /// <summary>
        /// Gets the name or IP address of the host used for SMTP transactions.
        /// </summary>
        public string Host => _smtpSection.Network.Host;

        /// <summary>
        /// Gets the port used for SMTP transactions
        /// </summary>
        public int Port => _smtpSection.Network.Port;

        /// <summary>
        /// Gets a value that specifies the amount of time after 
        /// which a synchronous Send call times out.
        /// </summary>
        public int TimeOut => 2000;
        public override string ToString() => $"From: [ {FromAddress} ]" +
                                             $"Host: [{Host}] Port: [{Port}] " +
                                             $"Pickup: {Directory.Exists(PickupFolder)}";
    }
}

Form code

using System;
using System.Text;
using System.Windows.Forms;
using SmtpConfigurationExample.Classes;
using static System.Configuration.ConfigurationManager;

namespace SmtpConfigurationExample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void GetEmailSettingsButton_Click(object sender, EventArgs e)
        {
            var mc = new MailConfiguration();
            var builder = new StringBuilder();

            builder.AppendLine($"User name: {mc.UserName}");
            builder.AppendLine($"From: {mc.FromAddress}");
            builder.AppendLine($"Host: {mc.Host}");
            builder.AppendLine($"Port: {mc.Port}");

            ResultsTextBox.Text = builder.ToString();

        }

        private void GetConnectionButton_Click(object sender, EventArgs e)
        {
            ResultsTextBox.Text = ConnectionStrings["Tournaments"].ConnectionString;
        }

        private void FilePathButton_Click(object sender, EventArgs e)
        {
            ResultsTextBox.Text = AppSettings["filePath"];
        }
    }
}
Karen Payne
  • 4,341
  • 2
  • 14
  • 31
0

This is what I did to resolve the exact same issue when building the Tournament Tracker.

  • I commented out or removed the <system.net>, from the appconfig file: [app.config file][1] [1]: https://i.stack.imgur.com/8pMoW.png

    I installed Fluentemail SMTP NuGet Package: [Fluentemail SMTP NuGet][2] [2]: https://i.stack.imgur.com/nsttr.png

Email Logic.cs

namespace TrackerLibrary {
     public class EmailLogic
    {
        public static void SendEmail(string sender, string recpient, string to, string subject, string body)
        {

            var client = new SmtpSender(() => new SmtpClient(host: "localhost")
            {

                EnableSsl = false,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Port = 25
            });

            Email.DefaultSender = client;

            var mail = Email
                .From(emailAddress: sender)
                .To(emailAddress: to, name: recpient)
                .Subject(subject)
                .Body(body)
                .Send();

        }
    }

TournamentLogic.cs

public static void AlertPlayerToNewRound(PlayersModel p, string teamName, MatchupEntryModel competitor)
        {
            if (p.EmailAddress.Length == 0)
            {
                return;
            }

            string sender = "";
            string to = "";
            string recpient = "";            
            string subject = "";
            StringBuilder body = new StringBuilder();

            if (competitor != null)
            {
                subject = $"You have a new matchup with { competitor.TeamCompeting.TeamName  } !";

            body.Append("Hello ");
            body.Append(p.FirstName);
            body.AppendLine(", ");
            body.AppendLine();                
            body.AppendLine("You have a new matchup !");
            body.Append("Competitor: ");
            body.Append(competitor.TeamCompeting.TeamName);
            body.AppendLine();
            body.AppendLine();
            body.AppendLine("Have a great tournament !");
            body.AppendLine("~Tournament Tracker");
        }
        else
        {
            subject = "You have a bye this round !";

            body.Append("Hello ");
            body.Append(p.FirstName);
            body.AppendLine(", ");
            body.AppendLine();
            body.AppendLine("Enjoy your bye round. ");
            body.AppendLine("~Tournament Tracker");
            }
            sender = GlobalConfig.AppKeyLookup("senderEmail");
            recpient = p.FullName;
            to = p.EmailAddress;
            

            EmailLogic.SendEmail(sender, recpient, to, subject, body.ToString());

After these changes, I was able to successfully send email and receive in Papercut SMTP. I hope this helps.