50 lines
1.8 KiB
C#
50 lines
1.8 KiB
C#
using Apimanager_backend.Exceptions;
|
|
using System.Net;
|
|
using System.Net.Mail;
|
|
|
|
namespace Apimanager_backend.Services
|
|
{
|
|
public class EmailService:IEmailService
|
|
{
|
|
private readonly IConfiguration _configuration;
|
|
public EmailService(IConfiguration configuration)
|
|
{
|
|
_configuration = configuration;
|
|
SmtpHost = _configuration["EmailSettings:Server"];
|
|
Port = int.Parse(_configuration["EmailSettings:Port"]);
|
|
Username = _configuration["EmailSettings:Username"];
|
|
Password = _configuration["EmailSettings:Password"];
|
|
EnableSSL = bool.Parse(_configuration["EmailSettings:Ssl"]);
|
|
}
|
|
private string SmtpHost { get; set; }
|
|
private int Port { get; set; }
|
|
public bool EnableSSL { get; set; }
|
|
private string Username { get; set; }
|
|
private string Password { get; set; }
|
|
public async Task SendEmailAsync(string toEmail,string subject,string body)
|
|
{
|
|
try
|
|
{
|
|
using SmtpClient smtpClient = new SmtpClient(SmtpHost, Port)
|
|
{
|
|
Credentials = new NetworkCredential(Username, Password),
|
|
EnableSsl = EnableSSL, //启用ssl
|
|
Timeout = 30000
|
|
};
|
|
using var emailMessage = new MailMessage
|
|
{
|
|
From = new MailAddress(Username),
|
|
Subject = subject,
|
|
Body = body,
|
|
IsBodyHtml = true
|
|
};
|
|
emailMessage.To.Add(toEmail);
|
|
await smtpClient.SendMailAsync(emailMessage);
|
|
}catch(Exception e)
|
|
{
|
|
throw new BaseException(5004,e.Message);
|
|
}
|
|
}
|
|
}
|
|
}
|