aboutsummaryrefslogtreecommitdiff
path: root/lib/Emails.Transactional.Plugin/src/Mta/SmtpProvider.cs
blob: 78781d4ba67fe28b507ac188caa8d89a4ff3d55d (plain)
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
/*
* Copyright (c) 2023 Vaughn Nugent
* 
* Library: VNLib
* Package: Emails.Transactional
* File: SmtpProvider.cs 
*
* SmtpProvider.cs is part of Emails.Transactional which is part of the larger 
* VNLib collection of libraries and utilities.
*
* Emails.Transactional is free software: you can redistribute it and/or modify 
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 2 of the License,
* or (at your option) any later version.
*
* Emails.Transactional is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License 
* along with Emails.Transactional. If not, see http://www.gnu.org/licenses/.
*/

using System;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;

using MailKit.Net.Smtp;

using MimeKit;
using MimeKit.Text;

using VNLib.Utils.Extensions;
using VNLib.Plugins;
using VNLib.Plugins.Extensions.Loading;

namespace Emails.Transactional.Mta
{

    [ConfigurationName("smtp")]
    internal sealed class SmtpProvider : IMailTransferAgent
    {
        private readonly Uri ServerAddress;
        private readonly IAsyncLazy<ICredentials> ServerCreds;
        private readonly TimeSpan Timeout;

        public SmtpProvider(PluginBase plugin, IConfigScope config)
        {
            ServerAddress = config.GetRequiredProperty("server_address", e => new Uri(e.GetString()!));
            Timeout = config["timeout_ms"].GetTimeSpan(TimeParseType.Milliseconds);

            //Get the client id from the config
            string clientId = config.GetRequiredProperty("username", e => e.GetString()!);

            //Get the password from the secret store and make it lazy loaded
            ServerCreds = plugin.GetSecretAsync("smtp_password").ToLazy<ICredentials>(r => new NetworkCredential(clientId, r.Result.ToString()));
        }


        ///<inheritdoc/>
        public async Task<MtaResult> SendEmailAsync(EmailTransaction transaction, IEmailMessageData template, CancellationToken cancellation = default)
        {
            _ = transaction ?? throw new ArgumentNullException(nameof(transaction));

            ICredentials creds = await ServerCreds;

            //Configured a new message
            using MimeMessage message = new()
            {
                Date = DateTime.UtcNow,
                Subject = transaction.Subject
            };

            //From address is the stored from address
            message.From.Add(new MailboxAddress(transaction.FromName, transaction.From));

            if (transaction.ToAddresses == null)
            {
                throw new ArgumentException("The transaction must contain at least one To address");
            }

            //Add to email addresses
            foreach (KeyValuePair<string, string> tos in transaction.ToAddresses)
            {
                message.To.Add(new MailboxAddress(tos.Value, tos.Key));
            }

            //Add ccs 
            if (transaction.CcAddresses != null)
            {
                foreach (KeyValuePair<string, string> ccs in transaction.CcAddresses)
                {
                    message.Cc.Add(new MailboxAddress(ccs.Value, ccs.Key));
                }
            }

            //Add bccs
            if (transaction.BccAddresses != null)
            {
                foreach (KeyValuePair<string, string> bccs in transaction.BccAddresses)
                {
                    message.Bcc.Add(new MailboxAddress(bccs.Value, bccs.Key));
                }
            }

            //Use html format since we expect to be reading html templates
            using TextPart body = new(TextFormat.Html)
            {
                IsAttachment = false
            };

            //Set the body text
            body.SetText(Encoding.UTF8, template.GetHtml());

            //Set message body
            message.Body = body;

            //Open a new mail client
            using SmtpClient client = new();

            //Set timeout for senting messages
            client.Timeout = (int)Timeout.TotalMilliseconds;

            //Connect to server
            await client.ConnectAsync(ServerAddress, cancellation);

            //Authenticate
            await client.AuthenticateAsync(creds, cancellation);

            //Send the email
            transaction.Result = await client.SendAsync(message, cancellation);

            //Disconnect from the server
            await client.DisconnectAsync(true, CancellationToken.None);

            return new MtaResult(true, transaction.Result);
        }
    }
}