I've put mail settings in app.config and can successfully pull them into a mailSettingsSectionGroup object. However, I'm not sure how to send a message using these settings.
This is what I have so far:
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
MailSettingsSectionGroup mailSettings =
config.GetSectionGroup("system.net/mailSettings") as
System.Net.Configuration.MailSettingsSectionGroup;
What do I need to do next to use the mailSettings object?
SMTP Client in C# and VB.NETThe Simple Mail Transfer Protocol (SMTP) is the only standard protocol for sending mail messages over the Internet. GemBox. Email enables you to work with the SMTP protocol in C# and VB.NET using an SmtpClient class.
App. Config is an XML file that is used as a configuration file for your application. In other words, you store inside it any setting that you may want to change without having to change code (and recompiling). It is often used to store connection strings.
I have a custom Class:
using System;
using System.Configuration;
using System.Net;
using System.Net.Configuration;
using System.Net.Mail;
namespace MyNameSpace
{
internal static class SMTPMailer
{
public static void SendMail(string to, string subject, string body)
{
Configuration oConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var mailSettings = oConfig.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
if (mailSettings != null)
{
int port = mailSettings.Smtp.Network.Port;
string from = mailSettings.Smtp.From;
string host = mailSettings.Smtp.Network.Host;
string pwd = mailSettings.Smtp.Network.Password;
string uid = mailSettings.Smtp.Network.UserName;
var message = new MailMessage
{
From = new MailAddress(@from)
};
message.To.Add(new MailAddress(to));
message.CC.Add(new MailAddress(from));
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = body;
var client = new SmtpClient
{
Host = host,
Port = port,
Credentials = new NetworkCredential(uid, pwd),
EnableSsl = true
};
try
{
client.Send(message);
}
catch (Exception ex)
{
}
}
}
}
}
And this pulls from my app.conf file just fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With