75 lines
2.6 KiB
C#
75 lines
2.6 KiB
C#
using IRaCIS.Core.Domain.Interfaces;
|
||
using IRaCIS.Core.Domain.Models;
|
||
using MailKit.Security;
|
||
using MimeKit;
|
||
using System;
|
||
using System.Threading.Tasks;
|
||
|
||
namespace IRaCIS.Application.Services
|
||
{
|
||
public interface IMailVerificationService
|
||
{
|
||
Task SendMail(Guid userId, string userName, string emailAddress, int verificationCode);
|
||
}
|
||
|
||
public class MailVerificationService: IMailVerificationService
|
||
{
|
||
private readonly IVerificationCodeRepository _verificationCodeRepository;
|
||
|
||
|
||
public MailVerificationService(IVerificationCodeRepository verificationCodeRepository)
|
||
{
|
||
_verificationCodeRepository = verificationCodeRepository;
|
||
|
||
}
|
||
|
||
public async Task SendMail(Guid userId, string userName, string emailAddress, int verificationCode)
|
||
{
|
||
|
||
|
||
var messageToSend = new MimeMessage();
|
||
//发件地址
|
||
messageToSend.From.Add(new MailboxAddress("GRR", "iracis_grr@163.com"));
|
||
//收件地址
|
||
messageToSend.To.Add(new MailboxAddress(userName, emailAddress));
|
||
//主题
|
||
messageToSend.Subject = "Reset PassWord (Verification Code)";
|
||
|
||
messageToSend.Body = new TextPart("plain")
|
||
{
|
||
Text = $@"Hey {userName},您正在通过邮箱重置密码,本次的验证码是:{verificationCode},3分钟内有效,如若不是本人操作,请忽略!
|
||
|
||
-- GRR"
|
||
};
|
||
using (var smtp = new MailKit.Net.Smtp.SmtpClient())
|
||
{
|
||
smtp.MessageSent += (sender, args) =>
|
||
{
|
||
// args.Response
|
||
var code = verificationCode.ToString();
|
||
_verificationCodeRepository.Add(new VerificationCode()
|
||
{
|
||
CodeType = 0,
|
||
HasSend = true,
|
||
Code = code,
|
||
UserId = userId,
|
||
ExpirationTime = DateTime.Now.AddMinutes(3)
|
||
});
|
||
_verificationCodeRepository.SaveChanges();
|
||
|
||
};
|
||
|
||
smtp.ServerCertificateValidationCallback = (s, c, h, e) => true;
|
||
|
||
await smtp.ConnectAsync("smtp.163.com", 25, SecureSocketOptions.StartTls);
|
||
|
||
await smtp.AuthenticateAsync("iracis_grr@163.com", "XLWVQKZAEKLDWOAH");
|
||
|
||
await smtp.SendAsync(messageToSend);
|
||
|
||
await smtp.DisconnectAsync(true);
|
||
|
||
}
|
||
}
|
||
}
|
||
} |