private static void SendEmailViaMailgun(MailMessage emailMsg) { bool valid = true; string status = ""; var sendingDomain = System.Configuration.ConfigurationManager.AppSettings["MailgunSendingDomainName"]; var apiKey = System.Configuration.ConfigurationManager.AppSettings["MailgunSecretAPIKey"]; if (string.IsNullOrWhiteSpace(sendingDomain)) { //no service api LoggingHelper.DoTrace(2, "***** EmailManager.SendEmailViaMailgun - no email service has been configured"); return; } var apiKeyEncoded = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes("api" + ":" + apiKey)); var url = "https://api.mailgun.net/v3/" + sendingDomain + "/messages"; // var email = new MailgunEmail() { BodyHtml = emailMsg.Body, From = emailMsg.From.Address, BCC = emailMsg.Bcc.ToString(), Subject = emailMsg.Subject }; email.To.Add(emailMsg.To.ToString()); email.CC.Add(emailMsg.CC.ToString()); if (emailMsg.Attachments != null && emailMsg.Attachments.Count > 0) { //need to be able to handle attachments } var parameters = email.GetMultipartFormDataContent(); //var parameters2 = email.GetContent2(); //var client2 = new MailgunClient( sendingDomain, apiKey ); try { using (var client = new HttpClient()) { System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", apiKeyEncoded); var result = client.PostAsync(url, parameters).Result; //var result = client.PostAsync( url, parameters2 ).Result; valid = result.IsSuccessStatusCode; status = valid ? result.Content.ReadAsStringAsync().Result : result.ReasonPhrase; } if (!valid) { LoggingHelper.DoTrace(2, "***** EmailManager.SendEmailViaMailgun - error on send: " + status); } } catch (Exception ex) { LoggingHelper.LogError(ex, "SendEmailViaMailgun"); } }
public async Task <bool> Send(MailgunEmail email) { HttpRequestMessage m = MakeMailgunMessage(email); HttpResponseMessage r = await Client.SendAsync(m); if (r.IsSuccessStatusCode) { Logger.Log("Sent an email successfullt"); return(true); } else { Logger.Log($"Encountered a failure when sending email: {r.ReasonPhrase}"); return(false); } }
public async Task TestSendEmail() { MailgunService MSS = new MailgunService(logger); MailgunEmail m = new MailgunEmail() { To = new List <string>() { "*****@*****.**" }, From = "ESk8BST <*****@*****.**>", Subject = "This is a Test Email", Body = "Testing from Test", IsTest = true }; bool success = await MSS.Send(m); Assert.True(success); }
// METHODS public HttpRequestMessage MakeMailgunMessage(MailgunEmail e) { UriBuilder ub = new UriBuilder($"https://api.mailgun.net/v3/{DOMAIN}/messages"); HttpRequestMessage m = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = ub.Uri, Content = new FormUrlEncodedContent(new Dictionary <string, string>() { { "from", e.From }, { "to", String.Join(",", e.To) }, { "subject", e.Subject }, { "text", e.Body }, { "o:testmode", e.IsTest ? "true" : "false" }, }), }; return(m); }
/// <summary> /// The endpoint hit when a user submits their email to esk8bst /// This schedules a Mailgun Email that will include a Confirm Subscribe Link /// </summary> /// <param name="request"></param> /// <param name="context"></param> /// <returns></returns> public async Task <APIGatewayProxyResponse> Subscribe(APIGatewayProxyRequest request, ILambdaContext context) { var logger = new Esk8LambdaLogger(context.Logger); logger.Log("Subscribe endpoint reached"); if (request.HttpMethod != HttpMethod.Post.Method) { return(new APIGatewayProxyResponse() { StatusCode = (int)HttpStatusCode.MethodNotAllowed }); } ; string postbody = request.Body; PostedSubscribeObject pso = null; string confirmkey = ""; try { JObject jobj = JObject.Parse(postbody); pso = PostedSubscribeObject.FromJson(jobj); if (pso.Email.Contains("@") && pso.Matches.Count > 0) // we can proceed { FirestoreService FSS = new FirestoreService(logger); if (await FSS.CheckIsPreconfirmed(pso.Email)) { // Immediately subscribe the user, they've already been here. await FSS.UpsertSubscriber(pso); return(new APIGatewayProxyResponse() { StatusCode = (int)HttpStatusCode.Created, Headers = new Dictionary <string, string> { { "Content-Type", "text/plain" } }, Body = "Alright! You've been confirmed as interested in receiving updates from https://esk8bst.com", }); } else { // Not pre-confirmed, send an opt-in email. string encryptionKey = Environment.GetEnvironmentVariable("ESK8BST_ENCRYPTION_KEY"); confirmkey = EncryptorService.CreateConfirmKey(pso.ToJson().ToString(), encryptionKey); } } } catch (Exception e) { logger.Log($"Tried to parse a malformed subscriber json: {e.Message}"); return(new APIGatewayProxyResponse() { StatusCode = (int)HttpStatusCode.InternalServerError, Headers = new Dictionary <string, string> { { "Content-Type", "text/plain" } }, Body = "Failed to parse json properly", }); } if (String.IsNullOrWhiteSpace(confirmkey)) { return(new APIGatewayProxyResponse() { StatusCode = (int)HttpStatusCode.InternalServerError, Body = "Failed to parse json properly - no email found", Headers = new Dictionary <string, string> { { "Content-Type", "text/plain" } }, }); } MailgunService MSS = new MailgunService(logger); MailgunEmail m = new MailgunEmail() { To = new List <string> { pso.Email }, From = MailgunService.POSTMASTER, Subject = "Esk8Bst Notification Opt In Request", Body = "" + "Someone has registered you as being interested in receiving notifications about new electric skateboard postings from https://esk8bst.com.\n\n" + "If this was you, please click the link below to confirm your email. If this was not you, or you no longer wish to receive emails from us, then ignore this message.\n\n" + $"https://1lol87xzbj.execute-api.us-east-2.amazonaws.com/Prod/confirm?confirmkey={confirmkey}", }; bool success = await MSS.Send(m); if (!success) { return(new APIGatewayProxyResponse() { StatusCode = (int)HttpStatusCode.InternalServerError, Body = "Failed to send email to recipent", Headers = new Dictionary <string, string> { { "Content-Type", "text/plain" } }, }); } //An email has been sent to the address specified confirming your subscription var response = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = "An email has been sent to the address specified confirming your subscription", Headers = new Dictionary <string, string> { { "Content-Type", "text/plain" } }, }; return(response); }
public async Task <IActionResult> Register([FromBody] UserEditViewModel user) { //if (!(await _authorizationService.AuthorizeAsync (this.User, Tuple.Create (user.Roles, new string[] { }), Authorization.Policies.AssignAllowedRolesPolicy)).Succeeded) // return new ChallengeResult (); try { var viewAllUsersPolicy = await _authorizationService.AuthorizeAsync(this.User, Authorization.Policies.ViewAllUsersPolicy); bool isGroupAdmin = await this.CanAdminGroups(); if (!viewAllUsersPolicy.Succeeded && !isGroupAdmin) { return(new ChallengeResult()); } if (ModelState.IsValid) { if (user == null) { return(BadRequest($"{nameof(user)} cannot be null")); } // force user type to be 'user' to avoid any other type being set through here user.Roles = new string[] { "user" }; TraisiUser appUser = Mapper.Map <TraisiUser> (user); var result = await _accountManager.CreateUserAsync(appUser, user.Roles, user.NewPassword); if (result.Item1) { MailgunEmail regEmail = new MailgunEmail() { Receipient = appUser.Email, Subject = _localizer["RegistrationEmailSubject"], Template = "RegistrationEmail", TemplateReplacements = new Dictionary <string, string> () { { "user_name", appUser.UserName }, { "password", user.NewPassword } } }; this._emailer.SendEmail(regEmail); /*var (emailRegSuccess, errorMessage) = await this._emailer.SendEmailAsync(regEmail); * if (!emailRegSuccess) * { * AddErrors(new string[] { errorMessage }); * }*/ UserViewModel userVM = await GetUserViewModelHelper(appUser.Id); return(CreatedAtAction(GetUserByIdActionName, new { id = userVM.Id }, userVM)); } AddErrors(result.Item2); } return(BadRequest(ModelState)); } catch (System.Exception ex) { return(BadRequest("User Creation Failed: " + ex.Message)); } }
public MailgunEmail MakeEmail(Subscriber s, List <LambdaMatch> lms) { // remember to include an Unsubscribe Link int itemCount = lms.Sum(x => x.Posts.Count); string subjectSingle = "1 new item that matched your criteria has been posted"; string subjectPlural = $"{itemCount} new items that matched your critiera have been posted"; MailgunEmail m = new MailgunEmail() { From = POSTMASTER, To = { s.DocumentId }, Subject = itemCount == 1 ? subjectSingle : subjectPlural }; string body = (itemCount == 1 ? subjectSingle : subjectPlural) + "\n\n"; string BSTtoSTring(BST bst) { switch (bst) { case BST.BST: return("buy, sell, or trade"); case BST.BUY: return("buy"); case BST.SELL: return("sell"); case BST.TRADE: return("trade"); case BST.NONE: return("none"); } return(""); } foreach (LambdaMatch lm in lms) { // Assemble Subheader string WTStr = $"People looking to {BSTtoSTring(lm.FbMatch.BST)}"; string fromStr = "products from " + (lm.FbMatch.Companies.Any() ? $"companies [{String.Join(", ", lm.FbMatch.Companies)}]" : "any company"); Currency c = CurrencyMap.CurrencyDict[lm.FbMatch.Currency]; string priceStr = lm.FbMatch.Price.HasValue ? $"for {(lm.FbMatch.BST == BST.BUY ? "more than or equal to " : "less than or equal to")} " + $"{c.symbol}{lm.FbMatch.Price.Value} {c.Code}" : "at any price"; string matchBody = $"{WTStr} {fromStr} {priceStr}:\n"; // Assemble Items foreach (BSTComment comment in lm.Posts) { string seller = comment.Seller; string comp = comment.Company; string product = comment.Product == "?" ? "<product unknown>" : comment.Product; string url = comment.Url; Currency c2 = CurrencyMap.CurrencyDict[comment.Currency]; string pstr = comment.Price == 0 ? "<price not posted>" : $"{c2.symbol}{comment.Price} {c2.Code}"; string commentStr = $"{comp} {product} by {seller} for {pstr}\n{url}\n\n"; matchBody += commentStr; } body += matchBody; } // make unsubscribe link string encryptionKey = Environment.GetEnvironmentVariable("ESK8BST_ENCRYPTION_KEY"); string encryptedPayload = EncryptorService.Base64Encode(s.DocumentId); //AESThenHMAC.SimpleEncryptWithPassword(s.DocumentId.ToLower(), encryptionKey); string link = $"https://1lol87xzbj.execute-api.us-east-2.amazonaws.com/Prod/unsubscribe?confirmkey={encryptedPayload}"; string unsubtext = $"Unsubscribe: {link}"; body += $"\n\n\n\n {unsubtext}"; m.Body = body; return(m); }