-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathEmailSender.cs
More file actions
52 lines (42 loc) · 1.66 KB
/
EmailSender.cs
File metadata and controls
52 lines (42 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System.Net;
using System.Net.Mail;
using Microsoft.AspNetCore.Identity.UI.Services;
namespace BudgetBoard.Utils;
public class EmailSender(IConfiguration configuration) : IEmailSender
{
public IConfiguration Configuration { get; } = configuration;
public async Task SendEmailAsync(string email, string subject, string htmlMessage)
{
var sender = Configuration.GetValue<string>("EMAIL_SENDER");
if (string.IsNullOrEmpty(sender))
{
throw new ArgumentNullException(nameof(sender));
}
// Some SMTP servers use a username separate from the sender email. If not set, use the sender email as username.
var senderUsername = Configuration.GetValue<string>("EMAIL_SENDER_USERNAME");
if (string.IsNullOrEmpty(senderUsername))
{
senderUsername = sender;
}
var senderPassword = Configuration.GetValue<string>("EMAIL_SENDER_PASSWORD");
var smtpHost = Configuration.GetValue<string>("EMAIL_SMTP_HOST");
if (string.IsNullOrEmpty(smtpHost))
{
throw new ArgumentNullException(nameof(smtpHost));
}
var smtpPort = Configuration.GetValue<int?>("EMAIL_SMTP_PORT") ?? 587;
using MailMessage mm = new(sender, email);
mm.Subject = subject;
mm.Body = htmlMessage;
mm.IsBodyHtml = true;
using SmtpClient smtp = new()
{
Host = smtpHost,
EnableSsl = true,
UseDefaultCredentials = false,
Port = smtpPort,
Credentials = new NetworkCredential(senderUsername, senderPassword),
};
await smtp.SendMailAsync(mm);
}
}