by
56 7

How to Send Email Messages using DNS inside C# & VB.NET Apps

This technical tip explains how to send an email messages using DNS inside .NET applications. Sometimes sending mails using an SMTP server is not feasible for a project’s requirement. We may want to utilize the MX record of the recipient’s domain name.
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/772748/How-to-Send-Email-Messages-using-DNS-ins?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
// Enter here the actual content of the snippet. static void Main(string[] args) { try { MailMessage msg = new MailMessage("add1@domain.com", "add1@domain.com", "test", "this is a test"); msg.CC.Add(new MailAddress("add2@domain.com", "CC Display Name")); DnsSendMessage(msg); } catch (Exception e) { Console.WriteLine(e.Message); } Console.WriteLine("Program finished. Press any key to exit...."); Console.ReadKey(); } /// <summary> /// Use for sent message /// </summary> /// <param name="msg">message to send</param> /// <returns></returns> private static void DnsSendMessage(MailMessage msg) { // Get all the recipients in to, cc and bcc in one collection MailAddressCollection addresses = new MailAddressCollection(); foreach (MailAddress to in msg.To) { addresses.Add(to); } foreach (MailAddress cc in msg.CC) { addresses.Add(cc); } foreach (MailAddress bcc in msg.Bcc) { addresses.Add(bcc); } // send mail using DNS to each address foreach (MailAddress addr in addresses) { //Find mail exchange servers with the help of DnsClient DnsClient dnsClient = new DnsClient(); Question mxQuestion = new Question(addr.Host, QueryType.MX); if (dnsClient.Resolve(mxQuestion)) { // try to send a message foreach (ResourceRecord record in dnsClient.ReceivedMessage.Answers) { MXResourceRecord cnRecord = record as MXResourceRecord; if (cnRecord != null) { try { // Send message SmtpClient client = new SmtpClient(); client.AuthenticationMethod = SmtpAuthentication.None; client.Host = cnRecord.ExchangeName; client.Port = 25; client.Send(msg); Console.WriteLine("Mail sent to " + addr.Address); } catch (SmtpException e) { Console.WriteLine(cnRecord.ExchangeName + ": " + e.Message + Environment.NewLine); continue; } } } } } }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus