Skip to content
Snippets Groups Projects
Email.cs 9.88 KiB
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using ATxCommon;

namespace ATxService
{
    public partial class AutoTx
    {
        /// <summary>
        /// Send an email using the configuration values.
        /// </summary>
        /// <param name="recipient">A full email address OR a valid ActiveDirectory account.</param>
        /// <param name="subject">The subject, might be prefixed with a configurable string.</param>
        /// <param name="body">The email body.</param>
        private void SendEmail(string recipient, string subject, string body) {
            subject = $"{_config.EmailPrefix}{ServiceName} - {subject} - {_config.HostAlias}";
            body += $"\n\n--\n[{_versionSummary}]\n";
            if (string.IsNullOrEmpty(_config.SmtpHost)) {
                Log.Debug("SendEmail: {0}\n{1}", subject, body);
                return;
            }
            if (!recipient.Contains(@"@")) {
                Log.Trace("Invalid recipient, trying to resolve via AD: {0}", recipient);
                recipient = ActiveDirectory.GetEmailAddress(recipient);
            }
            if (string.IsNullOrWhiteSpace(recipient)) {
                Log.Info("Invalid or empty recipient given, NOT sending email!");
                Log.Debug("SendEmail: {0}\n{1}", subject, body);
                return;
            }
            try {
                var smtpClient = new SmtpClient() {
                    Port = _config.SmtpPort,
                    Host = _config.SmtpHost,
                    EnableSsl = true,
                    Timeout = 10000,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = new System.Net.NetworkCredential(_config.SmtpUserCredential,
                        _config.SmtpPasswortCredential)
                };
                var mail = new MailMessage(_config.EmailFrom, recipient, subject, body) {
                    BodyEncoding = Encoding.UTF8
                };
                smtpClient.Send(mail);
            }
            catch (Exception ex) {
                Log.Error("Error in SendEmail(): {0}\nInnerException: {1}\nStackTrace: {2}",
                    ex.Message, ex.InnerException, ex.StackTrace);
            }
        }

        /// <summary>
        /// Load an email template from a file and do a search-replace with strings in a list.
        /// 
        /// NOTE: template files are expected to be in a subdirectory of the service executable.
        /// </summary>
        /// <param name="templateName">The file name of the template, without path.</param>
        /// <param name="substitions">A list of string-tuples to be used for the search-replace.</param>
        /// <returns>The template with all patterns replaced by their substitution values.</returns>
        private static string LoadMailTemplate(string templateName, List<Tuple<string, string>> substitions) {
            var text = File.ReadAllText(
                Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                    "Mail-Templates", templateName));
            foreach (var pair in substitions) {
                text = text.Replace(pair.Item1, pair.Item2);