Ads

Saturday, 23 March 2013

C# code to send Email in Sharepoint using SPUtility.SendEmail using HTML tags.

SPUtility.SendEmail has 4 overloaded method in Sharepoint for sending email to any email address. We will discuss mainly 2 methods which can handle every type of html email body in Sharepoint.
1) SPUtility.SendEmail(SPWeb web, bool fAppendHtmlTag, bool fHtmlEncode, string to, string subject,string htmlEmailBody)
Most of the time we may need to write a html email body having different styles for text and fonts.Then we can go for this method without much overhead.We can write our email body using html tags but to display our actual email content without html tags we have to take care of one important thing otherwise we will get the email with html tags embedded.
We will have to pass 'false' for 'fHtmlEncode' and 'true' for 'fAppendHtmlTag' as boolean value.
Limitations: We cannot send email to one than one person at a time with this method.
2) SPUtility.SendEmail(SPWeb web, StringDictionary messageHeaders, string messageBody)
This overloaded method has more functionality than the one we discussed above.The second parameter includes all the details about the sender,receiver, subject, cc, bcc, and content-type which we will have to add by making object of StringDictionary class and including System.Collections.Specialized in the beginning.We can send email to any number of people at a time.
For example:

//send mail to the member               
StringDictionary headers = new StringDictionary();
headers.Add("to", currCtxt.Web.CurrentUser.Email);
headers.Add("cc", "xyz@abc.com");
headers.Add("bcc", "");
headers.Add("from", "email@add.com");
headers.Add("subject", "Email Subject");
headers.Add("content-type", "text/html");
string bodyText = "Hello how are you?";
SPUtility.SendEmail(currCtxt.Web, headers, bodyText.ToString());
NOTE:  One important thing needs to be taken care of in the 'from' we can't provide email address randomly because that will result in no mail to our inbox.The reason behind this is that SharePoint has its setting for SPUtility.SendEmail() method which by default picks the 'From address' from Central administartion-> Operations-> Outgoing E-Mail Settings. Its better not to experiment with 'From addres' without knowledge.Leaving the above reason there will be no problem in sending email to any email address of any domain.

No comments:

Post a Comment

Ads