Enviar correo usando DNS
Contents
[
Hide
]
A veces, enviar correos electrónicos utilizando un servidor SMTP no es factible para los requisitos de un proyecto. Puede que queramos utilizar el registro MX del nombre de dominio del destinatario. El siguiente fragmento de código muestra cómo enviar correos electrónicos utilizando los servidores de correo del dominio del destinatario.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} | |
} | |
} | |
} | |
} |