/// <summary> /// Signs the given mail item, if possible, according to the DKIM standard. /// </summary> /// <param name="mailItem">The mail item that is to be signed, if possible.</param> private void SignMailItem(MailItem mailItem) { // If the mail item is a "system message" then it will be read-only here, // and we can't sign it. Additionally, if the message has a "TnefPart", // then it is in a proprietary format used by Outlook and Exchange Server, // which means we shouldn't bother signing it. if (!mailItem.Message.IsSystemMessage && mailItem.Message.TnefPart == null) { string domainPart = null; /* Check if we have a valid From address */ if (!mailItem.FromAddress.IsValid || mailItem.FromAddress.DomainPart == null) { // The FromAddress is empty. Try to get the domain from somewhere else (see https://github.com/Pro/dkim-exchange/issues/99) string smtpAddress = (mailItem.Message != null && mailItem.Message.Sender != null) ? mailItem.Message.Sender.SmtpAddress : null; if (smtpAddress != null && smtpAddress.Length > 0) { try { domainPart = new MailAddress(smtpAddress).Host; } catch (FormatException) { // do nothing } } if (domainPart == null) { Logger.LogWarning("Invalid from address '" + mailItem.FromAddress + "' and invalid SmtpAddress '" + smtpAddress + "'. Not signing email."); return; } } else { // from address is valid domainPart = mailItem.FromAddress.DomainPart; } /* If domain was found in define domain configuration */ if (dkimSigner.GetDomains().ContainsKey(domainPart)) { try { dkimSigner.SignMessage(dkimSigner.GetDomains()[domainPart], mailItem); } catch (Exception ex) { Logger.LogError("Could not sign message: " + ex.Message); } } else { Logger.LogDebug("No entry found in config for domain '" + domainPart + "'"); } } else { Logger.LogDebug("Message is a System message or of TNEF format. Not signing."); } }
/// <summary> /// Load the settings from the settings.xml file and apply the new settings to the dkimSigner instance. /// </summary> private void LoadSettings() { Settings config = new Settings(); config.InitHeadersToSign(); string assemblyDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (assemblyDir != null && config.Load(Path.Combine(assemblyDir, "settings.xml"))) { dkimSigner.UpdateSettings(config); Logger.LogLevel = config.Loglevel; Logger.LogInformation("Exchange DKIM settings loaded: " + config.SigningAlgorithm + ", Canonicalization Header Algorithm: " + config.HeaderCanonicalization + ", Canonicalization Body Algorithm: " + config.BodyCanonicalization + ", Number of domains: " + dkimSigner.GetDomains().Count); } else { Logger.LogError("Couldn't load the settings file.\n"); } }