Files
gameauthapi/Services/EmailService.cs
T

38 lines
1.4 KiB
C#

using System.Net;
using System.Net.Mail;
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
namespace GameAuthApi.Services;
public class EmailService
{
private readonly IConfiguration _config;
public EmailService(IConfiguration config) => _config = config;
public virtual async Task SendPasswordResetCodeAsync(string recipient, string code)
{
var host = _config["Email:SmtpHost"];
var sender = _config["Email:Sender"];
if (string.IsNullOrWhiteSpace(host) || string.IsNullOrWhiteSpace(sender))
throw new InvalidOperationException("SMTP email delivery is not configured.");
using var message = new MailMessage(sender, recipient)
{
Subject = "Your MedMind password reset code",
Body = $"Your MedMind verification code is {code}. It expires in 15 minutes. If you did not request this, you can ignore this email.",
IsBodyHtml = false
};
using var client = new SmtpClient(host, int.TryParse(_config["Email:SmtpPort"], out var port) ? port : 587)
{
EnableSsl = !bool.TryParse(_config["Email:UseTls"], out var tls) || tls
};
var username = _config["Email:Username"];
if (!string.IsNullOrWhiteSpace(username))
client.Credentials = new NetworkCredential(username, _config["Email:Password"]);
await client.SendMailAsync(message);
}
}