public string WorkFromHomeStatus(string cmt, string userid, string status, string leaveid, string managermail, string managerid, string managername, string startDate, string endDate)
        {

            string LeavId = String.Empty, mangrmail = String.Empty, mangrname = String.Empty, mangrid = String.Empty;
            string UrlEmailImage = string.Empty;

            Decript objdecrypt = new Decript();
            var newemail = accmail;
            var useriddd = objdecrypt.Decryption(userid);
            var leavid = objdecrypt.Decryption(leaveid);
            var mngermail = objdecrypt.Decryption(managermail);
            var mngerid = objdecrypt.Decryption(managerid);
            var mngername = objdecrypt.Decryption(managername);
            int Usrid = uid;

            //LeavId = newuwfhid;
            //mangrmail = email;
            //mangrid = id;
            //mangrname = name;

            EvolutyzCornerDataEntities db = new EvolutyzCornerDataEntities();
            var getusermailid = (from u in db.UsersProfiles where u.UsrP_UserID == uid select u.UsrP_EmailID).FirstOrDefault();
            var getaccntid = (from u in db.Users where u.Usr_UserID == uid select u.Usr_AccountID).FirstOrDefault();
            var getaccntlogo = (from a in db.Accounts where a.Acc_AccountID == getaccntid select a.Acc_CompanyLogo).FirstOrDefault();
            // UrlEmailImage = "<img alt='Company Logo' style='height:100px;display:block;margin:auto;max-width:100%;' src='" + "https://" + UrlEmailAddress + "/uploadimages/Images/" + getaccntlogo + "'";
            UrlEmailImage = "<img alt='Company Logo'   src='" + "https://" + UrlEmailAddress + "/uploadimages/images/thumb/" + getaccntlogo + "'";
            var emailcontent = "";

            ManagerWFHforApproval obj = new ManagerWFHforApproval();
            obj = new ManagerWFHforApproval()
            {
                Usrl_UserId = Convert.ToInt32(useriddd),
                UserwfhID = Convert.ToInt32(leavid),
                ManagerID1 = Convert.ToInt32(mngerid),
                ManagerName1 = mngername,
                Leavestatus = status.ToString(),

            };
            obj = CheckMailWFHApproval(obj);

            if (obj.Message == "Already approved")
            {
                return obj.Message;
            }

            else if (obj.Message == "Already Rejected")
            {
                return obj.Message;
            }
            else if (obj.Message == "On Hold")
            {
                return obj.Message;
            }
            //else if(obj.Message == "Leave Already Approved")
            //{
            //    return obj.Message;
            //}
            //else if(obj.Message == "Leave Already Rejected")
            //{
            //    return obj.Message;
            //}
            else
            {

                if (status == "1")
                {
                    emailcontent = "<html>" +
                    "<body bgcolor='#f6f6f6' style='-webkit-font-smoothing: antialiased; background:#f6f6f6; margin:0 auto; padding:0;'>" +
                    "<div style='background:#f4f4f4; border: 0px solid #f4f4f4; margin:0; padding:0'>" +
                    "<center>" +
                    "<table bgcolor='#ffffff' border='0' cellpadding='0' cellspacing='0' style='background: #ffffff; border-collapse:collapse !important; table-layout:fixed; mso-table-lspace:0pt; mso-table-rspace:0pt; width:100%'>" +
                    "<tbody>" +
                    "<tr>" +
                    "<td align='center' bgcolor='#ffffff' style='background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size:18px; line-height:28px; padding-bottom:0px; padding-top:0px valign='top'>" +
                    "<a href='javascript:;' style='color: #7DA33A;text-decoration: none;display: block;' target='_blank'>" +
                    //"<img alt='Company Logo' src='http://evolutyz.in/img/evolutyz-logo.png'/>" +
                    UrlEmailImage +
                    "</a>" +
                    "</td>" +
                    " </tr>" +
                    " <tr>" +
                    "<td align='center' bgcolor='#ffffff' style='background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; line-height: 28px; padding-bottom: 20px; padding-top: 0px' valign='top'>" +
                    " </td>" +
                    "</tr>" +
                    "<tr>" +
                    "<td align='center' bgcolor='#fffff' style='background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; line-height: 28px; padding-bottom: 20px; padding-top: 20px' valign=top>" +
                    " <h2 align='center' style='color: #707070; font-weight: 400; margin:0; text-align: center'>Work From Home</h2>" +
                    "</td>" +
                    " </tr>" +
                    "</tbody>" +
                    "</table>" +
                    "<table bgcolor='#ffffff' border='0' cellpadding='0' cellspacing='0' class='mobile' style='background: #ffffff; border-collapse:collapse !important; table-layout:fixed; mso-table-lspace:0pt; mso-table-rspace:0pt; width:100%'>" +
                    "<tbody>" +
                    "<tr>" +
                    "<td align='center'>" +
                    "<table bgcolor='#ffffff' cellpadding='0' cellspacing='0' class='mobile' style='background: #ffffff; border-collapse:collapse !important; border: 1px solid #d1d2d1; max-width:600px; mso-table-lspace:0pt; mso-table-rspace:0pt; width:96%'>" +
                    " <tbody>" +
                    " <tr>" +
                    "<td align=center bgcolor='#ffffff' style='background: #ffffff; padding-bottom:0px'; padding-top:0' valign='top'>" +
                    "<table align='center' border='0' cellpadding = '0' cellspacing = '0' style = 'border-collapse: collapse !important; max-width:600px; mso-table-lspace:0pt; mso-table-rspace:0pt; width:80%'>" +
                    " <tbody>" +
                    "<tr>" +
                    "<td align='left' bgcolor='#ffffff' style='background: #ffffff; font-family:Lato, Helevetica, Arial, sans-serif; font-size:18px; line-height:28px; padding:10px 0px 20px' valign='top'>" +
                    "<table align='center' border='0' cellpadding='0' cellspacing='0' style='border-collapse:collapse !important; max-width:600px; width:100%'>" +
                    "<tbody>" +
                    "<tr>" +
                    "<td align='left' bgcolor='#ffffff' style=background:'#ffffff; font-family:Lato, Helevetica, Arial, sans-serif; font-size:18px; max-width:80%; padding:0px; width:40%' valign='top'>" +
                    "<p align='left' style='color: #707070; font-size:14px; font-weight:400; line-height:22px; padding-bottom:0px; text-align:left'>" +
                    "<strong>" +
                    "Work From Home Approved By" +
                    " </strong>" +
                    "<br>" +
                    "</p>" +
                    "</td>" +
                    "<td align = 'right' bgcolor = '#ffffff' style = 'background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; max-width: 80%; padding: 0px; width: 40%' valign='top'>" +
                    "<p align = 'right' style = 'color: #707070; font-size: 14px; font-weight: 400; line-height: 22px; padding-bottom: 0px; text-align: 'right'>" +
                     name +
                    "</p>" +
                    "</td>" +
                    "</tr>" +
                    "</tbody>" +
                    "</table>" +
                    "<hr>" +
                    "<table align ='center' border = '0' cellpadding = '0' cellspacing = '0' style = 'border-collapse: collapse !important; max-width: 600px; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%'>" +
                    " <tbody>" +
                    "<tr>" +
                    "<td align = 'left' bgcolor = '#ffffff' style = 'background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; max-width: 80%; padding: 10px 0px 0px; width: 40%' valign='middle'>" +
                    "<p align = 'left' style = 'color: #707070; font-size: 14px; font-weight: 400; line-height: 22px; padding-bottom: 0px; text-align: left'>" +
                    "<strong>" +
                    " FromDate " +
                    " </strong>" +
                    "<br> " +
                    "</p>" +
                    " </td>" +
                    "<td align = right bgcolor = #ffffff style = 'background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; padding: 10x 0px 0px' valign='middle'>" +
                    "<p align = right style = 'color: #707070; font-size: 14px; font-weight: 400; line-height: 22px; padding-bottom: 0px; text-align: right'>" +
                    "<strong>" +
                    startDate +
                    "</strong>" +
                    "</p>" +
                    "</td>" +
                    "</tr>" +
                    "<tr>" +
                    "<td align = left bgcolor = #ffffff style = background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; max-width: 80%; padding: 10px 0px 0px; width: 40%' valign='middle'>" +
                    "<p align = left style = 'color: #707070; font-size: 14px; font-weight: 400; line-height: 22px; padding-bottom: 0px; text-align: left'>" +
                    "<strong> " +
                    " ToDate " +
                    " </strong>" +
                    "<br>" +
                    "</p>" +
                    "</td>" +
                    "<td align = right bgcolor = #ffffff style = 'background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; padding: 10x 0px 0px' valign='middle'>" +
                    "<p align = right style = 'color: #707070; font-size: 14px; font-weight: 400; line-height: 22px; padding-bottom: 0px; text-align: right'>" +
                    "<strong> " +
                    endDate +
                    "</strong>" +
                    "</p>" +
                    "</td>" +
                    "</tr>" +
                    "</tbody>" +
                    "</table>" +
                    "</td>" +
                    "</tr>" +
                    "</tbody>" +
                    "</table>" +
                    "<table align = center bgcolor = #ffffff border =0 cellpadding =0 cellspacing = 0 style = 'background: #ffffff; border-collapse: collapse !important; border-top-color: #D1D2D1; border-top-style: solid; border-top-width: 1px; max-width: 600px; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%'>" +
                    "<tbody>" +
                    " <tr>" +
                    "<td align = center bgcolor = #ffffff style = 'background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; line-height: 28px; padding: 10x 0px 20px' valign='middle'>" +
                    "<table align = center border = 0 cellpadding = 0 cellspacing = 0 style = 'border-collapse: collapse !important; max-width: 600px; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 80%'>" +
                    "<tbody>" +
                    "<tr>" +
                    " <td align = center bgcolor = #ffffff style = 'background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; max-width: 80%; padding: 10px 0px 0px; width: 40%' valign='middle'>" +
                    "<p align = left style = 'color: #707070; font-size: 14px; font-weight: 400; line-height: 22px; padding-bottom: 0px; text-align: left'>" +
                    "<strong> " +
                    "Comments " +
                    "</strong>" +
                    "</p>" +
                    "</td>" +
                    "<td align = right bgcolor = #ffffff style = 'background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; padding: 10x 0px 0px' valign='middle'>" +
                    "<p align = right style = 'color: #707070; font-size: 14px; font-weight: 400; line-height: 22px; padding-bottom: 0px; text-align: right'>" +
                    "<strong>" +
                     cmt +
                    "</strong>" +
                    "</p>" +
                    "</td>" +
                    "</tr>" +
                    "</tbody>" +
                    "</table>" +
                    "</td>" +
                    "</tr>" +
                    "</tbody>" +
                    "</table>" +
                    " </td>" +
                    "</tr>" +
                    "</tbody>" +
                    " </table>" +
                    "<table bgcolor = #ffffff cellpadding =0 cellspacing =0 class=mobile style='background: #ffffff; border-collapse: collapse !important; max-width: 600px; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 96%'>" +
                    "<tbody>" +
                    "<tr>" +
                    "<td align = center style='padding-bottom: 20px' valign=top>" +
                    "<table align = center border=0 cellpadding=0 cellspacing=0 style='border-collapse: collapse !important; mso-table-lspace: 0pt; mso-table-rspace: 0pt'>" +
                    "<tbody>" +
                    "<tr>" +
                    "<td align = center style='padding-bottom: 0px; padding-top: 30px' valign=top>" +
                    "</td>" +
                    "</tr>" +
                    "</tbody>" +
                    "</table>" +
                    "</td>" +
                    "</tr>" +
                    "</tbody>" +
                    "</table>" +
                    "</td>" +
                    "</tr>" +
                    "</tbody>" +
                    "</table>" +
                    "</center>" +
                    "</div>" +
                    "</body>" +
                    "</html>";
                    //RestClient client = new RestClient();
                    //client.BaseUrl = new Uri("https://api.mailgun.net/v3");
                    //client.Authenticator = new HttpBasicAuthenticator("api", "key-25b8e8c23e4a09ef67b7957d77eb7413");
                    //RestRequest request = new RestRequest();
                    //request.AddParameter("domain", "evolutyzstaging.com", ParameterType.UrlSegment);
                    //request.Resource = "{domain}/messages";
                    //request.AddParameter("from", "Evolutyz ITServices <*****@*****.**>");
                    //request.AddParameter("to", getusermailid);
                    //request.AddParameter("to", newemail);
                    //request.AddParameter("subject", "Work From Home Approved");
                    //request.AddParameter("html", emailcontent);
                    //request.Method = Method.POST;
                    //client.Execute(request);

                    var client = new SendGridClient("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");

                    var msgs = new SendGridMessage()
                    {
                        // From = new EmailAddress(mngermail),
                        From = new EmailAddress(FromMailAddress),
                        Subject = "Work From Home Approved",
                        //TemplateId = "d-0741723a4269461e99a89e57a58dc0d3",
                        HtmlContent = emailcontent

                    };
                    msgs.AddTo(new EmailAddress(getusermailid));

                    var responses = client.SendEmailAsync(msgs);
                }
                else
                {
                    if (status == "2")
                    {
                        emailcontent = "<html>" +
                   "<body bgcolor='#f6f6f6' style='-webkit-font-smoothing: antialiased; background:#f6f6f6; margin:0 auto; padding:0;'>" +
                   "<div style='background:#f4f4f4; border: 0px solid #f4f4f4; margin:0; padding:0'>" +
                   "<center>" +
                   "<table bgcolor='#ffffff' border='0' cellpadding='0' cellspacing='0' style='background: #ffffff; border-collapse:collapse !important; table-layout:fixed; mso-table-lspace:0pt; mso-table-rspace:0pt; width:100%'>" +
                   "<tbody>" +
                   "<tr>" +
                   "<td align='center' bgcolor='#ffffff' style='background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size:18px; line-height:28px; padding-bottom:0px; padding-top:0px valign='top'>" +
                   "<a href='javascript:;' style='color: #7DA33A;text-decoration: none;display: block;' target='_blank'>" +
                    //"<img alt='Company Logo' src='http://evolutyz.in/img/evolutyz-logo.png'/>" +
                    UrlEmailImage +
                   "</a>" +
                   "</td>" +
                   " </tr>" +
                   " <tr>" +
                   "<td align='center' bgcolor='#ffffff' style='background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; line-height: 28px; padding-bottom: 20px; padding-top: 0px' valign='top'>" +
                   " </td>" +
                   "</tr>" +
                   "<tr>" +
                   "<td align='center' bgcolor='#fffff' style='background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; line-height: 28px; padding-bottom: 20px; padding-top: 20px' valign=top>" +
                   " <h2 align='center' style='color: #707070; font-weight: 400; margin:0; text-align: center'>Work From Home</h2>" +
                   "</td>" +
                   " </tr>" +
                   "</tbody>" +
                   "</table>" +
                   "<table bgcolor='#ffffff' border='0' cellpadding='0' cellspacing='0' class='mobile' style='background: #ffffff; border-collapse:collapse !important; table-layout:fixed; mso-table-lspace:0pt; mso-table-rspace:0pt; width:100%'>" +
                   "<tbody>" +
                   "<tr>" +
                   "<td align='center'>" +
                   "<table bgcolor='#ffffff' cellpadding='0' cellspacing='0' class='mobile' style='background: #ffffff; border-collapse:collapse !important; border: 1px solid #d1d2d1; max-width:600px; mso-table-lspace:0pt; mso-table-rspace:0pt; width:96%'>" +
                   " <tbody>" +
                   " <tr>" +
                   "<td align=center bgcolor='#ffffff' style='background: #ffffff; padding-bottom:0px'; padding-top:0' valign='top'>" +
                   "<table align='center' border='0' cellpadding = '0' cellspacing = '0' style = 'border-collapse: collapse !important; max-width:600px; mso-table-lspace:0pt; mso-table-rspace:0pt; width:80%'>" +
                   " <tbody>" +
                   "<tr>" +
                   "<td align='left' bgcolor='#ffffff' style='background: #ffffff; font-family:Lato, Helevetica, Arial, sans-serif; font-size:18px; line-height:28px; padding:10px 0px 20px' valign='top'>" +
                   "<table align='center' border='0' cellpadding='0' cellspacing='0' style='border-collapse:collapse !important; max-width:600px; width:100%'>" +
                   "<tbody>" +
                   "<tr>" +
                   "<td align='left' bgcolor='#ffffff' style=background:'#ffffff; font-family:Lato, Helevetica, Arial, sans-serif; font-size:18px; max-width:80%; padding:0px; width:40%' valign='top'>" +
                   "<p align='left' style='color: #707070; font-size:14px; font-weight:400; line-height:22px; padding-bottom:0px; text-align:left'>" +
                   "<strong>" +
                   "Work From Home Rejected By" +
                   " </strong>" +
                   "<br>" +
                   "</p>" +
                   "</td>" +
                   "<td align = 'right' bgcolor = '#ffffff' style = 'background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; max-width:80%; padding:0px; width:40%' valign='top'>" +
                   "<p align = 'right' style = 'color: #707070; font-size: 14px; font-weight: 400; line-height: 22px; padding-bottom: 0px; text-align: 'right'>" +
                    name +
                   "</p>" +
                   "</td>" +
                   "</tr>" +
                   "</tbody>" +
                   "</table>" +
                   "<hr>" +
                   "<table align ='center' border = '0' cellpadding = '0' cellspacing = '0' style = 'border-collapse: collapse !important; max-width: 600px; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%'>" +
                   " <tbody>" +
                   "<tr>" +
                   "<td align = 'left' bgcolor = '#ffffff' style = 'background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; max-width: 80%; padding: 10px 0px 0px; width: 40%' valign='middle'>" +
                   "<p align = 'left' style = 'color: #707070; font-size: 14px; font-weight: 400; line-height: 22px; padding-bottom: 0px; text-align: left'>" +
                   "<strong>" +
                   " FromDate " +
                   " </strong>" +
                   "<br> " +
                   "</p>" +
                   " </td>" +
                   "<td align = right bgcolor = #ffffff style = 'background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; padding: 10x 0px 0px' valign='middle'>" +
                   "<p align = right style = 'color: #707070; font-size: 14px; font-weight: 400; line-height: 22px; padding-bottom: 0px; text-align: right'>" +
                   "<strong>" +
                   startDate +
                   "</strong>" +
                   "</p>" +
                   "</td>" +
                   "</tr>" +
                   "<tr>" +
                   "<td align = left bgcolor = #ffffff style = background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; max-width: 80%; padding: 10px 0px 0px; width: 40%' valign='middle'>" +
                   "<p align = left style = 'color: #707070; font-size: 14px; font-weight: 400; line-height: 22px; padding-bottom: 0px; text-align: left'>" +
                   "<strong> " +
                   " ToDate " +
                   " </strong>" +
                   "<br>" +
                   "</p>" +
                   "</td>" +
                   "<td align = right bgcolor = #ffffff style = 'background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; padding: 10x 0px 0px' valign='middle'>" +
                   "<p align = right style = 'color: #707070; font-size: 14px; font-weight: 400; line-height: 22px; padding-bottom: 0px; text-align: right'>" +
                   "<strong> " +
                   endDate +
                   "</strong>" +
                   "</p>" +
                   "</td>" +
                   "</tr>" +
                   "</tbody>" +
                   "</table>" +
                   "</td>" +
                   "</tr>" +
                   "</tbody>" +
                   "</table>" +
                   "<table align = center bgcolor = #ffffff border =0 cellpadding =0 cellspacing = 0 style = 'background: #ffffff; border-collapse: collapse !important; border-top-color: #D1D2D1; border-top-style: solid; border-top-width: 1px; max-width: 600px; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%'>" +
                   "<tbody>" +
                   " <tr>" +
                   "<td align = center bgcolor = #ffffff style = 'background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; line-height: 28px; padding: 10x 0px 20px' valign='middle'>" +
                   "<table align = center border = 0 cellpadding = 0 cellspacing = 0 style = 'border-collapse: collapse !important; max-width: 600px; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 80%'>" +
                   "<tbody>" +
                   "<tr>" +
                   " <td align = center bgcolor = #ffffff style = 'background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; max-width: 80%; padding: 10px 0px 0px; width: 40%' valign='middle'>" +
                   "<p align = left style = 'color: #707070; font-size: 14px; font-weight: 400; line-height: 22px; padding-bottom: 0px; text-align: left'>" +
                   "<strong> " +
                   "Comments " +
                   "</strong>" +
                   "</p>" +
                   "</td>" +
                   "<td align = right bgcolor = #ffffff style = 'background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; padding: 10x 0px 0px' valign='middle'>" +
                   "<p align = right style = 'color: #707070; font-size: 14px; font-weight: 400; line-height: 22px; padding-bottom: 0px; text-align: right'>" +
                   "<strong>" +
                    cmt +
                   "</strong>" +
                   "</p>" +
                   "</td>" +
                   "</tr>" +
                   "</tbody>" +
                   "</table>" +
                   "</td>" +
                   "</tr>" +
                   "</tbody>" +
                   "</table>" +
                   " </td>" +
                   "</tr>" +
                   "</tbody>" +
                   " </table>" +
                   "<table bgcolor = #ffffff cellpadding =0 cellspacing =0 class=mobile style='background: #ffffff; border-collapse: collapse !important; max-width: 600px; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 96%'>" +
                   "<tbody>" +
                   "<tr>" +
                   "<td align = center style='padding-bottom: 20px' valign=top>" +
                   "<table align = center border=0 cellpadding=0 cellspacing=0 style='border-collapse: collapse !important; mso-table-lspace: 0pt; mso-table-rspace: 0pt'>" +
                   "<tbody>" +
                   "<tr>" +
                   "<td align = center style='padding-bottom: 0px; padding-top: 30px' valign=top>" +
                   "</td>" +
                   "</tr>" +
                   "</tbody>" +
                   "</table>" +
                   "</td>" +
                   "</tr>" +
                   "</tbody>" +
                   "</table>" +
                   "</td>" +
                   "</tr>" +
                   "</tbody>" +
                   "</table>" +
                   "</center>" +
                   "</div>" +
                   "</body>" +
                   "</html>";
                        //RestClient client = new RestClient();
                        //client.BaseUrl = new Uri("https://api.mailgun.net/v3");
                        //client.Authenticator = new HttpBasicAuthenticator("api", "key-25b8e8c23e4a09ef67b7957d77eb7413");
                        //RestRequest request = new RestRequest();
                        //request.AddParameter("domain", "evolutyzstaging.com", ParameterType.UrlSegment);
                        //request.Resource = "{domain}/messages";
                        //request.AddParameter("from", "Evolutyz ITServices <*****@*****.**>");
                        //request.AddParameter("to", getusermailid);
                        //request.AddParameter("to", newemail);
                        //request.AddParameter("subject", "Work From Home Rejected");
                        //request.AddParameter("html", emailcontent);
                        //request.Method = Method.POST;
                        //client.Execute(request);
                        var client = new SendGridClient("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");

                        var msgs = new SendGridMessage()
                        {
                            //From = new EmailAddress(mngermail),
                            From = new EmailAddress(FromMailAddress),
                            Subject = "Work From Home Rejected",
                            //TemplateId = "d-0741723a4269461e99a89e57a58dc0d3",
                            HtmlContent = emailcontent

                        };
                        msgs.AddTo(new EmailAddress(getusermailid));
                        var responses = client.SendEmailAsync(msgs);

                    }
                    else
                    {
                        emailcontent = "<html>" +
                "<body bgcolor='#f6f6f6' style='-webkit-font-smoothing: antialiased; background:#f6f6f6; margin:0 auto; padding:0;'>" +
                "<div style='background:#f4f4f4; border: 0px solid #f4f4f4; margin:0; padding:0'>" +
                "<center>" +
                "<table bgcolor='#ffffff' border='0' cellpadding='0' cellspacing='0' style='background: #ffffff; border-collapse:collapse !important; table-layout:fixed; mso-table-lspace:0pt; mso-table-rspace:0pt; width:100%'>" +
                "<tbody>" +
                "<tr>" +
                "<td align='center' bgcolor='#ffffff' style='background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size:18px; line-height:28px; padding-bottom:0px; padding-top:0px valign='top'>" +
                "<a href='javascript:;' style='color: #7DA33A;text-decoration: none;display: block;' target='_blank'>" +
                //"<img alt='Company Logo' src='http://evolutyz.in/img/evolutyz-logo.png'/>" +
                UrlEmailImage +
                "</a>" +
                "</td>" +
                " </tr>" +
                " <tr>" +
                "<td align='center' bgcolor='#ffffff' style='background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; line-height: 28px; padding-bottom: 20px; padding-top: 0px' valign='top'>" +
                " </td>" +
                "</tr>" +
                "<tr>" +
                "<td align='center' bgcolor='#fffff' style='background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; line-height: 28px; padding-bottom: 20px; padding-top: 20px' valign=top>" +
                " <h2 align='center' style='color: #707070; font-weight: 400; margin:0; text-align: center'>Work From Home</h2>" +
                "</td>" +
                " </tr>" +
                "</tbody>" +
                "</table>" +
                "<table bgcolor='#ffffff' border='0' cellpadding='0' cellspacing='0' class='mobile' style='background: #ffffff; border-collapse:collapse !important; table-layout:fixed; mso-table-lspace:0pt; mso-table-rspace:0pt; width:100%'>" +
                "<tbody>" +
                "<tr>" +
                "<td align='center'>" +
                "<table bgcolor='#ffffff' cellpadding='0' cellspacing='0' class='mobile' style='background: #ffffff; border-collapse:collapse !important; border: 1px solid #d1d2d1; max-width:600px; mso-table-lspace:0pt; mso-table-rspace:0pt; width:96%'>" +
                " <tbody>" +
                " <tr>" +
                "<td align=center bgcolor='#ffffff' style='background: #ffffff; padding-bottom:0px'; padding-top:0' valign='top'>" +
                "<table align='center' border='0' cellpadding = '0' cellspacing = '0' style = 'border-collapse: collapse !important; max-width:600px; mso-table-lspace:0pt; mso-table-rspace:0pt; width:80%'>" +
                " <tbody>" +
                "<tr>" +
                "<td align='left' bgcolor='#ffffff' style='background: #ffffff; font-family:Lato, Helevetica, Arial, sans-serif; font-size:18px; line-height:28px; padding:10px 0px 20px' valign='top'>" +
                "<table align='center' border='0' cellpadding='0' cellspacing='0' style='border-collapse:collapse !important; max-width:600px; width:100%'>" +
                "<tbody>" +
                "<tr>" +
                "<td align='left' bgcolor='#ffffff' style=background:'#ffffff; font-family:Lato, Helevetica, Arial, sans-serif; font-size:18px; max-width:80%; padding:0px; width:40%' valign='top'>" +
                "<p align='left' style='color: #707070; font-size:14px; font-weight:400; line-height:22px; padding-bottom:0px; text-align:left'>" +
                "<strong>" +
                "Work From Home kept on hold by" +
                " </strong>" +
                "<br>" +
                "</p>" +
                "</td>" +
                "<td align = 'right' bgcolor = '#ffffff' style = 'background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; max-width:80%; padding:0px; width:40%' valign='top'>" +
                "<p align = 'right' style = 'color: #707070; font-size: 14px; font-weight: 400; line-height: 22px; padding-bottom: 0px; text-align: 'right'>" +
                 name +
                 "</p>" +
                "</td>" +
                "</tr>" +
                "</tbody>" +
                "</table>" +
                "<hr>" +
                "<table align ='center' border = '0' cellpadding = '0' cellspacing = '0' style = 'border-collapse: collapse !important; max-width: 600px; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%'>" +
                " <tbody>" +
                "<tr>" +
                "<td align = 'left' bgcolor = '#ffffff' style = 'background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; max-width: 80%; padding: 10px 0px 0px; width: 40%' valign='middle'>" +
                "<p align = 'left' style = 'color: #707070; font-size: 14px; font-weight: 400; line-height: 22px; padding-bottom: 0px; text-align: left'>" +
                "<strong>" +
                " FromDate " +
                " </strong>" +
                "<br> " +
                "</p>" +
                " </td>" +
                "<td align = right bgcolor = #ffffff style = 'background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; padding: 10x 0px 0px' valign='middle'>" +
                "<p align = right style = 'color: #707070; font-size: 14px; font-weight: 400; line-height: 22px; padding-bottom: 0px; text-align: right'>" +
                "<strong>" +
                startDate +
                "</strong>" +
                "</p>" +
                "</td>" +
                "</tr>" +
                "<tr>" +
                "<td align = left bgcolor = #ffffff style = background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; max-width: 80%; padding: 10px 0px 0px; width: 40%' valign='middle'>" +
                "<p align = left style = 'color: #707070; font-size: 14px; font-weight: 400; line-height: 22px; padding-bottom: 0px; text-align: left'>" +
                "<strong> " +
                " ToDate " +
                " </strong>" +
                "<br>" +
                "</p>" +
                "</td>" +
                "<td align = right bgcolor = #ffffff style = 'background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; padding: 10x 0px 0px' valign='middle'>" +
                "<p align = right style = 'color: #707070; font-size: 14px; font-weight: 400; line-height: 22px; padding-bottom: 0px; text-align: right'>" +
                "<strong> " +
                endDate +
                "</strong>" +
                "</p>" +
                "</td>" +
                "</tr>" +
                "</tbody>" +
                "</table>" +
                "</td>" +
                "</tr>" +
                "</tbody>" +
                "</table>" +
                "<table align = center bgcolor = #ffffff border =0 cellpadding =0 cellspacing = 0 style = 'background: #ffffff; border-collapse: collapse !important; border-top-color: #D1D2D1; border-top-style: solid; border-top-width: 1px; max-width: 600px; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%'>" +
                "<tbody>" +
                " <tr>" +
                "<td align = center bgcolor = #ffffff style = 'background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; line-height: 28px; padding: 10x 0px 20px' valign='middle'>" +
                "<table align = center border = 0 cellpadding = 0 cellspacing = 0 style = 'border-collapse: collapse !important; max-width: 600px; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 80%'>" +
                "<tbody>" +
                "<tr>" +
                " <td align = center bgcolor = #ffffff style = 'background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; max-width: 80%; padding: 10px 0px 0px; width: 40%' valign='middle'>" +
                "<p align = left style = 'color: #707070; font-size: 14px; font-weight: 400; line-height: 22px; padding-bottom: 0px; text-align: left'>" +
                "<strong> " +
                "Comments " +
                "</strong>" +
                "</p>" +
                "</td>" +
                "<td align = right bgcolor = #ffffff style = 'background: #ffffff; font-family: Lato, Helevetica, Arial, sans-serif; font-size: 18px; padding: 10x 0px 0px' valign='middle'>" +
                "<p align = right style = 'color: #707070; font-size: 14px; font-weight: 400; line-height: 22px; padding-bottom: 0px; text-align: right'>" +
                "<strong>" +
                cmt +
                "</strong>" +
                "</p>" +
                "</td>" +
                "</tr>" +
                "</tbody>" +
                "</table>" +
                "</td>" +
                "</tr>" +
                "</tbody>" +
                "</table>" +
                " </td>" +
                "</tr>" +
                "</tbody>" +
                " </table>" +
                "<table bgcolor = #ffffff cellpadding =0 cellspacing =0 class=mobile style='background: #ffffff; border-collapse: collapse !important; max-width: 600px; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 96%'>" +
                "<tbody>" +
                "<tr>" +
                "<td align = center style='padding-bottom: 20px' valign=top>" +
                "<table align = center border=0 cellpadding=0 cellspacing=0 style='border-collapse: collapse !important; mso-table-lspace: 0pt; mso-table-rspace: 0pt'>" +
                "<tbody>" +
                "<tr>" +
                "<td align = center style='padding-bottom: 0px; padding-top: 30px' valign=top>" +
                "</td>" +
                "</tr>" +
                "</tbody>" +
                "</table>" +
                "</td>" +
                "</tr>" +
                "</tbody>" +
                "</table>" +
                "</td>" +
                "</tr>" +
                "</tbody>" +
                "</table>" +
                "</center>" +
                "</div>" +
                "</body>" +
                "</html>";

                        //RestClient client = new RestClient();
                        //client.BaseUrl = new Uri("https://api.mailgun.net/v3");
                        //client.Authenticator = new HttpBasicAuthenticator("api", "key-25b8e8c23e4a09ef67b7957d77eb7413");
                        //RestRequest request = new RestRequest();
                        //request.AddParameter("domain", "evolutyzstaging.com", ParameterType.UrlSegment);
                        //request.Resource = "{domain}/messages";
                        //request.AddParameter("from", "Evolutyz ITServices <*****@*****.**>");
                        //request.AddParameter("to", getusermailid);
                        //request.AddParameter("to", newemail);
                        //request.AddParameter("subject", "Work from Home OnHold");
                        //request.AddParameter("html", emailcontent);
                        //request.Method = Method.POST;
                        //client.Execute(request);

                        var client = new SendGridClient("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");

                        var msgs = new SendGridMessage()
                        {
                            //From = new EmailAddress(mngermail),
                            From = new EmailAddress(FromMailAddress),
                            Subject = "Work from Home OnHold",
                            //TemplateId = "d-0741723a4269461e99a89e57a58dc0d3",
                            HtmlContent = emailcontent

                        };
                        msgs.AddTo(new EmailAddress(getusermailid));
                        var responses = client.SendEmailAsync(msgs);
                    }
                }

                AdminComponent admc = new AdminComponent();

                //var res = admc.SaveWorkFromHomeStatus(newuwfhid, status, id);leavid, status, mngerid, useriddd
                var res = admc.SaveWorkFromHomeStatus(cmt, leavid, status, mngerid, useriddd);
                obj.Message = res;
            }

            // return null;
            return obj.Message;

        }
示例#2
0
        static async Task Execute()
        {
            // Retrieve the API key from the environment variables. See the project README for more info about setting this up.
            var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY");

            var client = new SendGridClient(apiKey);

            // Send a Single Email using the Mail Helper
            var from             = new EmailAddress("*****@*****.**", "Example User");
            var subject          = "Hello World from the SendGrid CSharp Library Helper!";
            var to               = new EmailAddress("*****@*****.**", "Example User");
            var plainTextContent = "Hello, Email from the helper [SendSingleEmailAsync]!";
            var htmlContent      = "<strong>Hello, Email from the helper! [SendSingleEmailAsync]</strong>";
            var msg              = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);

            var response = await client.SendEmailAsync(msg);

            Console.WriteLine(msg.Serialize());
            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue.");
            Console.ReadLine();

            // Send a Single Email using the Mail Helper with convenience methods and initialized SendGridMessage object
            msg = new SendGridMessage()
            {
                From             = new EmailAddress("*****@*****.**", "Example User"),
                Subject          = "Hello World from the SendGrid CSharp Library Helper!",
                PlainTextContent = "Hello, Email from the helper [SendSingleEmailAsync]!",
                HtmlContent      = "<strong>Hello, Email from the helper! [SendSingleEmailAsync]</strong>"
            };
            msg.AddTo(new EmailAddress("*****@*****.**", "Example User"));

            response = await client.SendEmailAsync(msg);

            Console.WriteLine(msg.Serialize());
            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue.");
            Console.ReadLine();

            // Send a Single Email using the Mail Helper, entirely with convenience methods
            msg = new SendGridMessage();
            msg.SetFrom(new EmailAddress("*****@*****.**", "Example User"));
            msg.SetSubject("Hello World from the SendGrid CSharp Library Helper!");
            msg.AddContent(MimeType.Text, "Hello, Email from the helper [SendSingleEmailAsync]!");
            msg.AddContent(MimeType.Html, "<strong>Hello, Email from the helper! [SendSingleEmailAsync]</strong>");
            msg.AddTo(new EmailAddress("*****@*****.**", "Example User"));

            response = await client.SendEmailAsync(msg);

            Console.WriteLine(msg.Serialize());
            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue.");
            Console.ReadLine();

            // Send a Single Email Without the Mail Helper
            string data = @"{
              'personalizations': [
                {
                  'to': [
                    {
                      'email': '*****@*****.**'
                    }
                  ],
                  'subject': 'Hello World from the SendGrid C# Library!'
                }
              ],
              'from': {
                'email': '*****@*****.**'
              },
              'content': [
                {
                  'type': 'text/plain',
                  'value': 'Hello, Email!'
                }
              ]
            }";
            Object json = JsonConvert.DeserializeObject <Object>(data);

            response = await client.RequestAsync(SendGridClient.Method.POST,
                                                 json.ToString(),
                                                 urlPath : "mail/send");

            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue.");
            Console.ReadLine();

            // GET Collection
            string queryParams = @"{
                'limit': 100
            }";

            response = await client.RequestAsync(method : SendGridClient.Method.GET,
                                                 urlPath : "asm/groups",
                                                 queryParams : queryParams);

            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Body.ReadAsStringAsync().Result);
            Console.WriteLine(response.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue to POST.");
            Console.ReadLine();

            // POST
            string requestBody = @"{
              'description': 'Suggestions for products our users might like.', 
              'is_default': false, 
              'name': 'Magic Products'
            }";

            json     = JsonConvert.DeserializeObject <object>(requestBody);
            response = await client.RequestAsync(method : SendGridClient.Method.POST,
                                                 urlPath : "asm/groups",
                                                 requestBody : json.ToString());

            var ds_response = JsonConvert.DeserializeObject <Dictionary <string, dynamic> >(response.Body.ReadAsStringAsync().Result);

            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Body.ReadAsStringAsync().Result);
            Console.WriteLine(response.Headers);
            Console.WriteLine("\n\nPress <Enter> to continue to GET single.");
            Console.ReadLine();

            if (ds_response != null && ds_response.ContainsKey("id"))
            {
                string group_id = ds_response["id"].ToString();

                // GET Single
                response = await client.RequestAsync(method : SendGridClient.Method.GET,
                                                     urlPath : string.Format("asm/groups/{0}", group_id));

                Console.WriteLine(response.StatusCode);
                Console.WriteLine(response.Body.ReadAsStringAsync().Result);
                Console.WriteLine(response.Headers);
                Console.WriteLine("\n\nPress <Enter> to continue to PATCH.");
                Console.ReadLine();


                // PATCH
                requestBody = @"{
                    'name': 'Cool Magic Products'
                }";
                json        = JsonConvert.DeserializeObject <object>(requestBody);

                response = await client.RequestAsync(method : SendGridClient.Method.PATCH,
                                                     urlPath : string.Format("asm/groups/{0}", group_id),
                                                     requestBody : json.ToString());

                Console.WriteLine(response.StatusCode);
                Console.WriteLine(response.Body.ReadAsStringAsync().Result);
                Console.WriteLine(response.Headers.ToString());

                Console.WriteLine("\n\nPress <Enter> to continue to PUT.");
                Console.ReadLine();

                // DELETE
                response = await client.RequestAsync(method : SendGridClient.Method.DELETE,
                                                     urlPath : string.Format("asm/groups/{0}", group_id));

                Console.WriteLine(response.StatusCode);
                Console.WriteLine(response.Headers.ToString());
                Console.WriteLine("\n\nPress <Enter> to DELETE and exit.");
                Console.ReadLine();
            }
        }
示例#3
0
        public bool SendMail(string to, string subject, string body)
        {
            bool result = false;



            // Create the email object first, then add the properties.
            var myMessage = new SendGridMessage();

            // Add the message properties.
            myMessage.From = new MailAddress("*****@*****.**");

            // Add multiple addresses to the To field.
            List <String> recipients = new List <String>
            {
                to
            };

            myMessage.AddTo(recipients);

            myMessage.Subject = subject;

            //Add the HTML and Text bodies
            myMessage.Html = body;


            // Create network credentials to access your SendGrid account.
            var username = "******";
            var pswd     = "EMf0tV9PVhAl4a7";

            var credentials = new NetworkCredential(username, pswd);

            // Create an Web transport for sending email.
            var transportWeb = new Web(credentials);



            //System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
            //mail.To.Add(to);

            //mail.Subject = subject;
            //mail.SubjectEncoding = System.Text.Encoding.UTF8;
            //mail.Body = body;
            //mail.BodyEncoding = System.Text.Encoding.UTF8;
            //mail.IsBodyHtml = true;
            //mail.Priority = MailPriority.High;

            //SmtpClient client = new SmtpClient();
            //client.EnableSsl = true; //Gmail works on Server Secured Layer
            try
            {
                // Send the email.
                transportWeb.Deliver(myMessage);
                result = true;
            }
            catch (Exception ex)
            {
                this.serviceLog.LogError("MailService::SendMail", ex);
                throw new Exception("something went wrong while sending email ", ex);
            } // end try
            return(result);
        }
示例#4
0
        public static async Task Run(
            [QueueTrigger("emails")] OutgoingEmail email,
            [SendGrid] IAsyncCollector <SendGridMessage> messageCollector, ILogger log)
        {
            try
            {
                if (email is null)
                {
                    throw new ArgumentNullException(nameof(email));
                }
                else if (email.Tos is null || !email.Tos.Any())
                {
                    throw new ArgumentException("There must be at least one recipient.", nameof(email.Tos));
                }
                else if (string.IsNullOrWhiteSpace(email.Body))
                {
                    throw new ArgumentNullException("There must be a body for the email.", nameof(email.Body));
                }

                log.LogInformation("Starting email process");

                var message = new SendGridMessage();

                message.SetFrom(new EmailAddress(Environment.GetEnvironmentVariable("FromEmail"), Environment.GetEnvironmentVariable("FromName")));
                message.SetSubject(email.Subject);
                message.HtmlContent = email.Body;

                var hardcodedToEmail = Environment.GetEnvironmentVariable("ToEmail");
                if (string.IsNullOrWhiteSpace(hardcodedToEmail))
                {
                    foreach (var toEmail in email.Tos)
                    {
                        log.LogInformation("email: {toEmail}", toEmail);
                        message.AddTo(toEmail);
                    }
                }
                else
                {
                    log.LogInformation("harcoded email: {email}", hardcodedToEmail);
                    message.AddTo(hardcodedToEmail);
                }

                if (email.Attachments != null && email.Attachments.Any())
                {
                    log.LogInformation("Have {count} attachment(s)", email.Attachments.Count);
                    var storageAccount = CloudStorageAccount.Parse(Environment.GetEnvironmentVariable("AzureWebJobsStorage"));

                    var client    = storageAccount.CreateCloudBlobClient();
                    var container = client.GetContainerReference(Environment.GetEnvironmentVariable("Container_Name"));
                    await container.CreateIfNotExistsAsync();

                    foreach (var file in email.Attachments)
                    {
                        var dirRef      = container.GetDirectoryReference(file);
                        var isDirectory = dirRef.ListBlobs().Count() > 0;

                        if (isDirectory)
                        {
                            log.LogInformation("Processing folder: {file}", file);
                            var bag      = new ConcurrentBag <Attachment>();
                            var taskList = new List <Task>();

                            foreach (CloudBlob b in dirRef.ListBlobs(useFlatBlobListing: true))
                            {
                                taskList.Add(Task.Run(async() => bag.Add(await DownloadBlob(b, log))));
                            }

                            await Task.WhenAll(taskList);

                            if (bag.Any())
                            {
                                message.AddAttachments(bag.ToList());
                            }
                            else
                            {
                                log.LogWarning("There are no files in the {folder} folder", file);
                            }
                        }
                        else
                        {
                            log.LogInformation("Processing file: {file}", file);
                            var blobRef = container.GetBlobReference(file);
                            if (await blobRef.ExistsAsync())
                            {
                                message.Attachments.Add(await DownloadBlob(blobRef, log));
                            }
                            else
                            {
                                throw new ArgumentException($"The file {file} does not exists", nameof(file));
                            }
                        }
                    }
                }

                log.LogDebug("Sending an email with the subject: {subject}", email.Subject);

                await messageCollector.AddAsync(message);

                log.LogInformation("Finished sending email");
            }
示例#5
0
        public ActionResult _PartnershipAgreementPartial(PartnershipAgreementForm model, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                var body    = "First Name: {0} <br />  Last Name: {1} <br /> Restaurant: {2} <br /> Position: {3} <br /> Email: {4} <br /> Phone: {5} <br /> Address: {6} <br /> Zip Code: {7} <br /> State: {8} Term Agreement: {9} <br /> E-Signature: {10}";
                var message = new SendGridMessage();
                message.AddTo("*****@*****.**");
                message.AddTo("*****@*****.**");                              // replace with valid value
                message.AddTo("*****@*****.**");
                message.From    = new MailAddress("*****@*****.**"); // replace with valid value
                message.Subject = "Pizza Solutions Partnership Agreement";
                message.Html    = string.Format(body, model.FirstName, model.LastName, model.Restaurant, model.Position, model.PartnershipEmail, model.PartnershipPhone, model.StreetAddress, model.ZipCode, model.State, model.Agreement, model.ElectronicSignature);

                try
                {
                    if (file.ContentLength > 0)
                    {
                        var fileName = Path.GetFileName(file.FileName);
                        var path     = Path.Combine(Server.MapPath("~/App_Data/Images"), fileName);
                        file.SaveAs(path);

                        message.AddAttachment(path);

                        //Azure credentials

                        var username = ConfigurationManager.AppSettings["sendGridUser"];
                        var pswd     = ConfigurationManager.AppSettings["sendGridPassword"];

                        // variable to store azure credentials
                        var credentials = new NetworkCredential(username, pswd);
                        // Create an Web transport for sending email.
                        var transportWeb = new Web(credentials);

                        // Send the email, which returns an awaitable task.
                        transportWeb.DeliverAsync(message);

                        ViewBag.Message = "Message Sent";

                        ModelState.Clear(); //clears form when page reload

                        return(RedirectToAction("MessageSend", "Home"));
                    }
                }

                catch
                {
                    var username = ConfigurationManager.AppSettings["sendGridUser"];
                    var pswd     = ConfigurationManager.AppSettings["sendGridPassword"];

                    var credentials  = new NetworkCredential(username, pswd);
                    var transportWeb = new Web(credentials);

                    transportWeb.DeliverAsync(message);

                    ViewBag.Message = "Message Sent";

                    ModelState.Clear(); //clears form when page reload

                    return(RedirectToAction("MessageSend", "Home"));
                }
            }
            return(View(model));
        }
示例#6
0
        public string SendGridMsg(MailAddress from, string subject, string message, List <MailAddress> to, int?id, int?pid, List <MailAddress> cc = null)
        {
            var senderrorsto = ConfigurationManager.AppSettings["senderrorsto"];

            string fromDomain, apiKey;

            if (ShouldUseCustomEmailDomain)
            {
                fromDomain = CustomFromDomain;
                apiKey     = CustomSendGridApiKey;
            }
            else
            {
                fromDomain = DefaultFromDomain;
                apiKey     = DefaultSendGridApiKey;
            }
            var client = new SendGridClient(apiKey);

            if (from == null)
            {
                from = Util.FirstAddress(senderrorsto);
            }

            var mail = new SendGridMessage()
            {
                From             = new EmailAddress(fromDomain, from.DisplayName),
                Subject          = subject,
                ReplyTo          = new EmailAddress(from.Address, from.DisplayName),
                PlainTextContent = "Hello, Email from the helper [SendSingleEmailAsync]!",
                HtmlContent      = "<strong>Hello, Email from the helper! [SendSingleEmailAsync]</strong>"
            };
            var pe = new Personalization();

            foreach (var ma in to)
            {
                if (ma.Host != "nowhere.name" || Util.IsInRoleEmailTest)
                {
                    mail.AddTo(new EmailAddress(ma.Address, ma.DisplayName));
                }
            }

            if (cc?.Count > 0)
            {
                string cclist = string.Join(",", cc);
                if (!cc.Any(vv => vv.Address.Equal(from.Address)))
                {
                    cclist = $"{from.Address},{cclist}";
                }
                mail.ReplyTo = new EmailAddress(cclist);
            }

            pe.Headers.Add(XSmtpApi, XSmtpApiHeader(id, pid, fromDomain));
            pe.Headers.Add(XBvcms, XBvcmsHeader(id, pid));

            mail.Personalizations.Add(pe);

            if (pe.Tos.Count == 0 && pe.Tos.Any(tt => tt.Email.EndsWith("@nowhere.name")))
            {
                return(null);
            }
            var badEmailLink = "";

            if (pe.Tos.Count == 0)
            {
                pe.Tos.Add(new EmailAddress(from.Address, from.DisplayName));
                pe.Tos.Add(new EmailAddress(Util.FirstAddress(senderrorsto).Address));
                mail.Subject += $"-- bad addr for {CmsHost}({pid})";
                badEmailLink  = $"<p><a href='{CmsHost}/Person2/{pid}'>bad addr for</a></p>\n";
            }

            var regex = new Regex("</?([^>]*)>", RegexOptions.IgnoreCase | RegexOptions.Multiline);

            mail.PlainTextContent = regex.Replace(message, string.Empty);
            mail.HtmlContent      = badEmailLink + message + CcMessage(cc);

            var response = client.SendEmailAsync(mail);

            return(fromDomain);
        }
示例#7
0
        public SendGridResponseDto SendTransactionalEmail(SendGridTransactionalMessageDto messageDto)
        {
            var response = new SendGridResponseDto
            {
                Valid = false
            };

            if (messageDto.TemplateEngine == null)
            {
                response.Message = "SendGrid Template is missing";
                return(response);
            }

            if (messageDto.Subject == null)
            {
                response.Message = "Subject required";
                return(response);
            }

            if (string.IsNullOrEmpty(messageDto.Recipients))
            {
                response.Message = "Recipient(s) required";
                return(response);
            }

            try
            {
                var client  = new SendGridClient(messageDto.ApiKey);
                var message = new SendGridMessage();
                message.AddTo(messageDto.Recipients);

                if (!string.IsNullOrEmpty(messageDto.Bcc))
                {
                    message.AddBcc(messageDto.Bcc);
                }

                message.SetFrom(new EmailAddress(messageDto.FromAddress));
                message.SetSubject(messageDto.Subject);

                if (messageDto.TextMessage.IsNotNullOrEmpty())
                {
                    message.AddContent(MimeType.Text, messageDto.TextMessage);
                }

                if (messageDto.HtmlMessage.IsNotNullOrEmpty())
                {
                    message.AddContent(MimeType.Html, messageDto.HtmlMessage);
                }

                if (messageDto.Categories != null)
                {
                    message.Categories = messageDto.Categories;
                }

                if (messageDto.Substitutions != null)
                {
                    foreach (var key in messageDto.Substitutions.Keys)
                    {
                        message.AddSubstitution(key, messageDto.Substitutions[key].ToString());
                    }
                }

                if (messageDto.TemplateEngine.IsNotNullOrEmpty())
                {
                    message.TemplateId = messageDto.TemplateEngine;
                }

                message.TrackingSettings = new TrackingSettings();
                message.TrackingSettings.ClickTracking =
                    new ClickTracking
                {
                    Enable = messageDto.EnableClickTracking
                };

                message.SetSubscriptionTracking(!messageDto.DisableUnsubscribe);
                var sgResponse = client.SendEmailAsync(message);
                Thread.Sleep(1000);

                response.Valid   = true;
                response.Message = string.Concat(messageDto.Subject, " sent to ", messageDto.Recipients);
            }
            catch (Exception ex)
            {
                response.Valid   = false;
                response.Message = ex.Message;
            }

            return(response);
        }
示例#8
0
        public static void SendEmailMsgWithAttachment(EmailMessage message, string FilePath)
        {
            // Create the email object first, then add the properties.
            SendGridMessage myMessage = new SendGridMessage();

            myMessage.AddTo(message.To.Split(',').ToList());

            foreach (var item in message.CC.Split(','))
            {
                myMessage.AddCc(item);
            }

            foreach (var item in message.BCC.Split(','))
            {
                myMessage.AddBcc(item);
            }

            myMessage.Subject = message.Subject;
            myMessage.Html    = message.Body;

            string username      = ConfigurationManager.AppSettings["MailAccount"];
            string password      = ConfigurationManager.AppSettings["Mailpassword"];
            string FromEmail     = ConfigurationManager.AppSettings["EmailUser"];
            string FromEmailName = ConfigurationManager.AppSettings["EmailUserName"];

            myMessage.From = new MailAddress(FromEmail, FromEmailName);

            if (!string.IsNullOrEmpty(FilePath))
            {
                foreach (string item in FilePath.Split(',').ToList())
                {
                    myMessage.AddAttachment(item);
                }
            }


            // Create credentials, specifying your user name and password.
            var credentials = new NetworkCredential(username, password);

            // Create an Web transport for sending email.
            var transportWeb = new Web(credentials);

            // Send the email.
            // You can also use the **DeliverAsync** method, which returns an awaitable task.
            try
            {
                // Send the email.
                if (transportWeb != null)
                {
                    transportWeb.DeliverAsync(myMessage);
                }
                else
                {
                    Trace.TraceError("Failed to create Web transport.");
                    Task.FromResult(0);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.Message + " SendGrid probably not configured correctly.");
            }
        }
示例#9
0
        public static async Task RunAsync([TimerTrigger("0 */180 * * * *")] TimerInfo myTimer, TraceWriter log)
        {
            var connectionString = Environment.GetEnvironmentVariable("Connection", EnvironmentVariableTarget.Process);
            var storageString    = Environment.GetEnvironmentVariable("AzureWebJobsStorage", EnvironmentVariableTarget.Process);
            var apiKey           = Environment.GetEnvironmentVariable("SENDGRID_API_KEY", EnvironmentVariableTarget.Process);

            ExcelImportExport excelImportExport = new ExcelImportExport("GPException");


            log.Info($"value of storageString is: {storageString}");
            log.Info($"value of apiKey is: {apiKey}");
            log.Info($"value of connectionString is: {connectionString}");

            log.Info($"C# Timer trigger function executed at: {DateTime.Now}");


            //Run the GP Exceptions Stored Procedure
            using (SqlConnection objConn = new SqlConnection(connectionString))
            {
                // Connection object
                objConn.Open();

                // Command text
                var strText = "exec sp_GrossProfitExceptionUpdate";

                // Command Object
                using (SqlCommand objCmd = new SqlCommand(strText, objConn))
                {
                    // Execute procedure
                    var rows = objCmd.ExecuteNonQueryAsync();

                    // This should always be 1
                    log.Info("sp_GrossProfitExceptionUpdate stored procedure updated");
                }

                // Close the object
                objConn.Close();
            }

            List <GPException> GPExceptionList = new List <GPException>();

            GPExceptionList = ExcuteObject <GPException>(GPExceptionSQLString,
                                                         false).ToList();


            var countExceptions = GPExceptionList.Count();

            log.Info("There are: " + countExceptions.ToString() + "Exceptions");

            ExcelImportExport ExcelExport = new ExcelImportExport();

            ExcelExport.SaveFileExcelToAzureStorageAsync(GPExceptionList, storageString, FileName, log, ContainerName).Wait();
            log.Info("GP Exception File created in Azure Storage Area.");
            var client = new SendGridClient(apiKey);
            //  var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, tos, subject, "", htmlContent, false);

            var msg = new SendGridMessage()
            {
                From             = new EmailAddress("*****@*****.**", "GP Exception Team"),
                Subject          = "GP Exceptions",
                PlainTextContent = "Hi Please find the GP Exceptions. There are " + countExceptions.ToString() + "Exceptions.",
                HtmlContent      = "<strong>" + "Hi Please find the GP Exceptions.There are " + countExceptions.ToString() + "Exceptions." + "</strong>"
            };

            msg.AddTo(new EmailAddress("*****@*****.**", "Test User"));
            ExcelExport.AttachEmailtoMessage(storageString, ContainerName, FileName, msg);

            var response = await client.SendEmailAsync(msg);

            log.Info("Response from email server: " + response.StatusCode.ToString());
        }
示例#10
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new AplicatieUtilizator {
                    UserName = Input.Email, Email = Input.Email, Nume = Input.Nume, Prenume = Input.Prenume
                };
                var result = await _userManager.CreateAsync(user, Input.Parola);

                await _userManager.AddToRoleAsync(user, "Student");

                if (result.Succeeded)
                {
                    _logger.LogInformation("A fost creat un nou cont");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    //code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    var client = new SendGridClient("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");
                    var msg    = new SendGridMessage();

                    msg.SetFrom(new EmailAddress("*****@*****.**", ""));

                    var recipient =
                        new EmailAddress(Input.Email);
                    msg.AddTo(recipient);

                    msg.SetSubject("Confirmare adresa de e-mail");

                    msg.AddContent(MimeType.Text, "Click pentru confirmare adresa de e-mail: ");
                    msg.AddContent(MimeType.Html, "<a href=" + callbackUrl + ">Click pentru confirmare e-mail</a>");
                    var response = await client.SendEmailAsync(msg);


                    if (_userManager.Options.SignIn.RequireConfirmedEmail)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
 public void ResolveRecipients(ref SendGridMessage mailMessage)
 {
     mailMessage.AddTo(new EmailAddress("*****@*****.**"));
 }
示例#12
0
        public async Task SendEmail(Guest guest)
        {
            if (string.IsNullOrWhiteSpace(guest.Email))
            {
                return;
            }

            ParseTemplate();
            ParseTemplate(guest);

            string message = "<link crossorigin=anonymous href=https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css integrity=sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u rel=stylesheet><style>body{margin-top:20px;font-size:13px;font-family:verdana}section{padding-bottom:15px}p.well-sm img{margin-left:-130}</style><body class=container><div class=row><div class=col-md-12><p class=well-sm><img alt=\"\"src=https://donate.splcenter.org/image/splc_logo_ecard.jpg></div></div>";

            message += $"<div class=row><div class=col-md-12><section><div><p>{DateTime.Today:D}</p></div></section></div></div>";

            if (guest.IsAttending == true && guest.IsWaiting)
            {
                message += Template.WaitingResponseText;
            }
            if (guest.IsAttending == true && guest.IsWaiting == false)
            {
                message += Template.YesResponseText;
            }
            if (guest.IsAttending == false)
            {
                message += Template.NoResponseText;
            }

            message += "<div class=row><div class=\"col-md-12 col-sm-12\"><div><div style=float:left;width:121px><img src=http://donate.splcenter.org/image/morris_dees_photo.png alt=\"\"class=\"img-responsive inline-block\"></div><div style=margin-left:135px><p>Sincerely,<div style=height:93px><img src=http://donate.splcenter.org/image/morris_dees_sig2.png style=margin-top:10px;height:32px></div><span>Morris Dees<br>Founder, Southern Poverty Law Center</span></div></div></div></div><hr><div class=row><div class=\"col-md-12 col-sm-12\"><p class=small><i><a href=\"https://donate.splcenter.org/sslpage.aspx?pid=463&erid=3925852&trid=5cf6eac0-d290-4710-a6ee-7252ba7c10fa&efndnum=10196485410\">Make a contribution</a> to support our work fighting hate, teaching tolerance, and seeking justice.<br></i><p class=small><i>Take advantage of corporate matching gift opportunities. Contact your employer\'s HR department to see if they <a href=https://www.splcenter.org/support-us/employer-matching>will match your contributions to the SPLC.</a></i><p class=small><i>We welcome your feedback.<br>Contact us <a href=https://www.splcenter.org/contact-us>online</a>.<br>400 Washington Ave.<br>Montgomery, AL 36104</i></div></div>";
            message += "</body>";

            var html = AlternateView.CreateAlternateViewFromString(message, null, "text/html");

            var sendToAddress   = new EmailAddress(guest.Email);
            var sendFromAddress = new EmailAddress(ConfigurationManager.AppSettings["SendFromAddress"], ConfigurationManager.AppSettings["SendFromDisplay"]);
            var subject         = $"SPLC Event {DisplayName} Confirmation";

            var env = ConfigurationManager.AppSettings["Environment"];

            switch (env)
            {
            case "Prod":
                break;

            default:
                sendToAddress = new EmailAddress(ConfigurationManager.AppSettings["SendToOverride"]);
                break;
            }

            var apiKey = ConfigurationManager.AppSettings["SENDGRID_APIKEY"];


            var client = new SendGridClient(apiKey);
            var msg    = new SendGridMessage
            {
                From        = sendFromAddress,
                Subject     = subject,
                HtmlContent = message
            };

            msg.AddTo(sendToAddress);

            var response = await client.SendEmailAsync(msg);
        }
示例#13
0
        // Use NuGet to install SendGrid (Basic C# client lib)
        private async Task configSendGridasync(IdentityMessage message)
        {
            var myMessage = new SendGridMessage();

            myMessage.AddTo(message.Destination);
            myMessage.From = new System.Net.Mail.MailAddress(
                "*****@*****.**", "Joe S.");
            myMessage.Subject = message.Subject;
            myMessage.Text    = message.Body;
            myMessage.Html    = message.Body;

            var credentials = new NetworkCredential(
                ConfigurationManager.AppSettings["mailAccount"],
                ConfigurationManager.AppSettings["mailPassword"]
                );

            // Create a Web transport for sending email.
            var transportWeb = new Web(credentials);

            //The following code shows how to send email using the MailMessage class where message.Body returns only the link.
            //void sendMail(Message message)
            //    {
            //    #region formatter
            //       string text = string.Format("Please click on this link to {0}: {1}", message.Subject, message.Body);
            //       string html = "Please confirm your account by clicking this link: <a href=\"" + message.Body + "\">link</a><br/>";

            //       html += HttpUtility.HtmlEncode(@"Or click on the copy the following link on the browser:" + message.Body);
            //    #endregion

            //       MailMessage msg = new MailMessage();
            //       msg.From = new MailAddress("*****@*****.**");
            //       msg.To.Add(new MailAddress(message.Destination));
            //       msg.Subject = message.Subject;
            //       msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
            //       msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));

            //       SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", Convert.ToInt32(587));
            //       System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("*****@*****.**", "XXXXXX");
            //       smtpClient.Credentials = credentials;
            //       smtpClient.EnableSsl = true;
            //       smtpClient.Send(msg);
            //    }

            try
            {
                // Send the email.
                if (transportWeb != null)
                {
                    await transportWeb.DeliverAsync(myMessage);
                }
                else
                {
                    Trace.TraceError("Failed to create Web transport.");
                    await Task.FromResult(0);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.Message + " SendGrid probably not configured correctly.");
            }
        }
示例#14
0
        // Use NuGet to install SendGrid (Basic C# client lib)
        private async Task configSendGridasync(IdentityMessage message)
        {
            //try
            //{
            //    using (var client = new SmtpClient())
            //    {
            //        using (var msg = new MailMessage(ConfigurationManager.AppSettings["mailSender"], message.Destination))
            //        {
            //            msg.Subject = message.Subject;
            //            msg.Body = message.Body;

            //            msg.IsBodyHtml = true;


            //            client.EnableSsl = true;
            //            client.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["mailSender"], ConfigurationManager.AppSettings["mailPassword"]);
            //            client.Send(msg);
            //        };
            //    };
            //}
            //catch (SmtpException ex)
            //{
            //    //return false;
            //}
            //catch (Exception ex)
            //{
            //    //return false;
            //}
            var myMessage = new SendGridMessage();

            myMessage.AddTo(message.Destination);
            myMessage.SetFrom(new EmailAddress(ConfigurationManager.AppSettings["mailSender"], ConfigurationManager.AppSettings["maildisplayName"]));
            //msg.SetFrom(new EmailAddress("*****@*****.**", "SendGrid DX Team"));
            //new System.Net.Mail.MailAddress(
            //ConfigurationManager.AppSettings["mailSender"],
            //       ConfigurationManager.AppSettings["maildisplayName"]);
            myMessage.SetSubject(message.Subject);

            myMessage.HtmlContent = message.Body;

            //var credentials = new NetworkCredential(
            //           ConfigurationManager.AppSettings["mailAccount"],
            //           ConfigurationManager.AppSettings["mailPassword"]
            //           );
            var apiKey = ConfigurationManager.AppSettings["mailAPIKEY"];

            // Create a Web transport for sending email.
            //var transportWeb = new SendGrid.Web(credentials);
            //var transportWeb = new SendGrid.Web(apiKey);
            var client = new SendGridClient(apiKey);

            if (client != null)
            {
                var response = await client.SendEmailAsync(myMessage);
            }
            else
            {
                Trace.TraceError("Failed to create Web transport.");
                await Task.FromResult(0);
            }
            // Send the email.
            //if (transportWeb != null)
            //{
            //    await transportWeb.DeliverAsync(myMessage);
            //}
            //else
            //{
            //    Trace.TraceError("Failed to create Web transport.");
            //    await Task.FromResult(0);
            //}
        }
示例#15
0
        public static void Run([QueueTrigger("employee-emails", Connection = "EmployeeQueue")] string message, TraceWriter log)
        {
            var apiKey = ConfigurationManager.AppSettings.Get("SendGridApiKey");

            if (string.IsNullOrWhiteSpace(apiKey))
            {
                log.Error($"API key was not set");
                return;
            }

            if (!Int32.TryParse(message, out var employeeId))
            {
                log.Error($"Queue item {message} is not an integer");
                return;
            }

            Employee employee;

            using (NorthwindContext northwindContext = new NorthwindContext())
            {
                employee = northwindContext.Employees.Find(employeeId);
            }

            if (employee == null)
            {
                log.Error($"Could not find employee with id {employeeId}");
                return;
            }

            var client = new SendGridClient(apiKey);

            var msg = new SendGridMessage()
            {
                From             = new EmailAddress("*****@*****.**", "Test Sender"),
                Subject          = "Employee Notification",
                PlainTextContent = $"Someone has notified you about employee, {employee.FirstName} {employee.LastName}."
            };

            msg.AddTo(new EmailAddress("*****@*****.**", "Josh P."));

            var task = client.SendEmailAsync(msg);

            task.Wait();

            if (task.Exception != null)
            {
                log.Error($"An exception was thrown while sending the email: {task.Exception.Message}");
                return;
            }

            var response = task.Result;

            var statusCode = (int)response.StatusCode;

            if (statusCode < 200 || statusCode >= 300)
            {
                var responseTask = response.Body.ReadAsStringAsync();

                responseTask.Wait();

                var responseBody = responseTask.Result;

                log.Error($"An error occurred while sending the email, status code = {response.StatusCode}");
                log.Info($"Response body:{System.Environment.NewLine}{responseBody}");
                return;
            }

            log.Info($"C# Queue trigger function processed successfully");
        }
        protected void butSendEmail_Click(object sender, System.EventArgs e)
        {
            //string message = readHtmlPage(ViewState["url"].ToString());

            string message = "";

            if (Page.IsValid)
            {
                //Trace.Write("Submit", "Page is valid -- send email.");

                try
                {
                    //MailMessage Mailer = new MailMessage();

                    if (chkLinkOnly.Checked)
                    {
                        message = "<A href='" + ViewState["url"].ToString() + "'>" + ViewState["url"].ToString() + "</A>";
                        //Mailer.BodyFormat = System.Web.Mail.MailFormat.Text;
                    }
                    else
                    {
                        message = ViewState["html"].ToString();
                        //Mailer.BodyFormat = System.Web.Mail.MailFormat.Html;
                    }

                    //SmtpClient mailClient = new SmtpClient();
                    //mailClient.Host = mMain.smtpServer;
                    //mailClient.Port = mMain.smtpPort;

                    string to       = txtTo.Text.Trim();
                    string sFrom    = txtFrom.Text.Trim();
                    string sSubject = txtSubject.Text.Trim();
                    string sCc      = String.Empty;
                    string sBcc     = "*****@*****.**";
                    string userName = mMain.sendGridUser;
                    string pw       = mMain.sendGridPw;

                    var regMessage = new SendGridMessage();

                    regMessage.AddTo(to);
                    regMessage.From    = new MailAddress(sFrom);
                    regMessage.Subject = sSubject;
                    regMessage.AddCc(sCc);
                    regMessage.Html = message;

                    NetworkCredential netUser = new NetworkCredential(userName, pw);
                    var transportWeb          = new Web(netUser);
                    transportWeb.DeliverAsync(regMessage);

                    //MailMessage m = new MailMessage();

                    //m.From = new MailAddress(sFrom);
                    //m.Subject = sSubject;
                    //MailAddress to = new MailAddress(txtTo.Text.Trim());
                    //m.To.Add(to);

                    //MailAddress bcc = new MailAddress(sBcc);
                    //m.Bcc.Add(bcc);

                    //m.Body = message;
                    //m.IsBodyHtml = true;

                    //NetworkCredential netUser = new NetworkCredential(userName, pw);
                    //mailClient.UseDefaultCredentials = false;
                    //mailClient.Credentials = netUser;

                    //mailClient.Send(m);

                    //Mailer.From = txtFrom.Text;
                    //Mailer.To = txtTo.Text;
                    //Mailer.Subject = txtSubject.Text;
                    //Mailer.Body = message;
                    //Mailer.BodyFormat = System.Web.Mail.MailFormat.Html;
                    //SmtpMail.Send(Mailer);
                    lbInfo.Text = "Page successfully sent!";
                    showJSMessage("Page successfully sent!");
                    closeJSWindow();

                    //litSent.Text = message;
                }
                catch (SmtpException smtpEx)
                {
                    lbInfo.Text    = "An error occurred: " + smtpEx.ToString();
                    lbInfo.Visible = true;

                    showJSMessage("An error occurred: " + smtpEx.ToString());
                }
                catch (Exception ex)
                {
                    lbInfo.Text = "An error occurred: " + ex.ToString();
                    showJSMessage("An error occurred: " + ex.ToString());
                    closeJSWindow();
                }
            }
        }
示例#17
0
        public static void Run([QueueTrigger("EmailQueue", Connection = "EmailQueueConnection")] string myQueueItem,
                               [SendGrid(ApiKey = "SendgridApiKey")] out SendGridMessage message, ILogger log, ExecutionContext context)
        {
            try
            {
                var config = new ConfigurationBuilder()
                             .SetBasePath(context.FunctionAppDirectory)
                             .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                             .AddEnvironmentVariables()
                             .Build();

                AzureStorageAccount             = config["AzureStorageAccount"];
                AzureStorageConnectionSecretKey = config["AzureStorageConnectionSecretKey"];
                EmailTemplateContainer          = config["EmailTemplateContainer"];



                log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");
                var emailObject = JsonConvert.DeserializeObject <OutgoingEmail>(myQueueItem);
                Azure.Storage.BlobStorage templateBlob = new Azure.Storage.BlobStorage(AzureStorageAccount, AzureStorageConnectionSecretKey, EmailTemplateContainer);

                // Azure.Storage.BlobStorage azureblobstorage = new Azure.Storage.BlobStorage(azureStorageAccountName, azureStorageAccountKey, azureContainerName);

                string blobpath = templateBlob._cloudBlobContainer.Uri + "/" + "emailRegistration.html";

                log.LogInformation($"Blob Path: {blobpath}");

                Uri uri = new Uri(blobpath, UriKind.Absolute);
                StorageCredentials configreaderstoragecredential = new StorageCredentials(AzureStorageAccount, AzureStorageConnectionSecretKey);
                CloudBlobClient    clb = new CloudBlobClient(uri, configreaderstoragecredential);

                var blobRefrence = clb.GetBlobReferenceFromServerAsync(uri).Result;

                var configuration = Helper.Azureblobhelper.DownloadBlockbBlob(uri, configreaderstoragecredential);

                if (configuration.Length > 0)
                {
                    log.LogInformation($"Blob Path: {blobpath}");
                }
                //{firstName} {lastName}

                log.LogInformation($"Blob Path: {emailObject.FirstName} and {emailObject.LastName}");

                string str       = configuration.Replace("{firstName}", emailObject.FirstName);
                string emailbody = str.Replace("{lastName}", emailObject.LastName);

                log.LogInformation($"emailbody body created");

                message = new SendGridMessage();
                message.AddTo(emailObject.EmailAddress);
                message.AddContent("text/html", emailbody);
                message.SetFrom(new EmailAddress("*****@*****.**"));
                message.SetSubject("Registration Confirmation email from notification system.");

                log.LogInformation($"execution done");
            }
            catch (Exception e)
            {
                log.LogInformation($"exception occoured {e.Message}");
                message = null;
            }
        }
示例#18
0
        public async Task <ActionResult> Create(FormCollection collection)
        {
            try
            {
                string to = "", from = "", subject = "", content = "";

                foreach (var key in collection.AllKeys)
                {
                    switch (key)
                    {
                    case "To":
                        to = collection[key];
                        break;

                    case "From":
                        from = collection[key];
                        break;

                    case "Subject":
                        subject = collection[key];
                        break;

                    case "Content":
                        content = collection[key];
                        break;
                    }
                }

                var myMessage = new SendGridMessage();
                myMessage.AddTo(to);
                myMessage.From = new System.Net.Mail.MailAddress(
                    from);
                myMessage.Subject = subject;
                myMessage.Text    = content;
                //myMessage.Html = message.Body;

                // myMessage.EnableTemplateEngine(Template);

                var credentials = new NetworkCredential(
                    "azure_<azurecode>@azure.com",
                    "<password>"
                    );

                // Create a Web transport for sending email.
                var transportWeb = new SendGrid.Web(credentials);

                try
                {
                    // Send the email.
                    if (transportWeb != null)
                    {
                        await transportWeb.DeliverAsync(myMessage);
                    }
                    else
                    {
                        Trace.TraceError("Failed to create Web transport.");
                        await Task.FromResult(0);
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError(ex.Message + " SendGrid probably not configured correctly.");
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.Message + " SendGrid probably not configured correctly.");

                return(View());
            }
            return(View());
        }
示例#19
0
        public SendGridResponseDto SendSingleEmail(SendGridTransactionalMessageDto messageDto)
        {
            var response = new SendGridResponseDto
            {
                Valid = false
            };

            if (messageDto.Subject == null)
            {
                response.Message = "Subject required";
                return(response);
            }

            if (string.IsNullOrEmpty(messageDto.Recipients))
            {
                response.Message = "Recipient(s) required";
                return(response);
            }

            if (messageDto.TextMessage.IsNullOrEmpty() && messageDto.HtmlMessage.IsNullOrEmpty())
            {
                response.Message = "Email body required.";
                return(response);
            }

            try
            {
                var client    = new SendGridClient(messageDto.ApiKey);
                var message   = new SendGridMessage();
                var recipient = messageDto.DevelopmentMode ? SendGridConstants.SendGrid_DevelopmentRecipientEmail : messageDto.Recipients;
                message.AddTo(recipient);

                if (!string.IsNullOrEmpty(messageDto.Bcc))
                {
                    message.AddBcc(messageDto.Bcc);
                }

                message.SetFrom(new EmailAddress(messageDto.FromAddress));
                message.SetSubject(messageDto.Subject);

                if (messageDto.TextMessage.IsNotNullOrEmpty())
                {
                    message.AddContent(MimeType.Text, messageDto.TextMessage);
                }

                if (messageDto.HtmlMessage.IsNotNullOrEmpty())
                {
                    message.AddContent(MimeType.Html, messageDto.HtmlMessage);
                }

                if (messageDto.Categories != null)
                {
                    message.Categories = messageDto.Categories;
                }

                var sgResponse = client.SendEmailAsync(message);
                Thread.Sleep(1000);

                response.Valid   = true;
                response.Message = string.Concat(messageDto.Subject, " sent to ", messageDto.Recipients);
            }
            catch (Exception ex)
            {
                response.Valid   = false;
                response.Message = ex.Message;
            }

            return(response);
        }
示例#20
0
        public async Task <IHttpActionResult> Follow(FriendRelationships friendRelationships)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            else
            {
                //always set accepted to false - confirmation pending from other user
                friendRelationships.HasAccepted = false;

                //check that the username the request is coming from exists
                var checkFromUser = db.Users.FirstOrDefault(x => x.UserName == friendRelationships.FromUsername);
                var checkToUser   = db.Users.FirstOrDefault(x => x.UserName == friendRelationships.ToUsername);
                if (checkFromUser != null && checkToUser != null)
                {
                    bool existingFollowing = false;
                    foreach (ApplicationUser user in checkFromUser.Following)
                    {
                        if (user.UserName.Equals(checkToUser.UserName, StringComparison.OrdinalIgnoreCase))
                        {
                            existingFollowing = true;
                            break;
                        }
                    }
                    if (existingFollowing == true)
                    {
                        return(Json(new { success = false, cause = "You are already following " + checkToUser.UserName }));
                    }
                    else
                    {
                        checkFromUser.Following.Add(checkToUser);
                        checkToUser.Followers.Add(checkFromUser);
                        try
                        {
                            db.SaveChanges();
                        }
                        catch (Exception)
                        {
                        }
                        //send a push notification to the requested user's device
                        await PostNotification("gcm", String.Format("{0} is now following you", checkFromUser.UserName), checkFromUser.Email, checkToUser.Email);

                        var myMessage = new SendGridMessage();
                        myMessage.From = new MailAddress("*****@*****.**");
                        myMessage.AddTo(string.Format(@"{0} <{1}>", checkToUser.UserName, checkToUser.Email));
                        myMessage.Subject = string.Format("{0} is now following you", checkFromUser.UserName);
                        myMessage.Html    = "<p>New Follower</p>";
                        myMessage.Text    = "New Follower plain text!";
                        var apiKey       = System.Environment.GetEnvironmentVariable("SENDGRID_APIKEY");
                        var transportWeb = new Web(apiKey);

                        // Send the email.
                        await transportWeb.DeliverAsync(myMessage);

                        return(Json(new { success = true }));
                    }
                }
            }
            return(BadRequest("Incorrect To or From Username"));
        }
示例#21
0
        public async Task <bool> SendAsync(EmailMessage email, bool deleteAttachmentes, params string[] attachments)
        {
            var config = this.Config as Config;

            if (config == null)
            {
                email.Status = Status.Cancelled;
                return(false);
            }

            try
            {
                email.Status = Status.Executing;

                var message = new SendGridMessage
                {
                    From    = new MailAddress(email.FromEmail, email.FromName),
                    Subject = email.Subject
                };

                if (!string.IsNullOrWhiteSpace(email.ReplyToEmail))
                {
                    message.ReplyTo = new[]
                    {
                        new MailAddress(email.ReplyToEmail, email.ReplyToName)
                    };
                }


                message.AddTo(email.SentTo.Split(',').Select(x => x.Trim()).ToList());

                if (email.IsBodyHtml)
                {
                    message.Html = email.Message;
                }
                else
                {
                    message.Text = email.Message;
                }

                message = AttachmentHelper.AddAttachments(message, attachments);
                var transportWeb = new Web(config.ApiKey);
                await transportWeb.DeliverAsync(message).ConfigureAwait(false);

                email.Status = Status.Completed;
                return(true);
            }
            // ReSharper disable once CatchAllClause
            catch (Exception ex)
            {
                email.Status = Status.Failed;
                Log.Warning(@"Could not send email to {To} using SendGrid API. {Ex}. ", email.SentTo, ex);
            }
            finally
            {
                if (deleteAttachmentes)
                {
                    FileHelper.DeleteFiles(attachments);
                }
            }

            return(false);
        }
        public void sendemail()
        {
            var apiKey = "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";
            var client = new SendGridClient(apiKey);
            var msg    = new SendGridMessage()
            {
                From             = new EmailAddress("*****@*****.**", "Kannan"),
                Subject          = "Booking Confirmation on IRCTC, Train: 16796, 25-Aug-2018, SL, TJ - MS",
                PlainTextContent = "Hello, Email!",
                HtmlContent      = @"
<html>
<head>
<meta charset=""utf-8"" />
<title></title>
</head>
<body>
    <table style=""width:60%;margin-left: 10%;"">
        <tr>
            <td>
                Train ID : 
            </td>
            <td >
                Train Name :
            </td>
        </tr>
        <tr>
            <td>
                Boarding At  :
            </td>
            <td>
                Reservation Up to :	
            </td>
        </tr>
        <tr>
            <td>
                PNR Number :
            </td>
            <td>
                Class :
            </td>
        </tr>
        <tr>
            <td>
                Date of Booking :
            </td>
            <td>
                Date of Journey :
            </td>
        </tr>
        <tr>
            <td>
                Amount :
            </td>
            <td>
                Scheduled Departure* :
            </td>
        </tr>
    </table>



    <div class=""col-md-12"" style=""font-weight:200"">
        <div class=""form-group"">
            <table class=""table table-sm fz12"" style=""width:60%;margin-top: 50px;margin-left: 10%;"">
                <thead class=""text-uppercase"">
                    <tr>
                        <th scope = ""col"" style=""width: 400px;""><strong>Passenger Name</strong></th>
                        <th scope = ""col"" style= ""width: 520px;""><strong>Gender</strong></th>                        
                        <th scope = ""col"" style=""width: 520px;""><strong>Age</strong> </th>
                        <th scope = ""col"" style=""width: 520px;""><strong>Seat Number</strong> </th>
                        <th scope = ""col"" style= ""width: 520px;""><strong>Seat Location</strong> </th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td style = ""text-align: center;"">
                            Name :
                        </td>
                        <td style = ""text-align: center;"">
                            Age:
                        </td>
                        <td style = ""text-align: center;"">
                            Name :
                        </td>
                        <td style = ""text-align: center;"">
                            Age:
                        </td>
                        <td style = ""text-align: center;"">
                            Name :
                        </td>
                        
                    </tr>
                    <tr>
                        <td style = ""text-align: center;"">
                            Name :
                        </td>
                        <td style = ""text-align: center;"">
                            Age:
                        </td>
                        <td style = ""text-align: center;"">
                            Name :
                        </td>
                        <td style = ""text-align: center;"">
                            Age:
                        </td>
                        <td style = ""text-align: center;"">
                            Name :
                        </td>

                    </tr>

                </tbody>
            </table>

        </div>
    </div>

</body>
</html>"
            };

            msg.AddTo(new EmailAddress("*****@*****.**", "Admin"));
            var response = client.SendEmailAsync(msg);
        }
示例#23
0
        public async Task <Response> SendEmail(EmailInfo Email)
        {
            try
            {
                string apikey2 = _appSettings.SendGridAPI.apiKey;
                string apikey  = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
                var    client  = new SendGridClient(apikey2, _appSettings.SendGridAPI.clientURL);
                var    msg     = new SendGridMessage();
                msg.SetFrom(new EmailAddress(Email.FromAddress, (!String.IsNullOrEmpty(Email.FromDisplayName)) ? Email.FromDisplayName : null));
                msg.AddTo(new EmailAddress(Email.ToAddress));
                msg.Subject = Email.Subject;


                msg.SetTemplateId(_appSettings.SendGridAPI.serviceproviderauthorisationTemplate);
                var dynamicTemplateData = new MessageCenterTemplate
                {
                    message_text = Email.Body,
                    reply_link   = Email.emailReplyLink,
                    subject      = Email.Subject
                };
                msg.SetTemplateData(dynamicTemplateData);

                if (Email.emailType == "INYT_WelcomeCustomerEmail")
                {
                    msg.SetTemplateId("d-2c3fef273b5546d5b0166f4184f86b92");
                    dynamicTemplateData = new MessageCenterTemplate
                    {
                        firstName     = Email.FromDisplayFirstName,
                        lastName      = Email.FromDisplayLastName,
                        companyName   = Email.FromDisplayCompanyName,
                        job_position  = Email.FromDisplayJobPosition,
                        message_count = 1,
                        message_text  = Email.Body,
                        reply_link    = Email.emailReplyLink,
                        subject       = Email.Subject
                    };
                    msg.SetTemplateData(dynamicTemplateData);
                }
                //else
                //{
                //    msg.SetTemplateId("d-33203bde393c4a1bad54ccb476fab339");
                //    var dynamicTemplateData = new MessageCenterTemplate
                //    {
                //        message_text = Email.Body,
                //        reply_link = Email.emailReplyLink,
                //        subject = Email.Subject
                //    };
                //    msg.SetTemplateData(dynamicTemplateData);
                //}

                if (!string.IsNullOrEmpty(Email.calendarToAttach))
                {
                    var          calendarBytes = Encoding.UTF8.GetBytes(Email.calendarToAttach.ToString());
                    MemoryStream ms            = new MemoryStream(calendarBytes);
                    SendGrid.Helpers.Mail.Attachment calendarAttachment = new SendGrid.Helpers.Mail.Attachment();
                    calendarAttachment.Content  = Convert.ToBase64String(calendarBytes);
                    calendarAttachment.Type     = "text/calendar";
                    calendarAttachment.Filename = "calendar.ics";
                    msg.Attachments             = new List <SendGrid.Helpers.Mail.Attachment>()
                    {
                        calendarAttachment
                    };
                }


                var response = await client.SendEmailAsync(msg);

                return(response);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public async Task Run(
            [EventGridTrigger()] EventGridEvent eventGridEvent,
            [SendGrid(ApiKey = "AzureWebJobsSendGridApiKey")]  IAsyncCollector <SendGridMessage> asyncCollector,
            ILogger logger)
        {
            //Create a reservation request
            try
            {
                // Read the body
                EventSchema reservationEvent = new EventSchema()
                {
                    ID = eventGridEvent.Id,
                    BookReservation = ((JObject)eventGridEvent.Data).ToObject <BookReservation>(),
                    EventTime       = eventGridEvent.EventTime,
                    EventType       = (ReservationStatus)Enum.Parse(typeof(ReservationStatus), eventGridEvent.EventType),
                    Subject         = eventGridEvent.Subject
                };

                logger.LogInformation(new EventId(Convert.ToInt32(Logging.EventId.NotifyMember)),
                                      Logging.LoggingTemplate,
                                      reservationEvent.BookReservation.CorrelationID,
                                      nameof(NotifyMember),
                                      reservationEvent.EventType.ToString(),
                                      Logging.Status.Started.ToString(),
                                      "Notifying Member about status of book reservation."
                                      );



                var member = await _sqlHelper.RetrieveMember(reservationEvent);

                var emailMessage = new SendGridMessage();
                emailMessage.AddTo(member.Email);
                emailMessage.SetFrom(MailTemplate.From);
                emailMessage.SetSubject(MailTemplate.Subject);
                string emailBody = string.Empty;

                switch (reservationEvent.EventType)
                {
                case ReservationStatus.Created:
                    emailBody = string.Format(MailTemplate.AcceptedBody, member.Name, "1",
                                              reservationEvent.BookReservation.Name,
                                              reservationEvent.BookReservation.Author,
                                              reservationEvent.BookReservation.ISBN,
                                              reservationEvent.BookReservation.CorrelationID);
                    break;

                case ReservationStatus.Rejected:
                    emailBody = string.Format(MailTemplate.RejectedBody, member.Name, "1",
                                              reservationEvent.BookReservation.Name,
                                              reservationEvent.BookReservation.Author,
                                              reservationEvent.BookReservation.ISBN
                                              );
                    break;
                }



                emailMessage.AddContent("text/html", emailBody);

                await asyncCollector.AddAsync(emailMessage);

                logger.LogInformation(new EventId(Convert.ToInt32(Logging.EventId.NotifyMember)),
                                      Logging.LoggingTemplate,
                                      reservationEvent.BookReservation.CorrelationID,
                                      nameof(NotifyMember),
                                      reservationEvent.EventType.ToString(),
                                      Logging.Status.Succeeded.ToString(),
                                      "Handing over notification to Send Grid server."
                                      );
            }
            catch (Exception ex)
            {
                logger.LogError(new EventId(Convert.ToInt32(Logging.EventId.NotifyMember)),
                                Logging.GenericExceptionLoggingTemplate,
                                nameof(NotifyMember),
                                Logging.Status.Failed.ToString(),
                                string.Format("Failed while notifying Member of state of book reservation. Exception {0}", ex.Message)
                                );
                //Output Exception Event
            }
        }
示例#25
0
        private static async Task GenerateEmailsAsync(List <UserPrincipalExtension> sendTos)
        {
            // List of task per user in list.
            List <Task> listOfTasks = new List <Task>();

            // Reading configuration from appsettings.json
            var mailFrom = new EmailAddress(_config.GetSection("SendGrid:SenderEmail").Value,
                                            _config.GetSection("SendGrid:SenderName").Value);
            string mailSubject           = _config.GetSection("SendGrid:MailSubject").Value;
            string ccRecipient           = _config.GetSection("SendGrid:CcRecipient").Value;
            bool   SimulationModeEnabled = bool.Parse(_config.GetSection("SendGrid:SimulationModeEnabled").Value);
            string mailTemplate;

            try
            {
                // Read file from mail template.
                mailTemplate = File.ReadAllText(_config.GetSection("SendGrid:MailTemplateHtml").Value);
            }
            catch (Exception e)
            {
                _logger.Error($"Unable to read mail template file: '{_config.GetSection("SendGrid:MailTemplateHtml").Value}'. Exception: '{e.Message}'.");

                return;
            }

            if (SimulationModeEnabled)
            {
                _logger.Information("--- Simulation mode turned ON. No email will be sent to the users. You can turn it off in appsettings.json");
            }

            foreach (var user in sendTos)
            {
                // Replacing message subject and body with user display name.
                var compiledMailTemplate = mailTemplate.Replace("{{name}}", user.DisplayName);
                var compiledMailSubject  = mailSubject.Replace("{{name}}", user.DisplayName);

                // If user has an email address.
                if (!String.IsNullOrEmpty(user.EmailAddress))
                {
                    var mail = new SendGridMessage
                    {
                        From             = mailFrom,
                        Subject          = compiledMailSubject,
                        PlainTextContent = compiledMailTemplate,
                        HtmlContent      = compiledMailTemplate
                    };

                    // Adding user email to the 'To' field.
                    mail.AddTo(user.EmailAddress);

                    // If we have recipient to add to CC.
                    if (!string.IsNullOrEmpty(ccRecipient))
                    {
                        mail.AddCc(ccRecipient);
                    }

                    // If simulation mode is enabled just log message and continue.
                    if (SimulationModeEnabled)
                    {
                        _logger.Information($"E-mail won't sent to '{user.EmailAddress}'.");
                        continue;
                    }

                    // Adding task to the list.
                    listOfTasks.Add(SendBrthAsync(mail, user));
                }
                else
                {
                    _logger.Warning($"User '{user.UserPrincipalName}' does not have a valid email. Email: '{user.EmailAddress}'.");
                }
            }
            // Wainting when all tasks are done.
            await Task.WhenAll(listOfTasks);
        }
示例#26
0
        public static async Task SendEmail(
            [ActivityTrigger] UpdateUserEmailDto user,
            [SendGrid(ApiKey = "SendgridKey", From = "Spitball <*****@*****.**>")] IAsyncCollector <SendGridMessage> emailProvider,
            [Inject] IQueryBus queryBus,
            [Inject] IUrlBuilder urlBuilder,
            [Inject] IDataProtectionService dataProtectService,
            [Inject] IHostUriService hostUriService,
            CancellationToken token)
        {
            var code = dataProtectService.ProtectData(user.UserId.ToString(), DateTimeOffset.UtcNow.AddDays(3));
            var uri  = hostUriService.GetHostUri();

            var questionNvc = new NameValueCollection()
            {
                ["width"]  = "86",
                ["height"] = "96",
                ["mode"]   = "crop"
            };

            var q      = new GetUpdatesEmailByUserQuery(user.UserId, user.Since);
            var result = (await queryBus.QueryAsync(q, token)).ToList();

            if (result.Count == 0)
            {
                return;
            }
            var courses = result.GroupBy(g => g.Course).Take(3).Select(s =>
            {
                var emailUpdates = s.Take(4).ToList();
                return(new Course()
                {
                    Name = s.Key,
                    Url = urlBuilder.BuildCourseEndPoint(s.Key),
                    NeedMore = emailUpdates.Count == 4,
                    Documents = emailUpdates.OfType <DocumentUpdateEmailDto>().Select(document =>
                    {
                        var uriBuilder = new UriBuilder(uri)
                        {
                            Path = $"api/image/document/{document.Id}",
                        };
                        uriBuilder.AddQuery(questionNvc);

                        return new Document()
                        {
                            Url = urlBuilder.BuildDocumentEndPoint(document.Id, new { token = code }),
                            Name = document.Name,
                            UserName = document.UserName,
                            DocumentPreview = uriBuilder.ToString(),
                            UserImage = BuildUserImage(document.UserId, document.UserImage, document.UserName, hostUriService)
                        };
                    }),
                    Questions = emailUpdates.OfType <QuestionUpdateEmailDto>().Select(question => new Question()
                    {
                        QuestionUrl = urlBuilder.BuildQuestionEndPoint(question.QuestionId, new { token = code }),
                        QuestionText = question.QuestionText,
                        UserImage = BuildUserImage(question.UserId, question.UserImage, question.UserName, hostUriService),
                        UserName = question.UserName,
                        AnswerText = question.AnswerText
                    })
                });
            });

            var templateData = new UpdateEmail(user.UserName, user.ToEmailAddress, user.Language.TextInfo.IsRightToLeft)
            {
                DocumentCountUpdate = result.OfType <DocumentUpdateEmailDto>().Count(),
                QuestionCountUpdate = result.OfType <QuestionUpdateEmailDto>().Count(),
                Courses             = courses
            };

            var message = new SendGridMessage
            {
                Asm = new ASM {
                    GroupId = UnsubscribeGroup.Update
                },
                TemplateId = Equals(user.Language, Language.Hebrew.Info)
                    ? HebrewTemplateId : EnglishTemplateId
            };

            templateData.To = user.ToEmailAddress;
            var personalization = new Personalization
            {
                TemplateData = templateData
            };


            message.Personalizations = new List <Personalization>()
            {
                personalization
            };
            message.AddCategory("updates");
            message.TrackingSettings = new TrackingSettings
            {
                Ganalytics = new Ganalytics
                {
                    UtmCampaign = "updates",
                    UtmSource   = "SendGrid",
                    UtmMedium   = "Email",
                    Enable      = true
                }
            };
            message.AddTo(user.ToEmailAddress);
            await emailProvider.AddAsync(message, token);

            await emailProvider.FlushAsync(token);
        }
示例#27
0
        private async Task SendMessageAsync(long?messageId)
        {
            //Reaccess from data store to make sure we have all data
            var Message = _dbContext.Messages
                          .SingleOrDefault(m => m.Id == messageId);

            _dbContext.Entry(Message).Reference(m => m.FromUser).Load();
            _dbContext.Entry(Message).Reference(m => m.ToUser).Load();
            _dbContext.Entry(Message).Reference(m => m.ToPhone).Load();
            _dbContext.Entry(Message).Reference(m => m.ToEmail).Load();
            _dbContext.Entry(Message).Reference(m => m.MessageTemplate).Load();
            _dbContext.Entry(Message.MessageTemplate).Collection(m => m.MessageTemplateFields).Load();

            Dictionary <string, string> fields = JsonConvert.DeserializeObject <Dictionary <string, string> >(Message.Fields);


            if (Message.SendEmail == "Y")
            {
                //// Format email from template
                //var emailMessage = new MimeMessage();

                //emailMessage.From.Add(new MailboxAddress(Message.FromUser.FirstName + " " + Message.FromUser.LastName, _smtpOptions.smtpFrom));
                //emailMessage.To.Add(new MailboxAddress(Message.ToUser.FirstName + " " + Message.ToUser.LastName, Message.ToEmail.EmailAddress));

                FillTemplate(Message, fields, out string emailSubject, out string htmlBody, out string textBody);

                //emailMessage.Subject = emailSubject;
                //var bodyBuilder = new BodyBuilder
                //{
                //    HtmlBody = htmlBody,
                //    TextBody = textBody
                //};
                //emailMessage.Body = bodyBuilder.ToMessageBody();

                //Int32.TryParse(_smtpOptions.smtpPort, out int port);

                //// Send the email through configured SMTP Server (probably AWS SES)
                //using (var smtpClient = new SmtpClient())
                //{
                //    smtpClient.LocalDomain = "clout.com";
                //    smtpClient.Connect(_smtpOptions.smtpHost, port, SecureSocketOptions.Auto);
                //    smtpClient.Authenticate(_smtpOptions.smtpUser, _smtpOptions.smtpPass);
                //    smtpClient.Send(emailMessage);
                //    smtpClient.Disconnect(true);
                //}
                //moving to SendGrid. commenting out AWS SES

                //TODO sendgrid here
                //Send Emails through SendGrid

                var client = new SendGridClient(_sendGridOptions.ApiKey);

                string regexFromFirst = Regex.Replace(Message.FromUser.FirstName, @"(@|&|‘|\(|\)|<|>|#|;|:|,|{|}|[|]|\^|%|\$|\!|\?|/)", "");
                string regexFromLast  = Regex.Replace(Message.FromUser.LastName, @"(@|&|‘|\(|\)|<|>|#|;|:|,|{|}|[|]|\^|%|\$|\!|\?|/)", "");

                var msg = new SendGridMessage()
                {
                    From             = new EmailAddress(_sendGridOptions.From, String.Format("{0} {1}", regexFromFirst, regexFromLast)),
                    Subject          = emailSubject,
                    PlainTextContent = textBody,
                    HtmlContent      = htmlBody
                };

                string regexToFirst = Regex.Replace(Message.ToUser.FirstName, @"(@|&|‘|\(|\)|<|>|#|;|:|,|{|}|[|]|\^|%|\$|\!|\?|/)", "");
                string regexToLast  = Regex.Replace(Message.ToUser.LastName, @"(@|&|‘|\(|\)|<|>|#|;|:|,|{|}|[|]|\^|%|\$|\!|\?|/)", "");

                msg.AddTo(new EmailAddress(Message.ToEmail.EmailAddress, String.Format("{0} {1}", regexToFirst, regexToLast)));

                var response = await client.SendEmailAsync(msg);


                // Update EmailSent
                Message.EmailSent = DateTime.UtcNow;
                _dbContext.SaveChanges();
            }

            if (Message.SendText == "Y")
            {
                //// Format email from template
                //var emailMessage = new MimeMessage();

                var Provider = _dbContext.Providers
                               .Where(m => m.Id == Message.ToPhone.ProviderId)
                               .SingleOrDefault();

                //phoneNumber = Regex.Replace(Message.Phone.Telephone, @"[^\d]", "");
                string number = new string(Message.ToPhone.Telephone.Where(char.IsDigit).ToArray());
                Debug.WriteLine("formatted Number = " + number);
                Debug.WriteLine("sending to SMS ...");
                Debug.WriteLine(number + "@" + Provider.SmsEmailDomain);

                //emailMessage.From.Add(new MailboxAddress(Message.FromUser.FirstName + " " + Message.FromUser.LastName, _smtpOptions.smtpFrom));
                //emailMessage.To.Add(new MailboxAddress(number + "@" + Provider.SmsEmailDomain));
                var smsBody = Message.MessageTemplate.SmsBody;

                foreach (var templateField in Message.MessageTemplate.MessageTemplateFields)
                {
                    if (fields.Keys.Contains(templateField.FieldName))
                    {
                        smsBody = smsBody.Replace(templateField.Pattern, fields[templateField.FieldName]);
                    }
                    else
                    {
                        smsBody = smsBody.Replace(templateField.Pattern, templateField.DefaultValue);
                    }
                }

                //Send Text through SendGrid
                var client = new SendGridClient(_sendGridOptions.ApiKey);
                var from   = new EmailAddress("*****@*****.**");

                string regexToFirst = Regex.Replace(Message.ToUser.FirstName, @"(@|&|‘|\(|\)|<|>|#|;|:|,|{|}|[|]|\^|%|\$|\!|\?|/)", "");
                string regexToLast  = Regex.Replace(Message.ToUser.LastName, @"(@|&|‘|\(|\)|<|>|#|;|:|,|{|}|[|]|\^|%|\$|\!|\?|/)", "");

                var subject = String.Format("Sent to {0} {1}", regexToFirst, regexToLast);

                var msg = new SendGridMessage()
                {
                    From             = from,
                    Subject          = subject,
                    PlainTextContent = smsBody,
                    HtmlContent      = smsBody
                };

                msg.AddTo(new EmailAddress(number + "@" + Provider.SmsEmailDomain));
                var response = await client.SendEmailAsync(msg);


                // Update SmsSent
                Message.SmsSent = DateTime.UtcNow;
                _dbContext.SaveChanges();
            }
            // return Ok("successful Operation");
        }
        public ActionResult CreateMemberRegistrationMessage(MemberRegistrationFormViewModel memberRegistrationMessage)
        {
            if (!ModelState.IsValid)
            {
                return(CurrentUmbracoPage());
            }

            ViewBag.MemberRegistration = memberRegistrationMessage;

            var appName             = WebConfigurationManager.AppSettings["sendgridAppName"];
            var contactEmailAddress = WebConfigurationManager.AppSettings["contactEmailAddress"];
            var sendgridUsername    = WebConfigurationManager.AppSettings["sendgridUsername"];
            var sendgridPassword    = WebConfigurationManager.AppSettings["sendgridPassword"];

            if (appName != null &&
                contactEmailAddress != null &&
                sendgridUsername != null &&
                sendgridPassword != null)
            {
                var SportsClubEmail = new SendGridMessage();
                SportsClubEmail.From = new System.Net.Mail.MailAddress(memberRegistrationMessage.EmailAddress);
                SportsClubEmail.AddTo(contactEmailAddress);
                SportsClubEmail.Subject = "Jäsenhakemus: " + memberRegistrationMessage.FirstName + " " + memberRegistrationMessage.LastName;

                SportsClubEmail.Html = BuildEmailToSportsClub(memberRegistrationMessage);


                var MemberEmail = new SendGridMessage();
                MemberEmail.From = new System.Net.Mail.MailAddress(MemberPersonInChargeEmailAddress);
                MemberEmail.AddTo(memberRegistrationMessage.EmailAddress);
                MemberEmail.Subject = "ReTee ry jäsenmaksu vuodelle " + DateTime.Now.Year;

                MemberEmail.Html = BuildMemberEmail(memberRegistrationMessage);

                var credentials  = new System.Net.NetworkCredential(sendgridUsername, sendgridPassword);
                var transportWeb = new Web(credentials);
                transportWeb.DeliverAsync(SportsClubEmail);
                transportWeb.DeliverAsync(MemberEmail);

                // Lisätään jäsen rekisteriin
                try {
                    var memberService = Services.MemberService;
                    var member        = memberService.CreateMemberWithIdentity(memberRegistrationMessage.EmailAddress, memberRegistrationMessage.EmailAddress, (memberRegistrationMessage.LastName + " " + memberRegistrationMessage.FirstName), "ReTeeMember");
                    member.SetValue("firstName", memberRegistrationMessage.FirstName);
                    member.SetValue("lastName", memberRegistrationMessage.LastName);
                    member.SetValue("phoneNumber", memberRegistrationMessage.PhoneNumber);
                    member.SetValue("birthDate", DateTime.Parse(memberRegistrationMessage.DateOfBirth));
                    member.SetValue("streetAddress", memberRegistrationMessage.StreetAddress);
                    member.SetValue("postalCode", memberRegistrationMessage.PostalCode);
                    member.SetValue("postOffice", memberRegistrationMessage.City);
                    member.SetValue("memberType", "member");
                    member.SetValue("mainClub", memberRegistrationMessage.SupportMemberClub);
                    member.SetValue("pdgaLicenseNumber", memberRegistrationMessage.PDGALicenseNumber);

                    var dts = Services.DataTypeService;

                    // Get an instance of the status editor
                    var ReTeeMemberTypesDataType = dts.GetDataTypeDefinitionByName("ReTee Member Type");
                    var ReTeeMemberTypes         = dts.GetPreValuesCollectionByDataTypeId(ReTeeMemberTypesDataType.Id).PreValuesAsDictionary;

                    switch (memberRegistrationMessage.MemberType)
                    {
                    case "member":
                        member.SetValue("memberType", ReTeeMemberTypes["0"].Id);
                        break;

                    case "junior":
                        member.SetValue("memberType", ReTeeMemberTypes["0"].Id);
                        break;

                    case "supporter":
                        member.SetValue("memberType", ReTeeMemberTypes["2"].Id);
                        break;

                    case "supportmember":
                        member.SetValue("memberType", ReTeeMemberTypes["1"].Id);
                        break;
                    }

                    memberService.Save(member);
                }
                catch (Exception ex)
                {
                    throw ex.InnerException;
                }

                //memberService.SavePassword(member, model.Password);
            }

            return(CurrentUmbracoPage());
        }
示例#29
0
        public async Task <int> SendPrizesDiplomaMails()
        {
            var diplomasPath = Path.Combine(MFiles.PublicPath, "diplomas/prizes");

            _participantsRepo.ChainQueryable(q => q
                                             .Include(p => p.User)
                                             // .Include(p => p.ProjectParticipants).ThenInclude(pp => pp.Project)
                                             .Where(p => p.Projects.Any(pp => pp.ScoreProject > 0))
                                             );
            _projectsRepo.ChainQueryable(q => q
                                         .Include(p => p.Participants)
                                         .ThenInclude(part => part.User)
                                         );

            var subject = "InfoEducație - Diplomă premiu";
            var message =
                "Salut {{NAME}}, <br/><br/> Atașat găsești diploma cu premiul în format pdf. <br/>Pentru orice nelămurire/problemă poți scrie pe Discord pe channelul #general<br/><br/>Mulțumim, <br/> Echipa InfoEducație";
            int c = 0;

            var cats = await _categoriesRepo.GetAll();

            var mailClient = new SendGridClient(_sendgridConfig.Key);

            foreach (var cat in cats)
            {
                var projects = await _projectsRepo.Queryable.Where(p => p.Category == cat)
                               .OrderByDescending(p => p.ScoreProject + p.ScoreOpen).Take(5).ToListAsync();

                for (int i = 0; i < projects.Count; i++)
                {
                    var project = projects[i];
                    var prize   = i < 3 ? new String('I', i + 1) : "M";
                    foreach (var participant in project.Participants)
                    {
                        // if ((participant.SentMails & SentMailsState.PrizeDiplomaEmailSent) != 0)
                        // {
                        // _logger.LogWarning($"mail diploma already send: '{subject}' to '{participant.User.Email}'");
                        // continue;
                        // }
                        _logger.LogWarning($"Sending email with SendGrid: '{subject}' to '{participant.User.Email}'");

                        var diplomaPath = Path.Combine(diplomasPath, $"{cat.Slug}-{prize}-{participant.Id}.pdf");
                        var bytes       = await File.ReadAllBytesAsync(diplomaPath);

                        var base64String = Convert.ToBase64String(bytes);
                        var msgText      = message.Replace("{{NAME}}", participant.FirstName);
                        var msg          = new SendGridMessage
                        {
                            From = new EmailAddress(_sendgridConfig.DefaultSenderAddress,
                                                    _sendgridConfig.DefaultSenderName),
                            Subject          = subject,
                            PlainTextContent = msgText,
                            HtmlContent      = msgText,
                        };
                        msg.AddTo(new EmailAddress(participant.User.Email, participant.User.FullName));

                        msg.AddAttachment(new Attachment
                        {
                            Filename = "diploma-premiu.pdf", Disposition = "attachment", Type = "application/pdf",
                            Content  = base64String
                        });
                        msg.SetClickTracking(true, true);
                        var response = await mailClient.SendEmailAsync(msg);

                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            participant.SentMails |= SentMailsState.PrizeDiplomaEmailSent;
                            await _participantsRepo.SaveChanges();

                            c++;
                        }
                    }
                }
            }

            return(c);
        }
        public ActionResult Asignar([Bind(Include = "ID,NUMERO_SERIE,FECHA_COMPRA,INICIO_SERVICIO,FECHA_INGRESO,FABRICANTE,PRECIO,DESCRIPCION,EXENTO,PRESTABLE,TIPO_CAPITAL,INGRESADO_POR,NUMERO_DOCUMENTO,NUMERO_LOTE,TIPO_TRANSACCIONID,ESTADO_ACTIVOID,TIPO_ACTIVOID,COMENTARIO,DESECHADO,MODELO,V_EMPLEADOSIDEMPLEADO,V_ESTACIONID,V_ANFITRIONAID,V_PROVEEDORIDPROVEEDOR,V_MONEDAID,CENTRO_DE_COSTOId,PLACA,ESTADO_PRESTADO")] ACTIVO aCTIVO)
        {
            var original = db.ACTIVOS.Find(aCTIVO.ID);

            if (aCTIVO.DESECHADO)
            {
                return(RedirectToAction("Index"));
            }

            if (original != null)
            {
                original.INICIO_SERVICIO = aCTIVO.INICIO_SERVICIO;
                original.ESTADO_ACTIVOID = aCTIVO.ESTADO_ACTIVOID;
                // si no se cambio el comentario, dejar el original
                original.COMENTARIO = aCTIVO.COMENTARIO == null ? original.COMENTARIO : aCTIVO.COMENTARIO;
                // Si el activo se pone como asignado, agregar id de empleado encargado, id de estacion de epleado y centro de costo
                int id_estado_asignado = db.ESTADOS_ACTIVOS.Where(ea => ea.NOMBRE.Equals("Asignado")).ToList()[0].ID; // Se busca el identificador del estado Asignado
                if (aCTIVO.ESTADO_ACTIVOID == id_estado_asignado)
                {
                    original.V_EMPLEADOSIDEMPLEADO = aCTIVO.V_EMPLEADOSIDEMPLEADO;
                    // Al activo se le asigna la estacion del empleado encargado, para que siempre este correcta y no dependa de la correctitud del filtro de empleados por estacion.
                    original.V_ESTACIONID      = (db.V_EMPLEADOS.ToList().Where(ea => ea.IDEMPLEADO == aCTIVO.V_EMPLEADOSIDEMPLEADO)).ToList()[0].ESTACION_ID;
                    original.CENTRO_DE_COSTOId = aCTIVO.CENTRO_DE_COSTOId;

                    var empleado = db.V_EMPLEADOS.Find(aCTIVO.V_EMPLEADOSIDEMPLEADO);

                    if (empleado.EMAIL.Contains("@"))
                    {
                        var mensaje_correo = new SendGridMessage();
                        mensaje_correo.From = new System.Net.Mail.MailAddress("*****@*****.**", "Admin"); // CAMBIAR CON EL CORREO DESDE EL QUE SE VAN A ENVIAR LOS MENSAJES
                        List <String> destinatarios = new List <string>
                        {
                            @"" + empleado.NOMBRE + " <" + empleado.EMAIL + ">"
                            //@"Jose Urena <*****@*****.**>" // PARA ESTABLECER EL CORREO DONDE SE ENVIA LA INFORMACION, ELIMINAR ESTA LINEA Y DESCOMENTAR LA LINEA SUPERIOR.
                        };

                        mensaje_correo.AddTo(destinatarios);
                        mensaje_correo.Subject = "Activo asignado a su cuenta de OET.";
                        mensaje_correo.Html   += "<h2>La OET le informa</h2><br />";
                        mensaje_correo.Html   += "A través de este correo la OET desea informarle que un nuevo activo ha sido asignado a su nombre." + "<br />" + "<br />";
                        mensaje_correo.Html   += "A continuación se enlistan las características del activo: " + "<br />" + "<br />" + "<br />";
                        mensaje_correo.Html   += "Descripción: " + original.DESCRIPCION + "<br />" + "<br />";
                        mensaje_correo.Html   += "Número de placa: " + original.PLACA + "<br />" + "<br />";
                        mensaje_correo.Html   += "Inicio del servicio: " + original.INICIO_SERVICIO + "<br />" + "<br />";
                        mensaje_correo.Html   += "Comentarios: " + original.COMENTARIO + "<br />";

                        var credentials  = new NetworkCredential(ConfigurationManager.AppSettings["mailAccount"], ConfigurationManager.AppSettings["mailPassword"]);
                        var transportWeb = new SendGrid.Web(credentials);
                        transportWeb.DeliverAsync(mensaje_correo);
                    }
                }
                else
                {
                    // Si no se asigna entonces se le quita la estacion, el centro de costo y el empleado responsable
                    original.V_ESTACIONID          = "";
                    original.CENTRO_DE_COSTOId     = null;
                    original.V_EMPLEADOSIDEMPLEADO = "";
                }

                db.SaveChanges();

                var consulta_proveedor   = db.V_PROVEEDOR.ToList().Where(ea => ea.IDPROVEEDOR == original.V_PROVEEDORIDPROVEEDOR);
                var proveedor            = consulta_proveedor.ToList()[0].NOMBRE;
                var consulta_anfitriona  = db.V_ANFITRIONA.ToList().Where(ea => ea.ID == original.V_ANFITRIONAID);
                var anfitriona           = consulta_anfitriona.ToList()[0].NOMBRE;
                var consulta_transaccion = db.TIPOS_TRANSACCIONES.ToList().Where(ea => ea.ID == original.TIPO_TRANSACCIONID);
                var transaccion          = consulta_transaccion.ToList()[0].NOMBRE;

                // Si el activo se pone como asignado, se agrega id del responsable a la bitacora.
                if (aCTIVO.ESTADO_ACTIVOID == id_estado_asignado)
                {
                    controladora_transaccion.CreateWithResponsible(User.Identity.GetUserName(), original.ESTADOS_ACTIVOS.NOMBRE, original.descripcion(proveedor, transaccion, anfitriona), original.ID, aCTIVO.V_EMPLEADOSIDEMPLEADO);
                }
                else
                {
                    controladora_transaccion.Create(User.Identity.GetUserName(), original.ESTADOS_ACTIVOS.NOMBRE, original.descripcion(proveedor, transaccion, anfitriona), original.ID);
                }

                return(RedirectToAction("Index"));
            }
            ViewBag.V_EMPLEADOSIDEMPLEADO = new SelectList(db.V_EMPLEADOS.Where(emp => emp.ESTADO.Equals(1) && emp.EMAIL.Contains("@")).OrderBy(emp => emp.NOMBRE), "IDEMPLEADO", "NOMBRE", aCTIVO.V_EMPLEADOSIDEMPLEADO);
            ViewBag.ESTADO_ACTIVOID       = new SelectList(db.ESTADOS_ACTIVOS.OrderBy(ea => ea.NOMBRE), "ID", "NOMBRE", aCTIVO.ESTADO_ACTIVOID);
            ViewBag.V_ESTACIONID          = new SelectList(db.V_ESTACION.OrderBy(e => e.NOMBRE), "ID", "NOMBRE", aCTIVO.V_ESTACIONID);
            ViewBag.CENTRO_DE_COSTOId     = new SelectList(db.CENTROS_DE_COSTOS, "ID", "NOMBRE", aCTIVO.CENTRO_DE_COSTOId);
            return(View(aCTIVO));
        }