locked
How can I generate and use Gmail API to send email from Application for the login confirmation RRS feed

  • Question

  • User-1355965324 posted

    I want to include the email  confirmation from the user to activate their account in  to the application. Is it possible to generate Gmail API key to send the email . If so, Please can you let me know the steps

    Pol

    Sunday, May 24, 2020 10:26 PM

All replies

  • User711641945 posted

    Hi polachan,

    Did you use Identity in your asp.net core project.If so,please refer to the official document about email confirmation:

    https://docs.microsoft.com/en-us/aspnet/core/security/authentication/accconfirm?view=aspnetcore-3.1&tabs=visual-studio#register-confirm-email-and-reset-password

    Best Regards,

    Rena

    Monday, May 25, 2020 9:43 AM
  • User-1355965324 posted

    Rena

    I did the code in the following ways in my code. Still I cannot see any mail is  going for confirmation and then I tried to resend the email. Still the email is not coming using the sendgrid. Please can you ccheck my code anything wrong

    AppSetting.cs

     "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "AllowedHosts": "*",
      "SendGridKey": "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",
      "SendGridUser": "Library"
    }

    Register.cshtml.cs

    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);
    
                        await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                            $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
    

    Emailoptions.cs

    public class EmailOptions
        {
            public string SendGridKey { get; set; }
            public string SendGridUser { get; set; }
        }
    
     
    

    In startup.cs

    services.AddSingleton<IEmailSender, EmailSender>();
    services.Configure<EmailOptions>(Configuration);

    I created a class 

     public class EmailSender : IEmailSender
        {
            private readonly EmailOptions emailOptions;
            public EmailSender(IOptions<EmailOptions> options)
            {
                emailOptions = options.Value;
            }
            public Task SendEmailAsync(string email, string subject, string htmlMessage)
            {
                return Execute(emailOptions.SendGridKey, subject, htmlMessage, email);
            }
    
            private Task Execute(string sendGridKEy, string subject, string message, string email)
            {
                var client = new SendGridClient(sendGridKEy);
                var from = new EmailAddress("admin@libraryBooks.com", LibraryBooks");
                var to = new EmailAddress(email, "End User");
                var msg = MailHelper.CreateSingleEmail(from, to, subject, "", message);
                return client.SendEmailAsync(msg);
            }
           
        }

    Register.cshtml

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
    using System.Text.Encodings.Web;
    using System.Threading.Tasks;
    using LibraryBooks.DataAccess.Repository.IRepository;
    using LibraryBooks.Models;
    using LibraryBooks.Utility;
    using Microsoft.AspNetCore.Authentication;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.AspNetCore.Identity.UI.Services;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using Microsoft.AspNetCore.WebUtilities;
    using Microsoft.Extensions.Logging;
    
    namespace LibraryBooks.Areas.Identity.Pages.Account
    {
        [AllowAnonymous]
        public class RegisterModel : PageModel
        {
            private readonly SignInManager<IdentityUser> _signInManager;
            private readonly UserManager<IdentityUser> _userManager;
            private readonly ILogger<RegisterModel> _logger;
            private readonly IEmailSender _emailSender;
            private readonly RoleManager<IdentityRole> _roleManager;
            private readonly IUnitOfWork _unitOfWork;
    
            public RegisterModel(
                UserManager<IdentityUser> userManager,
                SignInManager<IdentityUser> signInManager,
                ILogger<RegisterModel> logger,
                IEmailSender emailSender,
                 RoleManager<IdentityRole> roleManager,
                IUnitOfWork unitOfWork)
                
            {
                _userManager = userManager;
                _signInManager = signInManager;
                _logger = logger;
                _emailSender = emailSender;
                _roleManager = roleManager;
                _unitOfWork = unitOfWork;
            }
    
            [BindProperty]
            public InputModel Input { get; set; }
    
            public string ReturnUrl { get; set; }
    
            public IList<AuthenticationScheme> ExternalLogins { get; set; }
    
            public class InputModel
            {
                [Required]
                [EmailAddress]
                [Display(Name = "Email")]
                public string Email { get; set; }
    
                [Required]
                [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
                [DataType(DataType.Password)]
                [Display(Name = "Password")]
                public string Password { get; set; }
    
                [DataType(DataType.Password)]
                [Display(Name = "Confirm password")]
                [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
                public string ConfirmPassword { get; set; }
                [Required]
                public string Name { get; set; }
                public string StreetAddress { get; set; }
                public string City { get; set; }
                public string State { get; set; }
                public string PostalCode { get; set; }
                public string PhoneNumber { get; set; }
                public int? CompanyId { get; set; }
                public string Role { get; set; }
                public IEnumerable<SelectListItem> CompanyList { get; set; }
                public IEnumerable<SelectListItem> RoleList { get; set; }
            }
    
            public async Task OnGetAsync(string returnUrl = null)
            {
                ReturnUrl = returnUrl;
                Input = new InputModel()
                {
                    CompanyList = _unitOfWork.Company.GetAll().Select(i => new SelectListItem
                    {
                        Text = i.Name,
                        Value = i.Id.ToString()
                    }),
                    RoleList = _roleManager.Roles.Where(u => u.Name != SD.Role_User_Indi).Select(x => x.Name).Select(i => new SelectListItem
                    {
                        Text = i,
                        Value = i
                    })
                };
                ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            }
    
            public async Task<IActionResult> OnPostAsync(string returnUrl = null)
            {
                returnUrl = returnUrl ?? Url.Content("~/");
                ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
                if (ModelState.IsValid)
                {
                    //var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };
                    var user = new ApplicationUser
                    {
                        UserName = Input.Email,
                        Email = Input.Email,
                        CompanyId = Input.CompanyId,
                        StreetAddress = Input.StreetAddress,
                        City = Input.City,
                        State = Input.State,
                        PostalCode = Input.PostalCode,
                        Name = Input.Name,
                        PhoneNumber = Input.PhoneNumber,
                        Role = Input.Role
                    };
                    var result = await _userManager.CreateAsync(user, Input.Password);
                    if (result.Succeeded)
                    {
                        _logger.LogInformation("User created a new account with password.");
                        if(!await _roleManager.RoleExistsAsync(SD.Role_Admin))
                        {
                            await _roleManager.CreateAsync(new IdentityRole(SD.Role_Admin));
                        }
                        if (!await _roleManager.RoleExistsAsync(SD.Role_Employee))
                        {
                            await _roleManager.CreateAsync(new IdentityRole(SD.Role_Employee));
                        }
                        if (!await _roleManager.RoleExistsAsync(SD.Role_User_Comp))
                        {
                            await _roleManager.CreateAsync(new IdentityRole(SD.Role_User_Comp));
                        }
                        if (!await _roleManager.RoleExistsAsync(SD.Role_User_Indi))
                        {
                            await _roleManager.CreateAsync(new IdentityRole(SD.Role_User_Indi));
                        }
                        await _userManager.AddToRoleAsync(user, SD.Role_Admin);
    
                        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);
    
                        await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                            $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
    
                        if (_userManager.Options.SignIn.RequireConfirmedAccount)
                        {
                            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();
            }
        }
    }
    

    Monday, May 25, 2020 2:51 PM