Search This Blog

Wednesday, August 11, 2021

SharePoint Custom WebService SendingEmail with Javascript

1. Create asp.net webproject

2. Add newItem- webSerive (asmx)


<script type="text/javascript">
        $(function () {
            $("#btnsend").click(function () {
                var hostName = "smtp.gmail.com";
                var portNumber = 587;

                var enableSSL = true;
                var password = "test@123";

                var fromEmail = "from@gmail.com";
                var dispName = "FromdispName";

                var toEmail = "testing@gmail.com";
                var cc = "testing@gmail.com";
                var bcc = "testing@gmail.com";

                var subject = "subjectmsg";
                var body = '<html><body><table><tr><td><a href="http://win-qgdhpl3b82d/erequest/Pages/HReMRServiceRequest.aspx">File 1</a></td><td>bodymsg</td></tr></table></body></html>';
                $.ajax({
                    type"POST",
                    url"http://win-qgdhpl3b82d/erequest/_layouts/15/WebMailService/MailService.asmx/SendGmail",
                    data"{ hostName: '" + hostName + "',portNumber: " + portNumber + ",enableSSL: " + enableSSL + ",password: '" + password + "',fromEmail: '" + fromEmail + "',dispName: '" + dispName + "',toEmail: '" + toEmail + "',cc: '" + cc + "',bcc: '" + bcc + "', subject: '" + subject + "', body: '" + body + "' }",
                    contentType"application/json; charset=utf-8",
                    dataType"json",
                    successfunction (r) {
                        alert(r.d);
                    },
                    errorfunction (r) {
                        alert(r.responseText);
                    },
                    failurefunction (r) {
                        alert(r.responseText);
                    }
                });
                return false;
            });
        });
    </script>

 using System;

using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Configuration;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Services;

namespace NParksMailService
{
    /// <summary>
    /// Summary description for MailService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class MailService : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod]      
        public string SendEmail(string hostNameint portNumberstring fromEmail,string dispNamestring toEmailstring ccstring bccstring subjectstring body)
        {
            if (SendMailMessage(hostNameportNumber,fromEmaildispNametoEmailccbccsubjectbody))
            {
                return "Email sent.";
            }
            else
            {
                return "Email failed to send";
            }
        }
        [WebMethod]
        public string SendGmail(string hostNameint portNumberbool enableSSLstring passwordstring fromEmailstring dispNamestring toEmailstring ccstring bccstring subjectstring body)
        {
            if (SendGmailMailMessage(hostNameportNumberenableSSLpassword,fromEmaildispNametoEmailccbccsubjectbody))
            {
                return "Email sent.";
            }
            else
            {
                return "Email failed to send";
            }
        }
        #region  Members

        /// <summary>
        /// SendMailMessage
        /// </summary>
        /// <param name="toEmail"></param>
        /// <param name="fromEmail"></param>
        /// <param name="bcc"></param>
        /// <param name="cc"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        public bool SendMailMessage(string hostNameint portNumber,string fromEmail,string dispNamestring toEmailstring ccstring bccstring subjectstring body)
        {
            try
            {
                //create the MailMessage object
                MailMessage mMailMessage = new MailMessage();

                //set the sender address of the mail message
                if (!string.IsNullOrEmpty(fromEmail))
                {
                    mMailMessage.From = new MailAddress(fromEmaildispName);
                }
                if (!string.IsNullOrEmpty(toEmail))
                {
                    if (toEmail.Contains("|"))
                    {
                        string[] toList = toEmail.Split('|');
                        foreach (var m in toList)
                        {
                            //set the recipient address of the mail message
                            mMailMessage.To.Add(new MailAddress(m));
                        }
                    }
                    else
                    {
                        //set the recipient address of the mail message
                        mMailMessage.To.Add(new MailAddress(toEmail));
                    }
                }
                //set the blind carbon copy address
                if (!string.IsNullOrEmpty(bcc))
                {
                    mMailMessage.Bcc.Add(new MailAddress(bcc));
                }
                //set the carbon copy address
                if (!string.IsNullOrEmpty(cc))
                {
                    if (cc.Contains("|"))
                    {
                        string[] cclist = cc.Split('|');
                        foreach (var m in cclist)
                        {
                            //set the recipient address of the mail message
                            mMailMessage.CC.Add(new MailAddress(m));
                        }
                    }
                    else
                    {
                        //set the recipient address of the mail message
                        mMailMessage.CC.Add(new MailAddress(cc));
                    }                   
                }
                //set the subject of the mail message
                if (!string.IsNullOrEmpty(subject))
                {
                    mMailMessage.Subject = subject;
                }
                else
                {
                    mMailMessage.Subject = "Subject";
                }

                //set the body of the mail message
                mMailMessage.Body = body;

                //set the format of the mail message body
                mMailMessage.IsBodyHtml = true;

                //set the priority
                mMailMessage.Priority = MailPriority.Normal;
                //create the SmtpClient instance              
                using (SmtpClient mSmtpClient = new SmtpClient(hostNameportNumber))
                {
                    mSmtpClient.Port = portNumber;
                    mSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                    mSmtpClient.UseDefaultCredentials = false;
                    mSmtpClient.Host = hostName;// "npkmail.nparksnet.nparks.gov.sg";
                                                //send the mail message
                    mSmtpClient.Send(mMailMessage);
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// SendMailMessage
        /// </summary>
        /// <param name="toEmail"></param>
        /// <param name="fromEmail"></param>
        /// <param name="bcc"></param>
        /// <param name="cc"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        public bool SendGmailMailMessage(string hostNameint portNumber,bool enableSSLstring passwordstring fromEmailstring dispNamestring toEmailstring ccstring bccstring subjectstring body)
        {
            try
            {
                //create the MailMessage object
                MailMessage mMailMessage = new MailMessage();

                //set the sender address of the mail message
                if (!string.IsNullOrEmpty(fromEmail))
                {
                    mMailMessage.From = new MailAddress(fromEmaildispName);
                }

                if (!string.IsNullOrEmpty(toEmail))
                {
                    if (toEmail.Contains("|"))
                    {
                        string[] toList = toEmail.Split('|');
                        foreach (var m in toList)
                        {
                            //set the recipient address of the mail message
                            mMailMessage.To.Add(new MailAddress(m));
                        }
                    }
                    else
                    {
                        //set the recipient address of the mail message
                        mMailMessage.To.Add(new MailAddress(toEmail));
                    }
                }
                //set the blind carbon copy address
                if (!string.IsNullOrEmpty(bcc))
                {
                    mMailMessage.Bcc.Add(new MailAddress(bcc));
                }

                //set the carbon copy address
                if (!string.IsNullOrEmpty(cc))
                {
                    if (cc.Contains("|"))
                    {
                        string[] cclist = cc.Split('|');
                        foreach (var m in cclist)
                        {
                            //set the recipient address of the mail message
                            mMailMessage.CC.Add(new MailAddress(m));
                        }
                    }
                    else
                    {
                        //set the recipient address of the mail message
                        mMailMessage.CC.Add(new MailAddress(cc));
                    }
                }

                //set the subject of the mail message
                if (!string.IsNullOrEmpty(subject))
                {
                    mMailMessage.Subject = subject;
                }
                else
                {
                    mMailMessage.Subject = "subject";
                }

                //set the body of the mail message
                mMailMessage.Body = body;

                //set the format of the mail message body
                mMailMessage.IsBodyHtml = true;

                //set the priority
                mMailMessage.Priority = MailPriority.Normal;
                //create the SmtpClient instance
                using (SmtpClient smtp = new SmtpClient(hostNameportNumber))
                {                  
                    smtp.Host = hostName;
                    smtp.EnableSsl = true;
                    NetworkCredential NetworkCred = new NetworkCredential(fromEmailpassword);
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = NetworkCred;
                    smtp.Port = portNumber;
                    smtp.Send(mMailMessage);
                }
                return true;
            }
            catch(Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// Determines whether an email address is valid.
        /// </summary>
        /// <param name="emailAddress">The email address to validate.</param>
        /// <returns>
        ///     <c>true</c> if the email address is valid; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsValidEmailAddress(string emailAddress)
        {
            // An empty or null string is not valid
            if (String.IsNullOrEmpty(emailAddress))
            {
                return (false);
            }

            // Regular expression to match valid email address
            string emailRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                                @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                                @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

            // Match the email address using a regular expression
            Regex re = new Regex(emailRegex);
            if (re.IsMatch(emailAddress))
                return (true);
            else
                return (false);
        }

        #endregion

    }
}

Sunday, May 30, 2021

SPClientPeoplePicker - model popup

 <div class="modal" id="my_modal">

    <div class="modal-dialog">
        <div class="modal-content">
            <div style="display:none;" class="pull-right">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="my-input">Delegate Approver Name</label>
                    <input type="text" class="form-control" style="display:none" id="username" ng-model="appProperties.DelegateUser.Title" disabled />
                    <div title="peoplePickerDelegateUser" id="peoplePickerDelegateUser"></div>
                </div>
            </div>
            <div class="modal-footer">
                <input id="btnSubmitRequest" class="frmbutton" value="Submit" ng-click="submitSysRequest(1,$event,appForm)" type="button" />
                <button class="btn btn-warning" type="button" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

                <script>
                     //OnValueChangedClientScript- while user assing fire this event
            SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDelegateUser_TopSpan.OnValueChangedClientScript = function (peoplePickerIdselectedUsersInfo) {
                var userData = selectedUsersInfo[0];
                if (userData !== undefined) {
                    $('#userID').val(userData.Key.split('\\')[1]);
                    $scope.appProperties.SystemAccess.RequestedFor.LoginName = userData.Key.split('\\')[1];
                    // Get the first user's ID by using the login name.
                    getUserId(userData.Key).done(function (user) {
                        $scope.appProperties.SystemAccess.RequestedFor.Id = user.d.Id;
                    });
                }
            };
              // Get the user ID.
        function getUserId(userName) {
            var call = $.ajax({
                url: siteAbsoluteUrl + "/_api/web/siteusers(@v)?@v='" + encodeURIComponent(userName) + "'",
                method: "GET",
                async: false,
                headers: { "Accept": "application/json; odata=verbose" },
            });
            return call;
        }
                </script>

Sunday, March 7, 2021

In SharePoint Online, using CSOM - update Workflow Tasks fields Programatically.

 

using (ClientContext ctx = new ClientContext("http://sp2016:22338/test/sites/"))

            {

                Web web = ctx.Web;

                List oList = web.Lists.GetByTitle("Workflow Tasks");

                ListItem listitem = oList.GetItemById(7407);

                ctx.Load(listitem);

                ctx.ExecuteQuery();

                Hashtable ht = GetExtendedPropertiesAsHashtable(listitem);

                listitem["Completed"] = true;

                listitem["PercentComplete"] = 1;

                listitem["Status"] = "Completed";

                listitem["WorkflowOutcome"] = "Approved";

                listitem["FormData"] = "Completed";

                //listitem["__ModerationComments"] = "Sdfs";

                //listitem["ows_FieldName_Comments"] = "Sdfs";

                //ht["ows_FieldName_Comments"] = "sdsds";

                listitem.Update();

                ctx.ExecuteQuery();

            }