-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEmailSettingsService.cs
More file actions
164 lines (141 loc) · 5.84 KB
/
EmailSettingsService.cs
File metadata and controls
164 lines (141 loc) · 5.84 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
using System;
using System.Threading.Tasks;
using Aquiis.SimpleStart.Core.Constants;
using Aquiis.SimpleStart.Core.Entities;
using Aquiis.SimpleStart.Core.Interfaces.Services;
using Aquiis.SimpleStart.Core.Services;
using Aquiis.SimpleStart.Infrastructure.Data;
using Aquiis.SimpleStart.Infrastructure.Services;
using Aquiis.SimpleStart.Shared.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SendGrid;
using SendGrid.Helpers.Mail;
namespace Aquiis.SimpleStart.Application.Services
{
public class EmailSettingsService : BaseService<OrganizationEmailSettings>
{
private readonly SendGridEmailService _emailService;
public EmailSettingsService(
ApplicationDbContext context,
ILogger<EmailSettingsService> logger,
UserContextService userContext,
IOptions<ApplicationSettings> settings,
SendGridEmailService emailService)
: base(context, logger, userContext, settings)
{
_emailService = emailService;
}
/// <summary>
/// Get email settings for current organization or create default disabled settings
/// </summary>
public async Task<OrganizationEmailSettings> GetOrCreateSettingsAsync()
{
var orgId = await _userContext.GetActiveOrganizationIdAsync();
if (orgId == null)
{
throw new UnauthorizedAccessException("No active organization");
}
var settings = await _dbSet
.FirstOrDefaultAsync(s => s.OrganizationId == orgId && !s.IsDeleted);
if (settings == null)
{
settings = new OrganizationEmailSettings
{
Id = Guid.NewGuid(),
OrganizationId = orgId.Value,
IsEmailEnabled = false,
DailyLimit = 100, // SendGrid free tier default
MonthlyLimit = 40000,
CreatedBy = await _userContext.GetUserIdAsync() ?? string.Empty,
CreatedOn = DateTime.UtcNow
};
await CreateAsync(settings);
}
return settings;
}
/// <summary>
/// Configure SendGrid API key and enable email functionality
/// </summary>
public async Task<OperationResult> UpdateSendGridConfigAsync(
string apiKey,
string fromEmail,
string fromName)
{
// Verify the API key works before saving
if (!await _emailService.VerifyApiKeyAsync(apiKey))
{
return OperationResult.FailureResult(
"Invalid SendGrid API key. Please verify the key has Mail Send permissions.");
}
var settings = await GetOrCreateSettingsAsync();
settings.SendGridApiKeyEncrypted = _emailService.EncryptApiKey(apiKey);
settings.FromEmail = fromEmail;
settings.FromName = fromName;
settings.IsEmailEnabled = true;
settings.IsVerified = true;
settings.LastVerifiedOn = DateTime.UtcNow;
settings.LastError = null;
await UpdateAsync(settings);
return OperationResult.SuccessResult("SendGrid configuration saved successfully");
}
/// <summary>
/// Disable email functionality for organization
/// </summary>
public async Task<OperationResult> DisableEmailAsync()
{
var settings = await GetOrCreateSettingsAsync();
settings.IsEmailEnabled = false;
await UpdateAsync(settings);
return OperationResult.SuccessResult("Email notifications disabled");
}
/// <summary>
/// Re-enable email functionality
/// </summary>
public async Task<OperationResult> EnableEmailAsync()
{
var settings = await GetOrCreateSettingsAsync();
if (string.IsNullOrEmpty(settings.SendGridApiKeyEncrypted))
{
return OperationResult.FailureResult(
"SendGrid API key not configured. Please configure SendGrid first.");
}
settings.IsEmailEnabled = true;
await UpdateAsync(settings);
return OperationResult.SuccessResult("Email notifications enabled");
}
/// <summary>
/// Send a test email to verify configuration
/// </summary>
public async Task<OperationResult> TestEmailConfigurationAsync(string testEmail)
{
try
{
await _emailService.SendEmailAsync(
testEmail,
"Aquiis Email Configuration Test",
"<h2>Configuration Test Successful!</h2>" +
"<p>This is a test email to verify your SendGrid configuration is working correctly.</p>" +
"<p>If you received this email, your email integration is properly configured.</p>");
return OperationResult.SuccessResult("Test email sent successfully! Check your inbox.");
}
catch (Exception ex)
{
_logger.LogError(ex, "Test email failed");
return OperationResult.FailureResult($"Failed to send test email: {ex.Message}");
}
}
/// <summary>
/// Update email sender information
/// </summary>
public async Task<OperationResult> UpdateSenderInfoAsync(string fromEmail, string fromName)
{
var settings = await GetOrCreateSettingsAsync();
settings.FromEmail = fromEmail;
settings.FromName = fromName;
await UpdateAsync(settings);
return OperationResult.SuccessResult("Sender information updated");
}
}
}