1.首先在appsettings.json
文件中添加 SMTP 配置信息
"SmtpSettings": {
"Server": "smtp.example.com",
"Port": 587,
"Username": "your_email@example.com",
"Password": "your_email_password"
}
2.创建发送邮件的服务
- 创建一个
EmailService
类,封装发送邮件的逻辑
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
namespace App.Common.SMTP
{
public class EmailService
{
private readonly SmtpSettings _smtpSettings;
public EmailService(IOptions<SmtpSettings> smtpSettings)
{
_smtpSettings = smtpSettings.Value;
}
public async Task SendEmailAsync(string email, string subject, string htmlMessage)
{
var mailMessage = new MailMessage
{
From = new MailAddress(_smtpSettings.Username),
Subject = subject,
Body = htmlMessage,
IsBodyHtml = true
};
mailMessage.To.Add(new MailAddress(email));
using var smtpClient = new SmtpClient(_smtpSettings.Server, _smtpSettings.Port);
smtpClient.Credentials = new NetworkCredential(_smtpSettings.Username, _smtpSettings.Password);
smtpClient.EnableSsl = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
await smtpClient.SendMailAsync(mailMessage);
}
}
}
- 创建一个用于储存SMTP设置的模型类
SmtpSetting.cs
public class SmtpSettings
{
public string Server { get; set; } = null!;
public int Port { get; set; }
public string Username { get; set; } = null!;
public string Password { get; set; } = null!;
}
- 在
Program.cs
文件中,添加 SMTP 设置的配置:
builder.Services.Configure<SmtpSettings>(builder.Configuration.GetSection("SmtpSettings"));
3.创建一个控制器用于调用EmailService
namespace App.WebAPI.Controllers
{
[Route("[controller]/[Action]")]
[ApiController]
public class EmailController : ControllerBase
{
private readonly EmailService _emailService;
private readonly IUserInfoService _iUserInfoService;
public EmailController(EmailService emailService, IUserInfoService iUserInfoService)
{
_emailService = emailService;
_iUserInfoService = iUserInfoService;
}
[HttpPost]
public async Task<ApiResult> SendEmailValidateCode(EmailLoginSendRequestInput req)
{
if (string.IsNullOrWhiteSpace(req.Email))
{
return ApiResultHelper.Error("邮箱不能为空");
}
var user = await _iUserInfoService.FindAsync(c => c.Email == req.Email);
if (user == null)
{
return ApiResultHelper.Error("邮箱不存在");
}
// 生成验证码
var validateCode = new Random().Next(100000, 999999).ToString();
string emailTemplate = @"
<!DOCTYPE html>
<html lang=""en"">
<head>
<meta charset=""UTF-8"">
<meta name=""viewport""
content=""width=device-width, initial-scale=1.0"">
<title>Document</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
margin: 0;
padding: 0;
}
.container {
max-width: 600px;
margin: 50px auto;
background-color: #ffffff;
padding: 30px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h2 {
color: #333333;
text-align: center;
margin-top: 0;
}
p {
color: #666666;
line-height: 1.6;
}
.code {
font-size: 24px;
font-weight: bold;
color: #007BFF;
margin: 20px 0;
text-align: center;
}
.notice {
color: #999999;
text-align: center;
}
.email {
color: #007BFF;
}
</style>
</head>
<body>
<div class=""container"">
<h2>欢迎使用邮箱登录验证</h2>
<p>您好,<span class=""email"">{{Email}}</span></p>
<p>感谢您选择使用我们的服务。以下是您的邮箱登录验证码,请查收:</p>
<div class=""code"">
<span id=""validateCode"">{{VALIDATE_CODE}}</span>
</div>
<p class=""notice"">请注意,此验证码有效期为5分钟,请在有效期内完成操作。为了保障您的账户安全,请勿向任何人透露此验证码。</p>
<p>如果您没有请求此验证码,请忽略此邮件,可能是有人误输入了您的邮箱地址。</p>
<p>祝您使用愉快!</p>
<p>此致<br>梦博客团队</p>
</div>
</body>
</html>";
// 发送验证码邮件
emailTemplate = emailTemplate.Replace("{{VALIDATE_CODE}}", validateCode);
emailTemplate = emailTemplate.Replace("{{Email}}", req.Email);
var subject = "邮箱登录验证码";
var message = emailTemplate;
MemoryHelper.SetMemory(validateCode, validateCode, 5);
await _emailService.SendEmailAsync(req.Email, subject, message);
return ApiResultHelper.Success("验证码已发送", true);
}
}
}
最后测试接口是否正常请求