Wednesday, October 07, 2009

How to send Email on Windows Azure Application

Today during “TechStart Windows Azure Training Program” session I got a question about sending Emails from Windows Azure Application.
I was expecting that Windows Azure itself provide a SMTP relay and i could easily send email using SmtpClient Class but after checking Azure documentation, I found that unfortunately it does not support it, now what, how to send email from Azure application… ?
As almost all outbound ports are open on windows azure (including 25), so this can be a good news for us.. we can use external SMTP to send email.
also another good news is after March CTP Windows Azure offers the option of running the code in your Web and worker roles under full trust. (To enable full trust, simply add the enableNativeCodeExecution attribute to your role in the Service Definition file and set the attribute value to true)
e.g.
<WebRole name="WebRole" enableNativeCodeExecution="true">
so i guess now we are ready to send an Email from our Azure application…
Standard code which we use to send email in our ASP.NET using SmtpClient class applications works fine with Windows Azure Application.
so Open Visual Studio, create a Cloude Service Applications and add a WebRole to it. now on design a Page which will accept a TO address and a body of your message, and a send button :), now copy paste following code to Button click event, replace the credential details with actual credentials and Test it.

SmtpClient myClient;
MailMessage myMessage;

myClient = new SmtpClient("mysmtp.cognitioninfotech.com", 25);
myClient.Credentials = new NetworkCredential("myAlert@cognitioninfotech.com", "mypassword");
myMessage = new MailMessage(new MailAddress("myAlert@cognitioninfotech.com"), new MailAddress(txtTo.Text));
myMessage.Body = txtMessage.Text;
myMessage.Subject = "Test Email";

try
{
    myClient.Send(myMessage);
    lblstatus.Text = "Sent";
}

catch (Exception ex)
{
    lblstatus.Text = ex.ToString();
}





2 comments:

Joshua said...

The problem with the relay solution is that you still need to have an email server to relay through. Amazon EC2 is having the same trouble as Azure with email sending. There are some traditional relay services out there like AuthSMTP or others, or you could try a new solution like Elastic Email (http://elasticemail.com). We recently switched over our Amazon hosted CMS service.

outbound email filtering said...

Azure application still has a few glitches on their email support system.