Sunday 12 July 2015

Programmatically Send E-Mail using System.Net.Mail - SharePoint

Hi,
 There are some limitations while sending mails through SPUtility.SendEmail method as I have stated here.

1.   No attachment allowed
2.   Message body size cannot exceed 2048 characters.
3.   The from address will be the “Outbound Sender Address” configured in the central admin.


To Overcome these we are going to follow the below approach.

Using SmtpClient from System.Net.Mail namespace.

Namespaces required:

using System.Net.Mail;
using Microsoft.SharePoint.Administration;


Below is the code for sending Email:

SmtpClient smtpServer = new SmtpClient(webApp.OutboundMailServiceInstance.Server.Address);

MailMessage mail = new MailMessage();
mail.From = new MailAddress("fromEmail@abc.com");
mail.To.Add("toEmail@abc.com");
mail.Subject = "subject";
mail.Body = "body";
mail.BodyFormat = System.Web.Mail.MailFormat.Html;
System.Web.Mail.MailAttachment attachObj = new System.Web.Mail.MailAttachment("path of the attachment in SharePoint");
mail.Attachments.Add(attachObj);

smtpServer.UseDefaultCredentials = true;
smtpsmtpServer.Send(mail);


By Following this we can overcome the limitations faced in SPUtility.SendEmail method.

Have a good Day :)
Happy Coding :)

No comments:

Post a Comment