Search This Blog

Sunday, August 6, 2017

Send Email to TO CC,BCC Using SP.Utilities.Utility and SMPT C# and Rest API

C#
  
public void SendEmailSMPT(string Email, string ApprovalName, string DocumentName, stringstrMessage, string SubjectBody)
        {
            SPWebApplication webApp = SPContext.Current.Site.WebApplication;
            // SPWebApplication webApp = this.Parent as SPWebApplication;
            SPWeb web = webApp.Sites[0].RootWeb;
            string mailFrom = webApp.OutboundMailSenderAddress;
            string smtpAddress = webApp.OutboundMailServiceInstance.Server.Address;
            string mailTo = string.Empty;
            string mailCc = string.Empty;
            string mailBcc = string.Empty;
            string mailSubject = SubjectBody;
            string mailBody = strMessage;
            bool blnIsBodyHTML = true;
            bool mailSent = false;
            SmtpClient smtpClient = null;
            if (Email != "")
            {
                try
                {
                    // Assign SMTP address
                    string BEPSBCCUser = System.Web.Configuration.WebConfigurationManager.AppSettings["BEPSBCCUser"].ToString();
                    smtpClient = new SmtpClient();
                    smtpClient.Host = smtpAddress;
 
                    //Create an email message
                    MailMessage mailMessage = new MailMessage();
                    MailAddress mailAddressFrom = new MailAddress(mailFrom);
                    mailMessage.From = mailAddressFrom;
 
                    if (String.IsNullOrEmpty(mailTo))
                    {
                        MailAddress mailAddressTo = new MailAddress(Email);
                        mailMessage.To.Add(mailAddressTo);
                    }
                    else
                    {
                        MailAddress mailAddressTo = new MailAddress("sRam@ngo.com");
                        mailMessage.To.Add(mailAddressTo);
                    }
 
 
                    if (!String.IsNullOrEmpty(BEPSBCCUser))
                    {
                        string[] arrMailIDs = mailCc.Split(';');
                        for (int i = 0; i < arrMailIDs.Length; i++)
                        {
                            MailAddress mailAddressCc = new MailAddress(arrMailIDs[i]);
                            mailMessage.CC.Add(mailAddressCc);
                        }
                    }
                    else
                    {
 
                        
                        MailAddress mailAddressTo = new MailAddress("Ram@ngo.com");
                        mailMessage.To.Add(mailAddressTo);
                    }
 
                    if (!String.IsNullOrEmpty(mailBcc))
                    {
                        string[] arrMailIDs = mailBcc.Split(';');
                        for (int i = 0; i < arrMailIDs.Length; i++)
                        {
                            MailAddress mailAddressBcc = new MailAddress(arrMailIDs[i]);
                            mailMessage.Bcc.Add(mailAddressBcc);
                        }
                    }
 
 
                    mailMessage.Subject = mailSubject;
                    mailMessage.Body = mailBody;
                    mailMessage.IsBodyHtml = blnIsBodyHTML;
                    mailMessage.Priority = MailPriority.Normal;
 
                    // Send the email
                    smtpClient.Send(mailMessage);
                    mailSent = true;
                }
                catch (Exception)
                {
                    //mailSent = false;
                    ////webApp = this.Parent as SPWebApplication;
                    //SPList taskList = spWeb.Lists["Mate_Error_Notification"];
                    //SPListItem newTask = taskList.Items.Add();
                    //newTask["Title"] = "" + Title + "";
                    //newTask["ErrorDiscription"] = "Error in sending email";
                    //newTask.Update();
 
                }
            }
            else
            {
                //webApp = this.Parent as SPWebApplication;
                //SPList taskList = webApp.Sites[0].RootWeb.Lists["Mate_Error_Notification"];
                //SPListItem newTask = taskList.Items.Add();
                //newTask["Title"] = "" + Title + "";
                //newTask["ErrorDiscription"] = "EmailId is not in group ";
                //newTask.Update();
            }
 
        }
        #endregion
        #region Bind HTML Body of items
        public void BindHtml(string DocumentName, string CreaterName, string ActionBy, stringAprrovedRejectText, string AprrovedRejectComment, string OptenTabType)
        {
            string imagepath = "SiteAssets/Images/tp-1.jpg?ver=1.0";
            string footerpath = "SiteAssets/Images/footer-2.png?ver=1.0";
            strMessage.Append("<div align=\"center\" style='font-family:Calibri'>");
            strMessage.Append("<table width = \"580\" border = \"0\" cellspacing = \"0\" cellpadding = \"0\">");
            strMessage.Append("<tr>");
            strMessage.Append("<td bgcolor = \"#efeff0\" ><img src = \"" + siteurl + "" + "/" +"" + imagepath + "" + "\" width = \"580\" height = \"222\" alt = \"\" /></ td >");
            strMessage.Append("</tr>");
            strMessage.Append("<tr>");
            strMessage.Append("<td><table width = \"580\"  border = \"0\" cellspacing = \"0\" cellpadding = \"0\">");
            strMessage.Append("<tr>");
            strMessage.Append("<td align =\"center\" valign = \"top\" bgcolor = \"#efeff0\"><table width = \"85%\" border = \"0\" cellspacing = \"0\" cellpadding = \"0\">");
            strMessage.Append("<span style=\"font-weight: bold \">Dear " + CreaterName + "</span>");
            strMessage.Append("<tr>");
            strMessage.Append("<td>The uploaded document <a href =\"" + siteurl + "" + "/" +"SitePages/Default.aspx?FN=" + "" + LibraryName + "/" + HdnFolder.Value + "" + "/" + OptenTabType + "\" target=\"new\">" + DocumentName.ToUpper() + "</a> has been  " + AprrovedRejectText + "  by " + ActionBy + " . </td>");
            strMessage.Append("</tr>");
            //strMessage.Append("<tr>");
            //strMessage.Append("<td>Kindly review the same.(Document : <a href=\"" + siteurl + "" + "/" + "SitePages/MDL.aspx?FN=" + "" + LibraryName + "/" + HdnFolder.Value + "" + "/" + OptenTabType + "\" target=\"new\">" + DocumentName.ToUpper() + "</a>  )</td>");
            //strMessage.Append("</tr>");
            strMessage.Append("<tr>");
            strMessage.Append("<td style=\"height:10px;\"></td>");
            strMessage.Append("</tr>");
            if (txtComment.Text != "")
            {
                strMessage.Append("<tr>");
                strMessage.Append("<td><span style=\"font-weight: bold \">" + AprrovedRejectComment + "</span></br> " + txtComment.Text + "</td>");
                strMessage.Append("</tr>");
            }
            strMessage.Append("<tr>");
            strMessage.Append("<td style=\"height:10px;\"></td>");
            strMessage.Append("</tr>");
            strMessage.Append("<tr>");
            strMessage.Append("<p><td > Thanks & Regards  </td></p>");
            strMessage.Append("</tr>");
            strMessage.Append("<tr>");
            strMessage.Append("<td > NGO Document Management Admin </td>");
            strMessage.Append("</tr>");
            strMessage.Append("<tr>");
            strMessage.Append("<td><span style=\"font-size:12.0pt\"><a href=\"mailto: Ram@ngo.com \">Ram@ngo.com</a></span></p></td>");
            strMessage.Append("</tr>");
            strMessage.Append("</table></td>");
            strMessage.Append("</tr>");
            strMessage.Append("</table>");
            strMessage.Append("</td>");
            strMessage.Append("</tr>");
            strMessage.Append("<tr>");
            strMessage.Append("<td align = \"center\" bgcolor = \"#efeff0\" style = \" height:30px\"></td>");
            strMessage.Append("</tr>");
            strMessage.Append("<tr>");
          
            strMessage.Append("<td align = \"center\" bgcolor = \"#e91d24\" style = \" height:50px\" ><img src = \"" + siteurl + "" + "/" + "" + footerpath + "" + "\" width =\"274\" height = \"28\" alt = \"\" /></td >");
            strMessage.Append("</tr>");
            strMessage.Append("</table>");
            strMessage.Append("</div>");
 
        }
        #endregion

REST API:

           Var EmailTo="r@ngo.com";
           var EmailCC=" r@ngo.com ";
            var EmailBCC=" r@ngo.com;Ram.Vinay@ngo.com";
           var htmlBody= BindHtml(DocumentName,AprrovedRejectText,AprrovedRejectComment, OptenTabType,ItemFolderLocation,CreatedBy);
           sendEmail("ngo@ngo.com",CreatedUserEmailId,htmlBody,AprrovedRejectSubject, EmailBCC,EmailCC);  
 
function sendEmail(from, to, body, subject,bcc,cc) {
     console.log(to);
    var urlTemplate = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.Utilities.Utility.SendEmail";
    var formDigest = document.getElementById("__REQUESTDIGEST").value;
    $.ajax({
        contentType: 'application/json',
        url: urlTemplate,
        type: 'POST',
        async:false,
        data: JSON.stringify({
            'properties': {
                '__metadata': { 'type': 'SP.Utilities.EmailProperties' },
                'From': from,
                'To': { 'results': [to] },
                'CC': { 'results': [cc] },
                'BCC': { 'results': [bcc] },
                'Subject': subject,
                'Body': body
            }
        }
      ),
        headers: {
            "Accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": formDigest
        },
        success: function (data) {
        alert('Yes');
          //  var result = data.d.results;
           // var i = result.length;
        },
        error: function (err) {
            alert(JSON.stringify(err));
        }
    });
}
 
 
function BindHtml(DocumentName,AprrovedRejectText,AprrovedRejectComment,OptenTabType,ItemFolderLocation,CreatedBy)
  {
            var strBody = "";
            var imagepath = "SiteAssets/Images/tp-1.jpg?ver=1.0";
            var footerpath = "SiteAssets/Images/footer-2.png?ver=1.0";
            var siteurl="http://s07ssharv008lvs:40072";
            strBody += "<div align=\"center\" style='font-family:Calibri'>";
            strBody += "<table width = \"580\" border = \"0\" cellspacing = \"0\" cellpadding = \"0\">";
            strBody += "<tr>";
            strBody += "<td bgcolor = \"#efeff0\" ><img src = \"" + siteurl + "" + "/" + "" + imagepath + "" + "\" width = \"580\" height = \"222\" alt = \"\" /></ td >";
           strBody += "</tr>";
            strBody += "<tr>";
            strBody += "<td><table width = \"580\"  border = \"0\" cellspacing = \"0\" cellpadding = \"0\">";
            strBody += "<tr>";
            strBody += "<td align =\"center\" valign = \"top\" bgcolor = \"#efeff0\"><table width = \"85%\" border = \"0\" cellspacing = \"0\" cellpadding = \"0\">";
            strBody += "<span style=\"font-weight: bold \">Dear " + CreatedBy + " </span>";
            strBody += "<tr>";
            strBody += "<td>The uploaded document <a href =\"" + siteurl + "" + "/" + "SitePages/Default.aspx?FN="+ encodeURI(ItemFolderLocation) + "" + "/" + OptenTabType + "\" target=\"new\">" + DocumentName.toUpperCase()+ "</a> has been  " + AprrovedRejectText + "  by " + $('#userIdLogin').text()+ " . </td>";
            strBody += "</tr>";
            strBody += "<tr>";
            strBody += "<td style=\"height:10px;\"></td>";
            strBody += "</tr>";
            if (txtComment.Text != "")
            {
                strBody += "<tr>";
                strBody += "<td><span style=\"font-weight: bold \">" + AprrovedRejectComment + "</span></br> " + $('#txtComment').val()+ "</td>";
              
 
                strBody += "</tr>";
            }
            strBody += "<tr>";
            strBody += "<td style=\"height:10px;\"></td>";
            strBody += "</tr>";
            strBody += "<tr>";
            strBody += "<p><td > Thanks & Regards  </td></p>";
            strBody += "</tr>";
            strBody += "<tr>";
            strBody += "<td > NGO Document Management Admin </td>";
            strBody += "</tr>";
            strBody += "<tr>";
            strBody += "<td><span style=\"font-size:12.0pt\"><a href=\"mailto:ngo@ngo.com \">ngo@ngo.com</a></span></p></td>";
            strBody += "</tr>";
            strBody += "</table></td>";
            strBody += "</tr>";
            strBody += "</table>";
            strBody += "</td>";
            strBody += "</tr>";
            strBody += "<tr>";
            strBody += "<td align = \"center\" bgcolor = \"#efeff0\" style = \" height:30px\"></td>";
            strBody += "</tr>";
            strBody += "<tr>";
            strBody += "<td align = \"center\" bgcolor = \"#e91d24\" style = \" height:50px\" ><img src = \"" + siteurl + "" + "/" + "" + footerpath + "" + "\" width =\"274\" height = \"28\" alt = \"\" /></td >";
            strBody += "</tr>";
            strBody += "</table>";
            strBody += "</div>";
           
            return strBody;
  }
  function onUpdateDocSuccess()
  {       
  //alert('Update Success');
  }
  function onUpdateDocFail()
  {
   alert('Failed ');
  }
 

No comments:

Post a Comment