Share via


SharePoint Provider Hosted Apps: How to Send Email

There are several alternative approaches available to send Emails from SharePoint Provider Hosted apps:

  • General Email Sending method
  • SharePoint Client Object Model (CSOM)
  • SharePoint JavaScript Model (JSOM)

Using general Email Sending method

This is the usual method to send email in ASP.NET. There are advantages over the other two methods:

  • Send attachments to the recipients
  • Send emails to external users (SharePoint 2013 email function can not be used to send emails to external users) 

There are many articles available for this and below is a code sample:

MailMessage mail = new MailMessage("from@mail.com", "to@mail.com");

SmtpClient client = new SmtpClient();

client.Port = 25;

client.DeliveryMethod = SmtpDeliveryMethod.Network;

client.UseDefaultCredentials = false;

client.Host = "smtp.google.com";

mail.Subject = "this is a test email.";

mail.Body = "this is my test email body";

client.Send(mail);

For this, you need to either have an SMTP server set up by yourself or valid authentication for the existing server.

Using SharePoint Client Object Model (CSOM)

This is a commonly used method to send email. You can use a SharePoint Utility class to send an email. One downside is that you cannot send to external users. If you are sending to external users they should be added to your mail exchange.  That needs to be done in advance since it will take some time to reflect such changes.

 

var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

using (var clientContext = spContext.CreateUserClientContextForSPHost())

{

 var emailp = new EmailProperties();

 emailp.BCC = new List<string>{"a@mail.com"};

 emailp.To = new List<string>{"b@mail.com"};

 emailp= "from@mail.com";

 emailp.Body = "<b>html</b>";

 emailp.Subject = "subject";

 

 Utility.SendEmail(_clientContext, properties);

 _clientContext.ExecuteQuery();}

You can use the same method with remote event receivers only by changing SharePoint client context initiation. 

Using SharePoint JavaScript Model (JSOM)

This is very similar to the CSOM but it will only use JavaScript for sending emails.

var mail = {
 properties: {
 __metadata: { 'type': 'SP.Utilities.EmailProperties' },
 From: 'from@mail.com',
 To: { 'results': ['one@mail.com','two@mail.com'] },
 Body: 'some body',
 Subject: 'subject'
 }
 };
  
var getAppWebUrlUrl = decodeURIComponent(utils.getQueryStringParameter("SPAppWebUrl").replace("#", ""));
var urlTemplate = getAppWebUrlUrl + "/_api/SP.Utilities.Utility.SendEmail";
  
$.ajax({
 contentType: 'application/json',
 url: urlTemplate,
 type: "POST",
 data: JSON.stringify(mail),
 headers: {
 "Accept": "application/json;odata=verbose",
 "content-type": "application/json;odata=verbose",
 "X-RequestDigest": $("#__REQUESTDIGEST").val()
 },
 success: function (data) {
 // code
 },
 error: function (err) {
 // code
 }
 });