Beispiel #1
1
        /// <summary>
        /// Called when the operation finishes
        /// </summary>
        /// <param name="result">The result object, if this derives from an exception, the operation failed</param>
        public void OnFinish(object result)
        {
            //If no email is supplied, then skip
            if (string.IsNullOrEmpty(m_to))
                return;

            //If we do not report this action, then skip
            if (!m_sendAll && !string.Equals(m_operationname, "Backup", StringComparison.InvariantCultureIgnoreCase))
                return;

            if (string.Equals(m_operationname, "Backup", StringComparison.InvariantCultureIgnoreCase))
            {
                MailLevels level;
                if (result is Exception)
                    level = MailLevels.Error;
                else if (result != null && result is Library.Interface.IBackupResults && (result as Library.Interface.IBackupResults).Errors.Count() > 0)
                    level = MailLevels.Warning;
                else
                    level = MailLevels.Success;

                m_parsedresultlevel = level.ToString();

                if (m_level != MailLevels.All)
                {
                    //Check if this level should send mail
                    if ((m_level & level) == 0)
                        return;
                }
            }

            try
            {
                string body = m_body;
                string subject = m_subject;
                if (body != DEFAULT_BODY && System.IO.File.Exists(body))
                    body = System.IO.File.ReadAllText(body);

                body = ReplaceTemplate(body, result, false);
                subject = ReplaceTemplate(subject, result, true);

                var message = new MimeMessage();
                MailboxAddress mailbox;
                foreach (string s in m_to.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                    if(MailboxAddress.TryParse(s.Replace("\"", ""), out mailbox))
                        message.To.Add(mailbox);

                MailboxAddress mailboxToFirst = (MailboxAddress) message.To[0];
                string toMailDomain = mailboxToFirst.Address.Substring(mailboxToFirst.Address.LastIndexOf("@") + 1);

                string from = m_from.Trim().Replace("\"", "");
                if (from.IndexOf('@') < 0)
                {
                    if (from.EndsWith(">"))
                        from = from.Insert(from.Length - 1, "@" + toMailDomain);
                    else
                        from = string.Format("No Reply - Backup report <{0}@{1}>", from, toMailDomain);
                }

                if (MailboxAddress.TryParse(from, out mailbox))
                    message.From.Add(mailbox);

                message.Subject = subject;
                message.Body = new TextPart("plain") { Text = body, ContentTransferEncoding = ContentEncoding.EightBit };

                List<string> servers = null;
                if (string.IsNullOrEmpty(m_server))
                {
                    var dnslite = new DnsLib.DnsLite();
                    var dnslist = new List<string>();

                    //Grab all IPv4 adresses
                    foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
                        try
                        {
                            foreach (IPAddress dnsAdress in networkInterface.GetIPProperties().DnsAddresses)
                                if (dnsAdress.AddressFamily == AddressFamily.InterNetwork)
                                    dnslist.Add(dnsAdress.ToString());
                        }
                        catch { }

                    dnslist = dnslist.Distinct().ToList();

                    // If we have no DNS servers, try Google and OpenDNS
                    if (dnslist.Count == 0)
                    {
                        // https://developers.google.com/speed/public-dns/
                        dnslist.Add("8.8.8.8");
                        dnslist.Add("8.8.4.4");

                        //http://www.opendns.com/opendns-ip-addresses/
                        dnslist.Add("208.67.222.222");
                        dnslist.Add("208.67.220.220");
                    }

                    var oldStyleList = new ArrayList();
                    foreach(var s in dnslist)
                        oldStyleList.Add(s);

                    dnslite.setDnsServers(oldStyleList);

                    servers = dnslite.getMXRecords(toMailDomain).OfType<MXRecord>().OrderBy(record => record.preference).Select(x => "smtp://" + x.exchange).Distinct().ToList();
                    if (servers.Count == 0)
                        throw new IOException(Strings.SendMail.FailedToLookupMXServer(OPTION_SERVER));
                }
                else
                {
                    servers = (from n in m_server.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries)
                              let srv = (n == null || n.IndexOf("://", StringComparison.InvariantCultureIgnoreCase) > 0) ? n : "smtp://" + n
                              where !string.IsNullOrEmpty(srv)
                              select srv).Distinct().ToList();
                }

                Exception lastEx = null;
                string lastServer = null;

                foreach(var server in servers)
                {
                    if (lastEx != null)
                        Logging.Log.WriteMessage(Strings.SendMail.SendMailFailedRetryError(lastServer, lastEx.Message, server), LogMessageType.Warning, lastEx);

                    lastServer = server;
                    try
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            try
                            {
                                using (var client = new SmtpClient(new MailKit.ProtocolLogger(ms)))
                                {
                                    client.Timeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds;

                                    client.Connect(new System.Uri(server));

                                    if (!string.IsNullOrEmpty(m_username) && !string.IsNullOrEmpty(m_password))
                                        client.Authenticate(m_username, m_password);

                                    client.Send(message);
                                    client.Disconnect(true);
                                }
                            }
                            finally
                            {
                                var log = Encoding.UTF8.GetString(ms.GetBuffer());
                                Logging.Log.WriteMessage(Strings.SendMail.SendMailLog(log), LogMessageType.Profiling);
                            }
                        }

                        lastEx = null;
                        Logging.Log.WriteMessage(Strings.SendMail.SendMailSuccess(server), LogMessageType.Information);
                        break;
                    }
                    catch (Exception ex)
                    {
                        lastEx = ex;
                    }
                }

                if (lastEx != null)
                    throw lastEx;
            }
            catch (Exception ex)
            {
                Exception top = ex;
                var sb = new StringBuilder();
                while (top != null)
                {
                    if (sb.Length != 0)
                        sb.Append("--> ");
                    sb.AppendFormat("{0}: {1}{2}", top.GetType().FullName, top.Message, Environment.NewLine);
                    top = top.InnerException;
                }

                Logging.Log.WriteMessage(Strings.SendMail.SendMailFailedError(sb.ToString()), LogMessageType.Warning, ex);
            }
        }
Beispiel #2
0
        /// <summary>
        /// Called when the operation finishes
        /// </summary>
        /// <param name="result">The result object, if this derives from an exception, the operation failed</param>
        public void OnFinish(object result)
        {
            //If no email is supplied, then skip
            if (string.IsNullOrEmpty(m_to))
                return;

            //If we do not report this action, then skip
            if (!m_sendAll && !string.Equals(m_operationname, "Backup", StringComparison.InvariantCultureIgnoreCase))
                return;

            if (string.Equals(m_operationname, "Backup", StringComparison.InvariantCultureIgnoreCase))
            {
                if (m_level != MailLevels.All)
                {
                    MailLevels level;
                    if (result is Exception)
                        level = MailLevels.Error;
                    else if (result != null && result is Library.Interface.IBackupResults && (result as Library.Interface.IBackupResults).Errors.Count() > 0)
                        level = MailLevels.Warning;
                    else
                        level = MailLevels.Success;

                    //Check if this level should send mail
                    if ((m_level & level) == 0)
                        return;
                }
            }

            try
            {
                string body = m_body;
                string subject = m_subject;
                if (body != DEFAULT_BODY && System.IO.File.Exists(body))
                    body = System.IO.File.ReadAllText(body);

                body = ReplaceTemplate(body, result);
                subject = ReplaceTemplate(subject, result);

                var message = new MailMessage();
                foreach(string s in m_to.Split(new [] { "," }, StringSplitOptions.RemoveEmptyEntries))
                    message.To.Add(new MailAddress(s.Replace("\"", "")));

                string from = m_from.Trim();
                if (from.IndexOf('@') < 0)
                {
                    if (from.EndsWith(">"))
                        from = from.Insert(from.Length - 1, "@" + message.To[0].Host);
                    else
                        from = string.Format("No Reply - Backup report <{0}@{1}>", from, message.To[0].Host);
                }
                message.From = new MailAddress(from.Replace("\"", ""));

                message.Subject = subject;
                message.Body = body;
                message.BodyEncoding = message.SubjectEncoding = Encoding.UTF8;

                List<string> servers = null;
                if (string.IsNullOrEmpty(m_server))
                {
                    var dnslite = new DnsLib.DnsLite();
                    var dnslist = new List<string>();

                    //Grab all IPv4 adresses
                    foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
                        try
                        {
                            foreach (IPAddress dnsAdress in networkInterface.GetIPProperties().DnsAddresses)
                                if (dnsAdress.AddressFamily == AddressFamily.InterNetwork)
                                    dnslist.Add(dnsAdress.ToString());
                        }
                        catch { }

                    dnslist = dnslist.Distinct().ToList();

                    // If we have no DNS servers, try Google and OpenDNS
                    if (dnslist.Count == 0)
                    {
                        // https://developers.google.com/speed/public-dns/
                        dnslist.Add("8.8.8.8");
                        dnslist.Add("8.8.4.4");

                        //http://www.opendns.com/opendns-ip-addresses/
                        dnslist.Add("208.67.222.222");
                        dnslist.Add("208.67.220.220");
                    }

                    var oldStyleList = new ArrayList();
                    foreach(var s in dnslist)
                        oldStyleList.Add(s);

                    dnslite.setDnsServers(oldStyleList);

                    servers = dnslite.getMXRecords(message.To[0].Host).OfType<MXRecord>().OrderBy(record => record.preference).Select(x => "smtp://" +  x.exchange).Distinct().ToList();
                    if (servers.Count == 0)
                        throw new IOException(string.Format(Strings.SendMail.FailedToLookupMXServer, OPTION_SERVER));
                }
                else
                {
                    servers = (from n in m_server.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries)
                              let srv = (n == null || n.IndexOf("://", StringComparison.InvariantCultureIgnoreCase) > 0) ? n : "smtp://" + n
                              where !string.IsNullOrEmpty(srv)
                              select srv).Distinct().ToList();
                }

                Exception lastEx = null;
                string lastServer = null;

                foreach(var server in servers)
                {
                    if (lastEx != null)
                        Logging.Log.WriteMessage(string.Format(Strings.SendMail.SendMailFailedRetryError, lastServer, lastEx.Message, server), LogMessageType.Warning, lastEx);

                    lastServer = server;
                    try
                    {
                        var serverUri = new System.Uri(server);
                        var useTls = string.Equals(serverUri.Scheme, "smtptls", StringComparison.InvariantCultureIgnoreCase) || string.Equals(serverUri.Scheme, "tls", StringComparison.InvariantCultureIgnoreCase);
                        var port = serverUri.Port <= 0 ? (useTls ? 587 : 25) : serverUri.Port;
                        var client = new SmtpClient(serverUri.Host, port);
                        client.Timeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds;
                        if (!string.IsNullOrEmpty(m_username) && !string.IsNullOrEmpty(m_password))
                            client.Credentials = new NetworkCredential(m_username, m_password);

                        //This ensures that you can override settings from an app.config file
                        if (useTls)
                            client.EnableSsl = true;

                        client.Send(message);
                        lastEx = null;
                        Logging.Log.WriteMessage(string.Format(Strings.SendMail.SendMailSuccess, server), LogMessageType.Information);
                        break;
                    }
                    catch (Exception ex)
                    {
                        lastEx = ex;
                    }
                }

                if (lastEx != null)
                    throw lastEx;
            }
            catch (Exception ex)
            {
                Exception top = ex;
                var sb = new StringBuilder();
                while (top != null)
                {
                    if (sb.Length != 0)
                        sb.Append("--> ");
                    sb.AppendFormat("{0}: {1}{2}", top.GetType().FullName, top.Message, Environment.NewLine);
                    top = top.InnerException;
                }

                Logging.Log.WriteMessage(string.Format(Strings.SendMail.SendMailFailedError, sb.ToString()), LogMessageType.Warning, ex);
            }
        }
Beispiel #3
0
        /// <summary>
        /// Called when the operation finishes
        /// </summary>
        /// <param name="result">The result object, if this derives from an exception, the operation failed</param>
        public void OnFinish(object result)
        {
            //If no email is supplied, then skip
            if (string.IsNullOrEmpty(m_to))
            {
                return;
            }

            //If we do not report this action, then skip
            if (!m_sendAll && !string.Equals(m_operationname, "Backup", StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            if (string.Equals(m_operationname, "Backup", StringComparison.InvariantCultureIgnoreCase))
            {
                MailLevels level;
                if (result is Exception)
                {
                    level = MailLevels.Error;
                }
                else if (result != null && result is Library.Interface.IBackupResults && (result as Library.Interface.IBackupResults).Errors.Count() > 0)
                {
                    level = MailLevels.Warning;
                }
                else
                {
                    level = MailLevels.Success;
                }

                m_parsedresultlevel = level.ToString();

                if (m_level != MailLevels.All)
                {
                    //Check if this level should send mail
                    if ((m_level & level) == 0)
                    {
                        return;
                    }
                }
            }

            try
            {
                string body    = m_body;
                string subject = m_subject;
                if (body != DEFAULT_BODY && System.IO.File.Exists(body))
                {
                    body = System.IO.File.ReadAllText(body);
                }

                body    = ReplaceTemplate(body, result, false);
                subject = ReplaceTemplate(subject, result, true);

                var message = new MailMessage();
                foreach (string s in m_to.Split(new [] { "," }, StringSplitOptions.RemoveEmptyEntries))
                {
                    message.To.Add(new MailAddress(s.Replace("\"", "")));
                }

                string from = m_from.Trim();
                if (from.IndexOf('@') < 0)
                {
                    if (from.EndsWith(">"))
                    {
                        from = from.Insert(from.Length - 1, "@" + message.To[0].Host);
                    }
                    else
                    {
                        from = string.Format("No Reply - Backup report <{0}@{1}>", from, message.To[0].Host);
                    }
                }
                message.From = new MailAddress(from.Replace("\"", ""));

                message.Subject      = subject;
                message.Body         = body;
                message.BodyEncoding = message.SubjectEncoding = Encoding.UTF8;

                List <string> servers = null;
                if (string.IsNullOrEmpty(m_server))
                {
                    var dnslite = new DnsLib.DnsLite();
                    var dnslist = new List <string>();

                    //Grab all IPv4 adresses
                    foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
                    {
                        try
                        {
                            foreach (IPAddress dnsAdress in networkInterface.GetIPProperties().DnsAddresses)
                            {
                                if (dnsAdress.AddressFamily == AddressFamily.InterNetwork)
                                {
                                    dnslist.Add(dnsAdress.ToString());
                                }
                            }
                        }
                        catch { }
                    }

                    dnslist = dnslist.Distinct().ToList();

                    // If we have no DNS servers, try Google and OpenDNS
                    if (dnslist.Count == 0)
                    {
                        // https://developers.google.com/speed/public-dns/
                        dnslist.Add("8.8.8.8");
                        dnslist.Add("8.8.4.4");

                        //http://www.opendns.com/opendns-ip-addresses/
                        dnslist.Add("208.67.222.222");
                        dnslist.Add("208.67.220.220");
                    }

                    var oldStyleList = new ArrayList();
                    foreach (var s in dnslist)
                    {
                        oldStyleList.Add(s);
                    }

                    dnslite.setDnsServers(oldStyleList);

                    servers = dnslite.getMXRecords(message.To[0].Host).OfType <MXRecord>().OrderBy(record => record.preference).Select(x => "smtp://" + x.exchange).Distinct().ToList();
                    if (servers.Count == 0)
                    {
                        throw new IOException(Strings.SendMail.FailedToLookupMXServer(OPTION_SERVER));
                    }
                }
                else
                {
                    servers = (from n in m_server.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries)
                               let srv = (n == null || n.IndexOf("://", StringComparison.InvariantCultureIgnoreCase) > 0) ? n : "smtp://" + n
                                         where !string.IsNullOrEmpty(srv)
                                         select srv).Distinct().ToList();
                }

                Exception lastEx     = null;
                string    lastServer = null;

                foreach (var server in servers)
                {
                    if (lastEx != null)
                    {
                        Logging.Log.WriteMessage(Strings.SendMail.SendMailFailedRetryError(lastServer, lastEx.Message, server), LogMessageType.Warning, lastEx);
                    }

                    lastServer = server;
                    try
                    {
                        var serverUri = new System.Uri(server);
                        var useTls    = string.Equals(serverUri.Scheme, "smtptls", StringComparison.InvariantCultureIgnoreCase) || string.Equals(serverUri.Scheme, "tls", StringComparison.InvariantCultureIgnoreCase);
                        var port      = serverUri.Port <= 0 ? (useTls ? 587 : 25) : serverUri.Port;
                        var client    = new SmtpClient(serverUri.Host, port);
                        client.Timeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds;
                        if (!string.IsNullOrEmpty(m_username) && !string.IsNullOrEmpty(m_password))
                        {
                            client.Credentials = new NetworkCredential(m_username, m_password);
                        }

                        //This ensures that you can override settings from an app.config file
                        if (useTls)
                        {
                            client.EnableSsl = true;
                        }

                        client.Send(message);
                        lastEx = null;
                        Logging.Log.WriteMessage(Strings.SendMail.SendMailSuccess(server), LogMessageType.Information);
                        break;
                    }
                    catch (Exception ex)
                    {
                        lastEx = ex;
                    }
                }

                if (lastEx != null)
                {
                    throw lastEx;
                }
            }
            catch (Exception ex)
            {
                Exception top = ex;
                var       sb  = new StringBuilder();
                while (top != null)
                {
                    if (sb.Length != 0)
                    {
                        sb.Append("--> ");
                    }
                    sb.AppendFormat("{0}: {1}{2}", top.GetType().FullName, top.Message, Environment.NewLine);
                    top = top.InnerException;
                }

                Logging.Log.WriteMessage(Strings.SendMail.SendMailFailedError(sb.ToString()), LogMessageType.Warning, ex);
            }
        }
Beispiel #4
0
        /// <summary>
        /// Called when the operation finishes
        /// </summary>
        /// <param name="result">The result object, if this derives from an exception, the operation failed</param>
        public void OnFinish(object result)
        {
            //If no email is supplied, then skip
            if (string.IsNullOrEmpty(m_to))
            {
                return;
            }

            //If we do not report this action, then skip
            if (!m_sendAll && !string.Equals(m_operationname, "Backup", StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            ParsedResultType level;

            if (result is Exception)
            {
                level = ParsedResultType.Fatal;
            }
            else if (result != null && result is Library.Interface.IBasicResults)
            {
                level = ((IBasicResults)result).ParsedResult;
            }
            else
            {
                level = ParsedResultType.Error;
            }

            m_parsedresultlevel = level.ToString();

            if (string.Equals(m_operationname, "Backup", StringComparison.InvariantCultureIgnoreCase))
            {
                if (!m_levels.Any(x => string.Equals(x, "all", StringComparison.OrdinalIgnoreCase)))
                {
                    //Check if this level should send mail
                    if (!m_levels.Any(x => string.Equals(x, level.ToString(), StringComparison.OrdinalIgnoreCase)))
                    {
                        return;
                    }
                }
            }

            try
            {
                string body    = m_body;
                string subject = m_subject;
                if (body != DEFAULT_BODY && System.IO.Path.IsPathRooted(body) && System.IO.File.Exists(body))
                {
                    body = System.IO.File.ReadAllText(body);
                }

                body    = ReplaceTemplate(body, result, false);
                subject = ReplaceTemplate(subject, result, true);

                var            message = new MimeMessage();
                MailboxAddress mailbox;
                foreach (string s in m_to.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                {
                    if (MailboxAddress.TryParse(s.Replace("\"", ""), out mailbox))
                    {
                        message.To.Add(mailbox);
                    }
                }

                var    mailboxToFirst = (MailboxAddress)message.To.First();
                string toMailDomain   = mailboxToFirst.Address.Substring(mailboxToFirst.Address.LastIndexOf("@", StringComparison.Ordinal) + 1);

                string from = m_from.Trim().Replace("\"", "");
                if (from.IndexOf('@') < 0)
                {
                    if (from.EndsWith(">", StringComparison.Ordinal))
                    {
                        from = from.Insert(from.Length - 1, "@" + toMailDomain);
                    }
                    else
                    {
                        from = string.Format("No Reply - Backup report <{0}@{1}>", from, toMailDomain);
                    }
                }

                if (MailboxAddress.TryParse(from, out mailbox))
                {
                    message.From.Add(mailbox);
                }

                message.Subject = subject;
                message.Body    = new TextPart("plain")
                {
                    Text = body, ContentTransferEncoding = ContentEncoding.EightBit
                };

                List <string> servers = null;
                if (string.IsNullOrEmpty(m_server))
                {
                    var dnslite = new DnsLib.DnsLite();
                    var dnslist = new List <string>();

                    //Grab all IPv4 addresses
                    foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
                    {
                        try
                        {
                            foreach (IPAddress dnsAddress in networkInterface.GetIPProperties().DnsAddresses)
                            {
                                if (dnsAddress.AddressFamily == AddressFamily.InterNetwork)
                                {
                                    dnslist.Add(dnsAddress.ToString());
                                }
                            }
                        }
                        catch { }
                    }

                    dnslist = dnslist.Distinct().ToList();

                    // If we have no DNS servers, try Google and OpenDNS
                    if (dnslist.Count == 0)
                    {
                        // https://developers.google.com/speed/public-dns/
                        dnslist.Add("8.8.8.8");
                        dnslist.Add("8.8.4.4");

                        //http://www.opendns.com/opendns-ip-addresses/
                        dnslist.Add("208.67.222.222");
                        dnslist.Add("208.67.220.220");
                    }

                    var records = new List <MXRecord>();
                    foreach (var s in dnslist)
                    {
                        var res = dnslite.getMXRecords(toMailDomain, s);
                        if (res != null)
                        {
                            records.AddRange(res.OfType <MXRecord>());
                        }
                    }

                    servers = records.OrderBy(record => record.preference).Select(x => "smtp://" + x.exchange).Distinct().ToList();
                    if (servers.Count == 0)
                    {
                        throw new IOException(Strings.SendMail.FailedToLookupMXServer(OPTION_SERVER));
                    }
                }
                else
                {
                    servers = (from n in m_server.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries)
                               let srv = (n == null || n.IndexOf("://", StringComparison.InvariantCultureIgnoreCase) > 0) ? n : "smtp://" + n
                                         where !string.IsNullOrEmpty(srv)
                                         select srv).Distinct().ToList();
                }

                Exception lastEx     = null;
                string    lastServer = null;

                foreach (var server in servers)
                {
                    if (lastEx != null)
                    {
                        Logging.Log.WriteMessage(Strings.SendMail.SendMailFailedRetryError(lastServer, lastEx.Message, server), LogMessageType.Warning, lastEx);
                    }

                    lastServer = server;
                    try
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            try
                            {
                                using (var client = new SmtpClient(new MailKit.ProtocolLogger(ms)))
                                {
                                    client.Timeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds;

                                    // Backward compatibility fix for setup prior to using MailKit
                                    var uri = new System.Uri(server);
                                    if (uri.Scheme.ToLowerInvariant() == "tls")
                                    {
                                        uri = new System.Uri("smtp://" + uri.Host + ":" + (uri.Port <= 0 ? 587 : uri.Port) + "/?starttls=always");
                                    }

                                    client.Connect(uri);

                                    if (!string.IsNullOrEmpty(m_username) && !string.IsNullOrEmpty(m_password))
                                    {
                                        client.Authenticate(m_username, m_password);
                                    }

                                    client.Send(message);
                                    client.Disconnect(true);
                                }
                            }
                            finally
                            {
                                var log = Encoding.UTF8.GetString(ms.GetBuffer());
                                if (!string.IsNullOrWhiteSpace(log))
                                {
                                    Logging.Log.WriteMessage(Strings.SendMail.SendMailLog(log), LogMessageType.Profiling);
                                }
                            }
                        }

                        lastEx = null;
                        Logging.Log.WriteMessage(Strings.SendMail.SendMailSuccess(server), LogMessageType.Information);
                        break;
                    }
                    catch (Exception ex)
                    {
                        lastEx = ex;
                    }
                }

                if (lastEx != null)
                {
                    throw lastEx;
                }
            }
            catch (Exception ex)
            {
                Exception top = ex;
                var       sb  = new StringBuilder();
                while (top != null)
                {
                    if (sb.Length != 0)
                    {
                        sb.Append("--> ");
                    }
                    sb.AppendFormat("{0}: {1}{2}", top.GetType().FullName, top.Message, Environment.NewLine);
                    top = top.InnerException;
                }

                Logging.Log.WriteMessage(Strings.SendMail.SendMailFailedError(sb.ToString()), LogMessageType.Warning, ex);
            }
        }
Beispiel #5
0
        /// <summary>
        /// Sends the email message
        /// </summary>
        /// <param name="subject">The subject line.</param>
        /// <param name="body">The message body.</param>
        protected override void SendMessage(string subject, string body)
        {
            var            message = new MimeMessage();
            MailboxAddress mailbox;

            foreach (string s in m_to.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries))
            {
                if (MailboxAddress.TryParse(s.Replace("\"", ""), out mailbox))
                {
                    message.To.Add(mailbox);
                }
            }

            var    mailboxToFirst = (MailboxAddress)message.To.First();
            string toMailDomain   = mailboxToFirst.Address.Substring(mailboxToFirst.Address.LastIndexOf("@", StringComparison.Ordinal) + 1);

            string from = m_from.Trim().Replace("\"", "");

            if (from.IndexOf('@') < 0)
            {
                if (from.EndsWith(">", StringComparison.Ordinal))
                {
                    from = from.Insert(from.Length - 1, "@" + toMailDomain);
                }
                else
                {
                    from = string.Format("No Reply - Backup report <{0}@{1}>", from, toMailDomain);
                }
            }

            if (MailboxAddress.TryParse(from, out mailbox))
            {
                message.From.Add(mailbox);
            }

            message.Subject = subject;
            message.Body    = new TextPart("plain")
            {
                Text = body, ContentTransferEncoding = ContentEncoding.EightBit
            };

            List <string> servers = null;

            if (string.IsNullOrEmpty(m_server))
            {
                var dnslite = new DnsLib.DnsLite();
                var dnslist = new List <string>();

                //Grab all IPv4 addresses
                foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
                {
                    try
                    {
                        foreach (IPAddress dnsAddress in networkInterface.GetIPProperties().DnsAddresses)
                        {
                            if (dnsAddress.AddressFamily == AddressFamily.InterNetwork)
                            {
                                dnslist.Add(dnsAddress.ToString());
                            }
                        }
                    }
                    catch (Exception ex) { Logging.Log.WriteExplicitMessage(LOGTAG, "DNSServerLookupFailure", ex, "Failed to get DNS servers from network interface"); }
                }

                dnslist = dnslist.Distinct().ToList();

                // If we have no DNS servers, try Google and OpenDNS
                if (dnslist.Count == 0)
                {
                    // https://developers.google.com/speed/public-dns/
                    dnslist.Add("8.8.8.8");
                    dnslist.Add("8.8.4.4");

                    //http://www.opendns.com/opendns-ip-addresses/
                    dnslist.Add("208.67.222.222");
                    dnslist.Add("208.67.220.220");
                }

                var records = new List <MXRecord>();
                foreach (var s in dnslist)
                {
                    var res = dnslite.getMXRecords(toMailDomain, s);
                    if (res != null)
                    {
                        records.AddRange(res.OfType <MXRecord>());
                    }
                }

                servers = records.OrderBy(record => record.preference).Select(x => "smtp://" + x.exchange).Distinct().ToList();
                if (servers.Count == 0)
                {
                    throw new IOException(Strings.SendMail.FailedToLookupMXServer(OPTION_SERVER));
                }
            }
            else
            {
                servers = (from n in m_server.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries)
                           let srv = (n == null || n.IndexOf("://", StringComparison.OrdinalIgnoreCase) > 0) ? n : "smtp://" + n
                                     where !string.IsNullOrEmpty(srv)
                                     select srv).Distinct().ToList();
            }

            Exception lastEx     = null;
            string    lastServer = null;

            foreach (var server in servers)
            {
                if (lastEx != null)
                {
                    Logging.Log.WriteWarningMessage(LOGTAG, "SendMailFailedWillRetry", lastEx, Strings.SendMail.SendMailFailedRetryError(lastServer, lastEx.Message, server));
                }

                lastServer = server;
                try
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        try
                        {
                            using (var client = new SmtpClient(new MailKit.ProtocolLogger(ms)))
                            {
                                client.Timeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds;

                                // Backward compatibility fix for setup prior to using MailKit
                                var uri = new System.Uri(server);
                                if (uri.Scheme.ToLowerInvariant() == "tls")
                                {
                                    uri = new System.Uri("smtp://" + uri.Host + ":" + (uri.Port <= 0 ? 587 : uri.Port) + "/?starttls=always");
                                }

                                client.Connect(uri);

                                if (!string.IsNullOrEmpty(m_username) && !string.IsNullOrEmpty(m_password))
                                {
                                    client.Authenticate(m_username, m_password);
                                }

                                client.Send(message);
                                client.Disconnect(true);
                            }
                        }
                        finally
                        {
                            var log = Encoding.UTF8.GetString(ms.GetBuffer());
                            if (!string.IsNullOrWhiteSpace(log))
                            {
                                Logging.Log.WriteProfilingMessage(LOGTAG, "SendMailResult", Strings.SendMail.SendMailLog(log));
                            }
                        }
                    }

                    lastEx = null;
                    Logging.Log.WriteInformationMessage(LOGTAG, "SendMailComplete", Strings.SendMail.SendMailSuccess(server));
                    break;
                }
                catch (Exception ex)
                {
                    lastEx = ex;
                }
            }

            if (lastEx != null)
            {
                throw lastEx;
            }
        }