A common question I get is, “why doesn’t my SMTP email code that I wrote for my other website not work on Azure Web App?” Additionally, I sometimes get this exception sent to me, “System.Net.Mail.SmtpException: Transaction failed. The server response was: #.#.# Service unavailable; Client host [...] blocked using; Blocked”.
I also wrote an article here about sending emails using an SMTP server hosted with Office 365. #O365 #Office365
The reason for the first issue is that currently, a common way to send an email from an Azure Web App is by using SendGrid. You enable / subscribe to SendGrid via the Market Place by selecting the NEW link on the bottom left of the Azure Management console, similar to that shown in Figure 1.
Figure 1, setup SendGrid for Azure App Services, SMTP not working
Once configured, you should see it in the list of available Market Place apps. Clicking on the SendGrid app, will redirect you to a page similar to that illustrated in Figure 2.
Figure 2, Configure SendGrid on an Azure App Services
Clicking on the MANAGE link on the bottom navigation bar, opens the SendGrid website where you can get your user id and password. Additionally you can find many examples in many languages to get a proof of concept page working on your Azure App Services Web App site.
Myself, being a strong C# programmer didn’t have much problem getting that example to work, but I did struggle with the PHP one. Here is a library you can use to get a PHP SendGrid solution up and running pretty quick. Simply add the code to a PHP file, shown in Listing 1, and deploy it to root directory of the PHP library.
Listing 1, consume PHP SendGrid PHPMailer code, using SendGrid
$mail = new PHPMailer;
//$mail->SMTPDebug = 3; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.sendgrid.net'; // Specify main/backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'YOUR USERNAME'; // SMTP username
$mail->Password = 'YOUR PASSWORD'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS/SSL encryption
$mail->Port = 587; // TCP port to connect to
$mail->From = 'firstname.lastname@example.org';
$mail->FromName = 'From SendGrid website';
$mail->addAddress('email@example.com', 'Support'); // Add a recipient
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
echo 'Message has been sent';
The second issue is because the IP address for your Azure App Services Web App has been blacklisted. Some potential work arounds for this are:
- Configure an Azure VNet to VNet Connection
- Using VNET integration and Hybrid connections with Azure Web Apps (Websites)
- Introducing App Service Environment