ASP.NET Core Web API:如何发送含账号密码的无链接令牌注册通知邮件
修改ASP.NET Core 6 Web API注册邮件为账号信息通知的方案
1. 创建新的账号信息邮件模板
在StaticFiles/Html目录下新建RegisterInfo.html,内容如下:
<h3>账号注册成功通知</h3> <p>您好,您的账号已成功创建,以下是您的账号信息:</p> <p>用户名:<strong>**username**</strong></p> <p>密码:<strong>**password**</strong></p> <p>请妥善保管您的账号信息,避免泄露。</p>
2. 修改邮件内容构建方法
替换原有的GetEmailBody方法(或新增专门的方法),用于替换模板中的用户名和密码占位符:
public static async Task<string> GetRegistrationInfoEmailBody(string emailTempPath, string username, string password) { var templateContent = await File.ReadAllTextAsync(Path.Combine(Directory.GetCurrentDirectory(), emailTempPath)); return templateContent .Replace("**username**", username) .Replace("**password**", password); }
3. 简化Register方法,移除验证令牌相关逻辑
修改Register方法,删除令牌生成、角色获取等无用代码,替换为账号信息邮件的生成逻辑:
public async Task<Response<string>> Register(RegisterUserDto model) { var user = _mapper.Map<AppUser>(model); user.IsActive = true; var response = new Response<string>(); using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _userManager.AddToRoleAsync(user, UserRoles.Customer); // 生成账号信息邮件内容 var mailBody = await EmailBodyBuilder.GetRegistrationInfoEmailBody( emailTempPath: "StaticFiles/Html/RegisterInfo.html", username: model.UserName, // 或使用user.UserName,根据实际字段调整 password: model.Password ); var mailRequest = new MailRequest() { Subject = "账号注册成功通知", Body = mailBody, ToEmail = model.Email }; bool emailResult = await _mailService.SendEmailAsync(mailRequest); if (emailResult) { _logger.Information("邮件发送成功"); var customer = new Customer { AppUser = user }; await _unitOfWork.Customers.InsertAsync(customer); await _unitOfWork.Save(); response.StatusCode = (int)HttpStatusCode.Created; response.Succeeded = true; response.Data = user.Id; response.Message = "用户创建成功!请查看邮箱获取账号信息。"; transaction.Complete(); return response; } _logger.Information("邮件服务发送失败"); transaction.Dispose(); response.StatusCode = (int)HttpStatusCode.BadRequest; response.Succeeded = false; response.Message = "注册失败,请重试"; return response; } response.Message = GetErrors(result); response.StatusCode = (int)HttpStatusCode.BadRequest; response.Succeeded = false; transaction.Complete(); return response; }; }
4. 清理无用代码(可选)
如果原有的GetEmailBody方法(处理验证链接的)不再使用,可以直接删除,减少冗余。
内容的提问来源于stack exchange,提问作者Ayobamilaye
相关产品推荐
相关产品推荐

