Processing messages

When we receive a request to send an email, we will be receiving an EmailSendRequest message. That message should be fully populated with all of the information we need to send the email. In the following code, our ProcessEmailSendRequestMessage is triggered as soon as we receive a request message. From there, we will pass the message to our SendMessage function to handle sending the email:

bool ProcessEmailSendRequestMessage(EmailSendRequest msg)
{
Console.WriteLine("Received Email Send Request Message");
RILogManager.Default?.SendInformation("Received Email Send Request Message");
SendEmail(msg);
return true;
}

Now that the framework of our microservice is complete, let's create a routine that will send an email, but we're going to do it with a twist. Let's see if you can figure out what is happening differently.

Here's how we send a simple message. Before looking at it, I want to point out that for those wanting to learn and for those with a creative spirit, this might be the most individually customized, influenced object we deal with in the entire book. You can absolutely explode with creative ideas of how to create fancy or professional looking emails, how to substitute in previously designed email templates, and much more:

EmailSendRequest m = new EmailSendRequest();
m.Subject = "Test";
m.To = "[email protected]";
m.From = "[email protected]";
m.Body = "This is a test of the email microservice system";
Console.WriteLine(EmailSender.Send(m.From, m.To, m.Subject, m.Body)
? "Email sent" : "Email not sent");

And here's our Send function:

public static bool Send(string from, string to, string subject, string body)
{
string domainName = GetDomainName(to);
IPAddress[] servers = GetMailExchangeServer(domainName);
foreach (IPAddress server in servers)
{
try
{
SmtpClient client = new SmtpClient(server.ToString(), SmtpPort);
client.Send(from, to, subject, body);
return true;
}
catch
{
continue;
}
}
return false;
}

Can you see yet what it is that we are doing differently compared with probably every other email.send routine you've done? If not, think harder. Notice that the SmtpClient constructor and Send calls are embedded inside a for loop. This for loop is going to enumerate over every possible server IP address for mail exchanges until either one works, or until we have completed without success.

Internally, we have our FindDnsServers function, and its job is to get the domain server for our email address by checking the registry and returning all the values. The probability that one of them will work is very high, and this way we don't have to do the normal SmtpClient initialization and provide usernames and passwords.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset