Enviar Email Usando DNS

Contents
[ ]

Às vezes, enviar emails usando um servidor SMTP não é viável para os requisitos de um projeto. Podemos querer utilizar o registro MX do nome de domínio do destinatário. O seguinte trecho de código mostra como enviar emails usando servidores de mail do domínio do destinatário.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
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);
}
}
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;
}
}
}
}
}
}