Search This Blog

Friday, July 22, 2016

SPUtility.SendEmail vs. SmtpClient.Send


When there is requirement to send email in SharePoint , developers usually use
Microsoft.SharePoint.Utilities.SPUtility.SendEmail(web, false, false, emailId, MailSubject, htmlBody);
due to the fact that this class automatically uses the default SMTP configuration settings of the SharePoint.
Developers avoid using System.Net.Mail.SmtpClient class to send emails because they need to have the SMTP configuration before using this class. However they can use the below code snippet to automatically detect the 
SMTP settings with the help of SPWebApplication.
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.IsBodyHtml = true;
message.Body = html;
message.From = new System.Net.Mail.MailAddress(SPContext.Current.Site.WebApplication.OutboundMailSenderAddress);
SPOutboundMailServiceInstance smtpServer = SPContext.Current.Site.WebApplication.
OutboundMailServiceInstance;
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(smtpServer.Server.Address);
message.To.Add(emailId);
message.Subject = "Test";
smtp.Send(message);
 A major drawback of using SPUtility.SendEmail is of its character limitation of 2048 per line 
which strips out the content of the Email after sending while System.Net.Mail.SmtpClient does 
not haveany such limitation.

No comments:

Post a Comment