Sending Email From Sharepoint Hosted Apps – Common Pitfalls And Solutions

Common Pitfalls When Sending Email from SharePoint Hosted Apps

Configuring Incorrect Mail Settings in SharePoint

A common pitfall when attempting to send email from SharePoint hosted apps is configuring incorrect mail settings in the SharePoint environment. The mail settings in SharePoint allow the platform to relay messages through an SMTP server. Incorrect configuration of these settings will prevent messaging functionality. Common issues include:

  • Failing to specify an SMTP relay server
  • Providing an invalid SMTP host address
  • Using an incorrect SMTP port number such as 25 or 587
  • Enabling TLS encryption without proper certificate configuration
  • Allowing anonymous access when authentication is required

Not Setting Up an SMTP Relay

Another frequent issue is attempting to send email without configuring an SMTP relay server for SharePoint to leverage. Relying solely on SharePoint’s limited internal messaging capabilities will severely restrict the ability to transmit messages externally. It is vital to establish a dedicated SMTP relay server or mail transfer agent that accepts messages from SharePoint and forwards them to recipients.

Using Hardcoded User Credentials

Many apps attempting to send outbound email from SharePoint will contain hardcoded credentials to authenticate against the SMTP relay server. This poses security risks as usernames and passwords end up easily exposed within the app package. The relay may also block such connections detecting suspicious behavior. It is considered a poor practice to hardcode credentials. Instead, more secure methods like certificate based authentication or secrets management should be implemented to broker the connection between SharePoint and SMTP server.

Failing to Handle Exceptions

Lastly, a simple but impactful oversight is failing to implement proper exception handling when sending email. Any number of issues can disruption email delivery including network errors, authentication problems, invalid addresses etc. Wrapping mail logic in try/catch blocks ensures errors are caught and dealt with gracefully. Lack of exception handling often leads to cryptic failures and broken messaging without clear resolution path.

Solutions for Sending Email Successfully

Verifying Mail Settings in SharePoint

The first recommended step when establishing email capabilities from SharePoint hosted apps is to verify proper mail settings configuration in the SharePoint environment. Within SharePoint administration, confirm an accessible SMTP relay server is defined along with valid credentials and encryption settings to authenticate if necessary. Test the configuration by sending emails internally to verify two-way network communication between SharePoint and SMTP host. Rectifying issues here is crucial before additional troubleshooting elsewhere.

Setting up an SMTP Relay Service

When transmission problems persist, investigate settings on the SMTP host configured in SharePoint environment. In most enterprise scenarios, a dedicated SMTP relay or gateway handles email relay duties. Ensure relay server is on and reachable over the network from SharePoint. Validate open ports for proper TLS/SSL encrypted connections as necessary. Supply credentials and/or configure certificates for SharePoint apps to authenticate successfully. Test relay server transmission externally to confirm operation. Setting up a fully functioning relay service is imperative to offloading email duties from SharePoint server.

Storing Credentials Securely

When developing SharePoint apps that interact with SMTP relay, avoid hardcoding usernames, passwords and other secrets. Instead leverage more secure methods for managing credentials. Options like Azure KeyVault allow central storage of keys, passwords, certificates without exposing sensitive data. Additionally, platform features like SharePoint App-Only policy provide mechanisms granting app permissions without coding passwords. Employing these techniques greatly improves overall security posture.

Implementing Try/Catch Blocks

Despite best efforts, email delivery may still fail due to unanticipated issues. To improve resiliency, wrap SharePoint mail functionality within try/catch blocks. This structures logic to catch generated exceptions allowing clean handling. Example steps include logging error details, surfacing failure notifications to users, and retry mechanisms. Carefully handling errors avoids unpredictable behavior when email fails. Just as importantly, logging details and cleanly failing allows troubleshooting root cause.

Example Code for Sending Email

Configuring the Mail Settings

SharePoint provides API for interacting with environment mail settings programmatically. Configuration steps may include:

// Configure Mail Settings
$web = Get-SPWeb "http://sharepoint.contoso.com"
  
$settings = $web.MailSettings
$settings.From = "[email protected]"
$settings.SMTPServer = "smtp.contoso.com"
$settings.EnableSsl = $true
$settings.Username = "[email protected]"
$settings.Password = Read-Host "Enter Mail Password" -AsSecureString 
             
$web.Update()

Initializing the Email Message

Construct MIME email message specifying key components:

// Build Message 
$message = New-Object System.Net.Mail.MailMessage
$message.From = "[email protected]"
$message.To.Add("[email protected]")
$message.CC.Add("[email protected]")  
$message.Subject = "SharePoint Notification"
$message.Body = "Notification contents"
$message.IsBodyHTML = $true

Adding Recipients

Continue building out message by adding recipients:

// Add Recipients
$message.To.Add("[email protected]")
$message.To.Add("[email protected]")

$message.CC.Add("[email protected]")    
$message.Bcc.Add("[email protected]")

Sending the Message

Transmit message using built-in SharePoint API:

// Send Message
$web = Get-SPWeb "http://sharepoint.contoso.com"
    
try {
  $web.AllowUnsafeUpdates = $true  
  $web.SendEmail($message)
  Write-Host "Email Sent Successfully"
}
catch {
  Write-Host "Error Sending Email: " $_.Exception.Message
}
finally {
  $web.AllowUnsafeUpdates = $false 
  $web.Dispose()
}

Handling Errors

Surround mail logic in try/catch block to handle failures:

try {
  // Send message 
  $web.SendEmail($message) 
}
catch [System.Net.Mail.SmtpException] {
  // Handle SMTP errors
  Write-Host "SMTP error occurred. Check credentials, settings"  
}
catch {
  // Catch all other exceptions
  Write-Host "Failed sending message: " $_.Exception.Message
} 

Leave a Reply

Your email address will not be published. Required fields are marked *