There are several alternative approaches available to send Emails.
- 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)
code:
MailMessage mail = new MailMessage("[email protected]", "[email protected]");
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);
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.
code:
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
var emailp = new EmailProperties();
emailp.BCC = new List<string>{"[email protected]"};
emailp.To = new List<string>{"[email protected]"};
emailp.From = "[email protected]";
emailp.Body = "<b>html</b>";
emailp.Subject = "subject";
Utility.SendEmail(_clientContext, emailp);
_clientContext.ExecuteQuery();
}
Using JavaScript and the SharePoint REST-API
This is very similar to the CSOM but it will use only JavaScript for sending emails.
code:
var mail = {
properties: {
__metadata: { 'type': 'SP.Utilities.EmailProperties' },
From: '[email protected]',
To: { 'results': ['[email protected]','[email protected]'] },
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
}
});
Reference: