-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
121 lines (98 loc) · 3.92 KB
/
Program.cs
File metadata and controls
121 lines (98 loc) · 3.92 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
using Azure.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Relayway;
using Serilog;
using Serilog.Events;
using SmtpServer;
using System.Reflection;
using System.Text.Json;
using ServiceProvider = SmtpServer.ComponentModel.ServiceProvider;
// Version and copyright message
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Relayway");
Console.WriteLine(Assembly.GetEntryAssembly()!.GetName().Version?.ToString(3));
Console.ForegroundColor = ConsoleColor.White;
// Configuration
IConfigurationBuilder builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true)
.AddEnvironmentVariables();
IConfiguration configuration = builder.Build();
// Get log level string
string logLevelString = configuration["LogLevel"] ?? "Information";
// Parse to Serilog log level enum
bool parsed = Enum.TryParse<LogEventLevel>(logLevelString, ignoreCase: true, out var logLevel);
if (!parsed)
{
logLevel = LogEventLevel.Information;
}
// Creating logger
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Is(logLevel)
.WriteTo.Console(
theme: Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme.Literate,
outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {Message:lj}{NewLine}{Exception}")
.CreateLogger();
// Prase config
Relayway.Configuration? config = configuration.Get<Relayway.Configuration>();
// If configuration can not be parsed to config - exit
if (config == null || config.Graph == null || config.Smtp == null || config.SendFrom == null)
{
Log.Error("Could not load the configuration! Please see the README for how to set the configuration!");
Environment.Exit(1);
}
// Log configuration
Log.Information("Configuration: \n {Serialize}", JsonSerializer.Serialize(config, new JsonSerializerOptions{WriteIndented = true}));
// Create SMTP Server options
ISmtpServerOptions? options = new SmtpServerOptionsBuilder()
.ServerName(config.Smtp.Host)
.Port(config.Smtp.Port, false)
.Build();
// Create client secrete credential
ClientSecretCredential clientSecretCredential = new(
config.Graph.TenantId,
config.Graph.ClientId,
config.Graph.ClientSecret,
new ClientSecretCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
}
);
// Create graph client
GraphServiceClient graphClient = new(clientSecretCredential, new[] { "https://graph.microsoft.com/.default" });
// SendFrom checks
try
{
User? user = await graphClient.Users[config.SendFrom].GetAsync();
if (user == null)
{
Log.Error("The specifed SendFrom address: '{From}' does not exist in the tenant!", config.SendFrom);
Environment.Exit(1);
}
if (user.Mail == null && user.UserPrincipalName == null)
{
Log.Error("The user '{From}' has no email address configured and cannot send mail.", config.SendFrom);
Environment.Exit(1);
}
if (user.MailboxSettings == null)
{
Log.Warning("Mailbox settings for user '{From}' not found. Sending mail might not be available.", config.SendFrom);
}
}
catch (Microsoft.Graph.Models.ODataErrors.ODataError error)
{
Log.Error("The specifed SendFrom address: '{From}' does not exist in the tenant!\nThe Micrsoft Graph error message is: '{error}'", config.SendFrom, error.Message);
Environment.Exit(1);
}
// Create email service provider
ServiceProvider emailServiceProvider = new();
// Add the message handler to the service provider
emailServiceProvider.Add(new Relayway.MessageHandler(graphClient, Log.Logger.ForContext<Relayway.MessageHandler>(), config.SendFrom));
// Create the server
SmtpServer.SmtpServer smtpServer = new(options, emailServiceProvider);
// Log server start
Log.Information("Smtp server started on {SmtpHost}:{SmtpPort}", config.Smtp.Host, config.Smtp.Port);
// Start the server
await smtpServer.StartAsync(CancellationToken.None);