-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathEmailChannelSender.cs
More file actions
208 lines (187 loc) · 6.97 KB
/
EmailChannelSender.cs
File metadata and controls
208 lines (187 loc) · 6.97 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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
using Castle.Core.Logging;
using Shesha.Configuration;
using Shesha.Configuration.Email;
using Shesha.Domain;
using Shesha.Email.Dtos;
using Shesha.Notifications.Dto;
using Shesha.Notifications.MessageParticipants;
using Shesha.Utilities;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
namespace Shesha.Notifications
{
#nullable enable
public class EmailChannelSender : INotificationChannelSender
{
private readonly IEmailSettings _emailSettings;
public ILogger Logger { get; set; } = NullLogger.Instance;
public EmailChannelSender(IEmailSettings emailSettings)
{
_emailSettings = emailSettings;
}
public string? GetRecipientId(Person person)
{
return person?.EmailAddress1;
}
private async Task<EmailSettings> GetSettingsAsync()
{
return await _emailSettings.EmailSettings.GetValueAsync();
}
public async Task<SendStatus> SendAsync(IMessageSender? sender, IMessageReceiver receiver, NotificationMessage message, List<EmailAttachment>? attachments = null)
{
var settings = await GetSettingsAsync();
if (settings == null)
return SendStatus.Failed("Email settings are not configured");
if (!settings.EmailsEnabled)
{
Logger.Warn("Emails are disabled");
return SendStatus.Failed("Emails are disabled");
}
var toAddress = !string.IsNullOrWhiteSpace(settings.RedirectAllMessagesTo)
? settings.RedirectAllMessagesTo
: receiver.GetAddress(this);
if (string.IsNullOrWhiteSpace(toAddress))
return SendStatus.Failed("Recipient address is empty");
using (var mail = BuildMessageWith(sender?.GetAddress(this), toAddress, message.Subject, message.Message, message.Cc))
{
if (attachments != null)
{
foreach (var attachment in attachments)
{
mail.Attachments.Add(new Attachment(attachment.Stream, attachment.FileName));
}
}
try
{
await SendEmailAsync(mail);
return SendStatus.Success();
}
catch (Exception e)
{
Logger.Error("Failed to send email", e);
return SendStatus.Failed(e.Message);
}
}
}
#region private methods
/// <summary>
///
/// </summary>
/// <param name="mail"></param>
private async Task SendEmailAsync(MailMessage mail)
{
try
{
using (var smtpClient = await GetSmtpClientAsync())
{
smtpClient.Send(mail);
}
}
catch (Exception ex)
{
Logger.Error($"Error sending email: {ex.Message}", ex);
throw new InvalidOperationException($"An error occurred while sending the email. Message: {ex.Message} ", ex);
}
}
private async Task<SmtpClient> GetSmtpClientAsync()
{
var smtpSettings = await _emailSettings.SmtpSettings.GetValueAsync();
return GetSmtpClient(smtpSettings);
}
/// <summary>
/// Returns SmtpClient configured according to the current application settings
/// </summary>
private SmtpClient GetSmtpClient(SmtpSettings smtpSettings)
{
var client = new SmtpClient(smtpSettings.Host, smtpSettings.Port)
{
EnableSsl = smtpSettings.EnableSsl,
Credentials = string.IsNullOrWhiteSpace(smtpSettings.Domain)
? new NetworkCredential(smtpSettings.UserName, smtpSettings.Password)
: new NetworkCredential(smtpSettings.UserName, smtpSettings.Password, smtpSettings.Domain)
};
return client;
}
/// <summary>
///
/// </summary>
/// <param name="fromAddress"></param>
/// <param name="toAddress"></param>
/// <param name="subject"></param>
/// <param name="body"></param>
/// <param name="cc"></param>
/// <returns></returns>
private MailMessage BuildMessageWith(string? fromAddress, string toAddress, string subject, string body, string? cc = null)
{
var smtpSettings = _emailSettings.SmtpSettings.GetValue();
var message = new MailMessage
{
Subject = (subject ?? "").Replace("\r", " ").Replace("\n", " ").RemoveDoubleSpaces(),
Body = body.WrapAsHtmlDocument(),
IsBodyHtml = true,
};
if (string.IsNullOrWhiteSpace(fromAddress) || smtpSettings.ForceFromAddressFromSettings)
{
if (smtpSettings.UseSmtpRelay && !string.IsNullOrWhiteSpace(smtpSettings.DefaultFromAddress))
{
message.From = new MailAddress(
smtpSettings.DefaultFromAddress,
smtpSettings.DefaultFromDisplayName,
Encoding.UTF8
);
}
else
{
message.From = new MailAddress(
smtpSettings.UserName,
null,
Encoding.UTF8
);
}
}
else if (StringHelper.IsValidEmail(fromAddress))
{
message.From = new MailAddress(fromAddress);
}
else
{
throw new ArgumentException("Invalid email address provided.");
}
string[] tos = toAddress.Split(';');
foreach (string to in tos)
{
if (StringHelper.IsValidEmail(to))
{
message.To.Add(new MailAddress(to.Trim()));
}
else
{
throw new ArgumentException($"Invalid 'to' email address: {to}");
}
}
if (!string.IsNullOrEmpty(cc))
{
string[] copies = cc.Split(',');
foreach (var copyAddress in copies)
{
var trimmedCopy = copyAddress.Trim();
if (StringHelper.IsValidEmail(trimmedCopy))
{
message.CC.Add(new MailAddress(trimmedCopy));
}
else
{
throw new ArgumentException($"Invalid 'cc' email address: {trimmedCopy}");
}
}
}
return message;
}
#endregion
}
#nullable restore
}