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

    }
}

No comments:

Post a Comment