public void Valid_send_sign_DomainKey_then_DKIM(string headers)
        {
            var msg = new MailMessage();

            msg.To.Add(new MailAddress(_to, "Jim Bob"));
            msg.From    = new MailAddress(_from, "Joe Bloggs");
            msg.Subject = "Test DomainKeys & DKIM Message";
            msg.Body    = "A simple message";



            var domainKeySigner = new DomainKeySigner(PrivateKeySigner.Create(_privateKey), _domain, _selector, GetHeaders(headers));

            msg.DomainKeySign(domainKeySigner);


            var dkimSigner = new DkimSigner(PrivateKeySigner.Create(_privateKey), _domain, _selector, GetHeaders(headers));

            msg.DkimSign(dkimSigner);



            var smtp = new SmtpClient();

            smtp.Send(msg);
        }
Beispiel #2
0
        private static void GetDkimSigners()
        {
            try
            {
                var files = new DirectoryInfo(Config.PrivateKeyFolder).GetFiles("*.pem");

                if (files.Length == 0)
                {
                    throw new Exception("No private key files (*.pem) found");
                }

                foreach (var file in files)
                {
                    var key      = file.Name.Replace(".pem", "");
                    var selector = key.Split('@')[0];
                    var domain   = key.Split('@')[1];

                    var pKeySig      = PrivateKeySigner.LoadFromFile(file.FullName);
                    var dkimSig      = new DkimSigner(pKeySig, domain, selector, new[] { "From", "To", "Subject" });
                    var domainKeySig = new DomainKeySigner(pKeySig, domain, selector, new[] { "From", "To", "Subject" });

                    dkimSig.HeaderCanonicalization = DkimCanonicalizationAlgorithm.RELAXED;
                    dkimSig.BodyCanonicalization   = DkimCanonicalizationAlgorithm.RELAXED;

                    _dkimSignerCache.TryAdd(key, dkimSig);
                    _domailKeySignerCache.TryAdd(key, domainKeySig);
                }
            }
            catch (Exception ex)
            {
                Logger.Log.Warn("Unable to turn on DKIM: {0}", ex.Message);
            }
        }
Beispiel #3
0
        public void TestArgumentExceptions()
        {
            var        locator    = new DummyPublicKeyLocator(DkimKeys.Public);
            var        dkimHeader = new Header(HeaderId.DkimSignature, "value");
            var        options    = FormatOptions.Default;
            var        message    = new MimeMessage();
            DkimSigner signer;

            Assert.Throws <ArgumentNullException> (() => new DkimSigner((AsymmetricKeyParameter)null, "domain", "selector"));
            Assert.Throws <ArgumentException> (() => new DkimSigner(DkimKeys.Public, "domain", "selector"));
            Assert.Throws <ArgumentNullException> (() => new DkimSigner(DkimKeys.Private, null, "selector"));
            Assert.Throws <ArgumentNullException> (() => new DkimSigner(DkimKeys.Private, "domain", null));
            Assert.Throws <ArgumentNullException> (() => new DkimSigner((string)null, "domain", "selector"));
            Assert.Throws <ArgumentNullException> (() => new DkimSigner("fileName", null, "selector"));
            Assert.Throws <ArgumentNullException> (() => new DkimSigner("fileName", "domain", null));
            Assert.Throws <ArgumentException> (() => new DkimSigner(string.Empty, "domain", "selector"));
            Assert.Throws <ArgumentNullException> (() => new DkimSigner((Stream)null, "domain", "selector"));
            using (var stream = File.OpenRead(Path.Combine("..", "..", "TestData", "dkim", "example.pem"))) {
                Assert.Throws <ArgumentNullException> (() => new DkimSigner(stream, null, "selector"));
                Assert.Throws <ArgumentNullException> (() => new DkimSigner(stream, "domain", null));

                signer = new DkimSigner(stream, "example.com", "1433868189.example")
                {
                    SignatureAlgorithm    = DkimSignatureAlgorithm.RsaSha1,
                    AgentOrUserIdentifier = "@eng.example.com",
                    QueryMethod           = "dns/txt",
                };
            }

            Assert.Throws <ArgumentNullException> (() => message.Sign(null, new HeaderId[] { HeaderId.From }));
            Assert.Throws <ArgumentNullException> (() => message.Sign(signer, (IList <HeaderId>)null));
            Assert.Throws <ArgumentException> (() => message.Sign(signer, new HeaderId[] { HeaderId.Unknown, HeaderId.From }));
            Assert.Throws <ArgumentException> (() => message.Sign(signer, new HeaderId[] { HeaderId.Received, HeaderId.From }));
            Assert.Throws <ArgumentException> (() => message.Sign(signer, new HeaderId[] { HeaderId.ContentType }));
            Assert.Throws <ArgumentNullException> (() => message.Sign(null, new string[] { "From" }));
            Assert.Throws <ArgumentNullException> (() => message.Sign(signer, (IList <string>)null));
            Assert.Throws <ArgumentException> (() => message.Sign(signer, new string[] { "", "From" }));
            Assert.Throws <ArgumentException> (() => message.Sign(signer, new string[] { null, "From" }));
            Assert.Throws <ArgumentException> (() => message.Sign(signer, new string[] { "Received", "From" }));
            Assert.Throws <ArgumentException> (() => message.Sign(signer, new string[] { "Content-Type" }));

            Assert.Throws <ArgumentNullException> (() => message.Sign(null, signer, new HeaderId[] { HeaderId.From }));
            Assert.Throws <ArgumentNullException> (() => message.Sign(options, null, new HeaderId[] { HeaderId.From }));
            Assert.Throws <ArgumentException> (() => message.Sign(options, signer, new HeaderId[] { HeaderId.From, HeaderId.Unknown }));
            Assert.Throws <ArgumentNullException> (() => message.Sign(options, signer, (IList <HeaderId>)null));

            Assert.Throws <ArgumentNullException> (() => message.Sign(null, signer, new string[] { "From" }));
            Assert.Throws <ArgumentNullException> (() => message.Sign(options, null, new string[] { "From" }));
            Assert.Throws <ArgumentException> (() => message.Sign(options, signer, new string[] { "From", null }));
            Assert.Throws <ArgumentNullException> (() => message.Sign(options, signer, (IList <string>)null));

            Assert.Throws <ArgumentNullException> (() => message.Verify(null, locator));
            Assert.Throws <ArgumentNullException> (() => message.Verify(dkimHeader, null));
            Assert.Throws <ArgumentNullException> (() => message.Verify(null, dkimHeader, locator));
            Assert.Throws <ArgumentNullException> (() => message.Verify(FormatOptions.Default, null, locator));
            Assert.Throws <ArgumentNullException> (() => message.Verify(FormatOptions.Default, dkimHeader, null));
        }
Beispiel #4
0
        private void WriteSignedContent()
        {
            var content = new MailPayload(GetMessage());

            var dkim   = new DkimSigner(config);
            var header = dkim.CreateHeader(content.Headers, content.Body, signatureDate);

            WriteHeader(header);
            Write(content);
        }
Beispiel #5
0
        public void TestInitialize()
        {
            Message = new System.Net.Mail.MailMessage();
            Message.To.Add(new MailAddress("*****@*****.**", "Jim Bob"));
            Message.From    = new MailAddress("*****@*****.**", "Joe Bloggs");
            Message.Subject = "Test DKIM Message";
            Message.Body    = "A simple message";

            Smtp = new SmtpClient();
            Smtp.DeliveryMethod          = SmtpDeliveryMethod.SpecifiedPickupDirectory;
            Smtp.PickupDirectoryLocation = Path.GetTempPath();

            DkimSigner      = new DkimSigner(PrivateKeySigner.Create(PrivateKey), "acme.com", "dkim", GetHeaders("From,To,Subject"));
            DomainKeySigner = new DomainKeySigner(PrivateKeySigner.Create(PrivateKey), "acme.com", "dkim", GetHeaders("From,To,Subject"));
        }
Beispiel #6
0
        private static bool SendEmailInternal(string to, string subject, string body, string replyToName, string replyToEmail)
        {
            try
            {
                if (Debugger.IsAttached || Configuration.GetSMTPUserName().IsNullOrEmpty())
                {
                    HttpContext.Current.Response.Write(subject + " " + body);
                    return(false);
                }

                var privateKey = PrivateKeySigner.Create(Configuration.GetDomainKey());

                using (var client = new SmtpClient())
                {
                    var message = new MailMessage();
                    message.To.Add(new MailAddress(to));

                    if (!replyToEmail.IsNullOrEmpty())
                    {
                        ActionExtensions.TryAction(() => message.ReplyToList.Add(new MailAddress(replyToEmail, replyToName)));
                    }

                    message.From       = new MailAddress("*****@*****.**", "rssheap");
                    message.Subject    = subject;
                    message.Body       = body;
                    message.IsBodyHtml = true;

                    var domainKeySigner = new DomainKeySigner(privateKey, "rssheap.com", "abc", new string[] { "From", "To", "Subject" });
                    message.DomainKeySign(domainKeySigner);

                    var dkimSigner = new DkimSigner(privateKey, "rssheap.com", "abc", new string[] { "From", "To", "Subject" });
                    message.DkimSign(dkimSigner);

                    client.Host = "192.99.232.179";
                    client.Port = 25;
                    client.UseDefaultCredentials = false;
                    client.Credentials           = new NetworkCredential(Configuration.GetSMTPUserName(), Configuration.GetSMTPPassword());
                    client.EnableSsl             = false;

                    client.Send(message);
                }
            }
            catch
            {
                return(false);
            }
            return(true);
        }
Beispiel #7
0
        public void TestDkimSignerDefaults()
        {
            var        path = Path.Combine(TestHelper.ProjectDir, "TestData", "dkim", "example.pem");
            DkimSigner signer;

            signer = new DkimSigner(DkimKeys.Private, "example.com", "1433868189.example");
            Assert.AreEqual(DkimSignatureAlgorithm.RsaSha256, signer.SignatureAlgorithm, "SignatureAlgorithm #1");

            signer = new DkimSigner(path, "example.com", "1433868189.example");
            Assert.AreEqual(DkimSignatureAlgorithm.RsaSha256, signer.SignatureAlgorithm, "SignatureAlgorithm #2");

            using (var stream = File.OpenRead(path)) {
                signer = new DkimSigner(stream, "example.com", "1433868189.example");
                Assert.AreEqual(DkimSignatureAlgorithm.RsaSha256, signer.SignatureAlgorithm, "SignatureAlgorithm #3");
            }
        }
        public static void DkimSign(MimeMessage message)
        {
            var headers = new HeaderId[] { HeaderId.From, HeaderId.Subject, HeaderId.Date };
            var signer  = new DkimSigner("privatekey.pem", "example.com", "brisbane", DkimSignatureAlgorithm.RsaSha256)
            {
                HeaderCanonicalizationAlgorithm = DkimCanonicalizationAlgorithm.Simple,
                BodyCanonicalizationAlgorithm   = DkimCanonicalizationAlgorithm.Simple,
                AgentOrUserIdentifier           = "@eng.example.com",
                QueryMethod = "dns/txt",
            };

            // Prepare the message body to be sent over a 7bit transport (such as older versions of SMTP).
            // Note: If the SMTP server you will be sending the message over supports the 8BITMIME extension,
            // then you can use `EncodingConstraint.EightBit` instead.
            message.Prepare(EncodingConstraint.SevenBit);

            signer.Sign(message, headers);
        }
Beispiel #9
0
        public static void SendEmailWithDKIP(string subject, string body)
        {
            if (Configuration.GetSMTPUserName().IsNullOrEmpty())
            {
                return;
            }

            var privateKey = PrivateKeySigner.Create(Configuration.GetDomainKey());

            var msg = new MailMessage();

            msg.To.Add(new MailAddress("*****@*****.**"));
            msg.From    = new MailAddress("*****@*****.**", "rssheap");
            msg.Subject = subject;
            msg.Body    = body;

            var domainKeySigner = new DomainKeySigner(privateKey, "rssheap.com", "abc", new string[] { "From", "To", "Subject" });

            msg.DomainKeySign(domainKeySigner);

            var dkimSigner = new DkimSigner(privateKey, "rssheap.com", "abc", new string[] { "From", "To", "Subject" });

            msg.DkimSign(dkimSigner);

            var client = new SmtpClient
            {
                Host = "192.99.232.179",
                Port = 25,
                UseDefaultCredentials = false,
                Credentials           = new NetworkCredential(Configuration.GetSMTPUserName(), Configuration.GetSMTPPassword()),
                EnableSsl             = false
            };

            try
            {
                client.Send(msg);
            }
            catch
            {
                string bp = string.Empty;
            }
        }
        public void AddDkimHeader(System.Net.Mail.MailMessage message)
        {
            if (string.IsNullOrWhiteSpace(GlobalConfiguration.Configuration.DkimPrivateKey))
            {
                return;
            }
            if (message.From.Host != GlobalConfiguration.Configuration.DkimDomain)
            {
                return;
            }

            try
            {
                var privateKey   = DKIM.PrivateKeySigner.Create(GlobalConfiguration.Configuration.DkimPrivateKey);
                var headerToSign = new string[] { "From", "To", "Subject" };

                var domainKeySigner = new DKIM.DomainKeySigner(privateKey,
                                                               GlobalConfiguration.Configuration.DkimDomain,
                                                               GlobalConfiguration.Configuration.DkimSelector,
                                                               headerToSign);

                var dkimSigner = new DkimSigner(privateKey,
                                                GlobalConfiguration.Configuration.DkimDomain,
                                                GlobalConfiguration.Configuration.DkimSelector,
                                                headerToSign);


                message.DomainKeySign(domainKeySigner);
                message.DkimSign(dkimSigner);
            }
            catch (Exception ex)
            {
                ex.Data.Add("domain", GlobalConfiguration.Configuration.DkimDomain);
                ex.Data.Add("from", message.From.Address);
                foreach (var emailTo in message.To)
                {
                    ex.Data.Add(string.Format("to{0}", message.To.IndexOf(emailTo)), emailTo.Address);
                }
                ex.Data.Add("subject", message.Subject);
                GlobalConfiguration.Configuration.Logger.Error(ex);
            }
        }
Beispiel #11
0
        public void TestDkimSignerCtors()
        {
            Assert.DoesNotThrow(() => {
                var signer = new DkimSigner(Path.Combine(TestHelper.ProjectDir, "TestData", "dkim", "example.pem"), "example.com", "1433868189.example")
                {
                    SignatureAlgorithm    = DkimSignatureAlgorithm.RsaSha256,
                    AgentOrUserIdentifier = "@eng.example.com",
                    QueryMethod           = "dns/txt"
                };
            });

            Assert.DoesNotThrow(() => {
                var signer = new DkimSigner(DkimKeys.Private, "example.com", "1433868189.example")
                {
                    SignatureAlgorithm    = DkimSignatureAlgorithm.RsaSha256,
                    AgentOrUserIdentifier = "@eng.example.com",
                    QueryMethod           = "dns/txt"
                };
            });
        }
Beispiel #12
0
        public void Valid_send_sign_DKIM(string headers)
        {

            var msg = new MailMessage();
            msg.To.Add(new MailAddress(_to, "Jim Bob"));
            msg.From = new MailAddress(_from, "Joe Bloggs");
            msg.Subject = "Test DKIM Message";
            msg.Body = "A simple message";


            var dkimSigner = new DkimSigner(PrivateKeySigner.Create(_privateKey), _domain, _selector, GetHeaders(headers));

            msg.DkimSign(dkimSigner);

            var smtp = new SmtpClient();

            smtp.Send(msg);



        }
Beispiel #13
0
        public void TestSignRfc8463Example()
        {
            var message = MimeMessage.Load(Path.Combine(TestHelper.ProjectDir, "TestData", "dkim", "rfc8463-example.msg"));
            var signer  = new DkimSigner(Ed25519PrivateKey, "football.example.com", "brisbane", DkimSignatureAlgorithm.Ed25519Sha256)
            {
                HeaderCanonicalizationAlgorithm = DkimCanonicalizationAlgorithm.Relaxed,
                BodyCanonicalizationAlgorithm   = DkimCanonicalizationAlgorithm.Relaxed,
                AgentOrUserIdentifier           = "@football.example.com"
            };
            var headers = new string[] { "from", "to", "subject", "date", "message-id", "from", "subject", "date" };

            signer.Sign(message, headers);

            int index    = message.Headers.IndexOf(HeaderId.DkimSignature);
            var locator  = new DkimPublicKeyLocator();
            var verifier = new DkimVerifier(locator);
            var dkim     = message.Headers[index];

            locator.Add("brisbane._domainkey.football.example.com", "v=DKIM1; k=ed25519; p=11qYAYKxCrfVS/7TyWQHOg7hcvPapiMlrwIaaPcHURo=");
            locator.Add("test._domainkey.football.example.com", "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDkHlOQoBTzWRiGs5V6NpP3idY6Wk08a5qhdR6wy5bdOKb2jLQiY/J16JYi0Qvx/byYzCNb3W91y3FutACDfzwQ/BC/e/8uBsCR+yz1Lxj+PL6lHvqMKrM3rG4hstT5QjvHO9PzoxZyVYLzBfO2EeC3Ip3G+2kryOTIKT+l/K4w3QIDAQAB");

            Assert.IsTrue(verifier.Verify(message, message.Headers[index]), "Failed to verify ed25519-sha256");
        }
Beispiel #14
0
        public static void SendEmail(string smtpHost, Int32 smtpPort, string from, SecureString password, string to, string subject, string bodyEmail, bool isDkimEmail, string txtDKIMPath)
        {
            SmtpClient smtpClient = new SmtpClient();   //inicjalizacja klienta smtp z przestrzeni nazw MailKit.Net.Smtp

            try
            {
                smtpClient.Connect(smtpHost, smtpPort, SecureSocketOptions.StartTls); //łączymy się
            }
            catch (SmtpCommandException ex)                                           //obsługa wyjątku
            {
                Console.WriteLine("~~Cannot connect with client (SMTP Command Exception): {0}~~", ex.ToString());
                Environment.Exit(1);
            }
            catch (SmtpProtocolException ex)    //obsługa wyjątku
            {
                Console.WriteLine("~~Cannot connect with client (SMTP Protocol Exception): {0}~~", ex.ToString());
                Environment.Exit(1);
            }

            try
            {
                smtpClient.Authenticate(from, new NetworkCredential(string.Empty, password).Password);
            }
            catch (AuthenticationException ex)  //obsługa wyjątku
            {
                Console.WriteLine("~~Authentication error (Authentication Exception): {0}~~", ex.ToString());
                Environment.Exit(1);
            }
            catch (SmtpCommandException ex) //obsługa wyjątku
            {
                Console.WriteLine("~~Authentication error (SMTP Command Exception): {0}~~", ex.ToString());
                Environment.Exit(1);
            }
            catch (SmtpProtocolException ex)    //obsługa wyjątku
            {
                Console.WriteLine("~~Authentication error (SMTP Protocol Exception): {0}~~", ex.ToString());
                Environment.Exit(1);
            }


            smtpClient.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
            MimeMessage mimeMessage = new MimeMessage();    //inicjalizujemy obiekt mailMessage

            if (isDkimEmail)
            {
                string domain = from.Split("@")[1];

                HeaderId[] headers = new HeaderId[] { HeaderId.From, HeaderId.Subject, HeaderId.Date };
                DkimSigner signer  = new DkimSigner(txtDKIMPath, domain, "mail", DkimSignatureAlgorithm.RsaSha256)
                {
                    HeaderCanonicalizationAlgorithm = DkimCanonicalizationAlgorithm.Relaxed,
                    BodyCanonicalizationAlgorithm   = DkimCanonicalizationAlgorithm.Relaxed,
                    AgentOrUserIdentifier           = "@" + domain,
                    QueryMethod = "dns/txt",
                };

                //message.Prepare(EncodingConstraint.SevenBit);
                //message.Prepare(EncodingConstraint.EightBit);

                signer.Sign(mimeMessage, headers);
            }

            mimeMessage.From.Add(new MailboxAddress(from));     //od kogo e-mail
            mimeMessage.To.Add(new MailboxAddress(from));       //do kogo
            mimeMessage.Subject = subject;                      //temat
            BodyBuilder bodyBuilder = new BodyBuilder();        //bodyBuilder do tworzenia treści e-maila

            bodyBuilder.TextBody = bodyEmail;                   //tekst treści
            mimeMessage.Body     = bodyBuilder.ToMessageBody(); //wrzucenie tekstu bodyBuildera do treści e-maila
            try
            {
                smtpClient.Send(mimeMessage); //wysyłanie e-maila
            }
            catch (SmtpCommandException ex)   //obsługa wyjątku
            {
                Console.WriteLine("~~E-mail has not been sent (SMTP Command Exception): {0}", ex.Message);
                Environment.Exit(1);
            }
            catch (SmtpProtocolException ex)    //obsługa wyjątku
            {
                Console.WriteLine("~~E-mail has not been sent (SMTP Protocol Exception): {0}", ex.Message);
                Environment.Exit(1);
            }
            Console.WriteLine("~~E-mail sent~~");
            smtpClient.Disconnect(true);
        }
Beispiel #15
0
        public void SendSignedEmail()
        {
            var message = new MailMessage();



            message.To.Add(new MailAddress("*****@*****.**", "Port25"));



            message.From = new MailAddress(ConfigurationManager.AppSettings["from"]);

            message.Subject = @"test©";
            // message contains white space
//            message.Body = @"abc©
// ©   ©
// ©
//
//
//";

//            message.IsBodyHtml = false;


//            message.Body = @"
//line 1
//
//line 2
//
//line 3";


            message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("text", Encoding.ASCII, "text/plain"));
            message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("html", Encoding.ASCII, "text/html"));



            var privateKey = PrivateKeySigner.Create(ConfigurationManager.AppSettings["privatekey"], SigningAlgorithm.RSASha1);

            var dkim = new DkimSigner(
                privateKey,
                ConfigurationManager.AppSettings["domain"],
                ConfigurationManager.AppSettings["selector"],
                new string[] { "From", "To", "Subject" }
                );



            var debugger = new ConsoleDebug();

            dkim.Debug                = debugger;
            dkim.Encoding             = Encoding.ASCII;
            dkim.BodyCanonicalization = DkimCanonicalizationAlgorithm.Relaxed;



            var signedMessage = dkim.SignMessage(message);


            var text = signedMessage.GetText();

            debugger.WriteLine();
            debugger.WriteContent("dkim", text);



            //    var domainkey = new DomainKeySigner(
            //privateKey,
            //ConfigurationManager.AppSettings["domain"],
            //ConfigurationManager.AppSettings["selector"],
            //new string[] { "From", "To", "Subject" }
            //);

            //signedMessage = domainkey.SignMessage(signedMessage);

            //text = signedMessage.GetText();
            //debugger.WriteContent("domainkey", text);

            new SmtpClient().Send(signedMessage);
        }
Beispiel #16
0
		public void SendSignedEmail()
		{
			var message = new MailMessage();


			
			message.To.Add(new MailAddress("*****@*****.**", "Port25"));
			


			message.From = new MailAddress(ConfigurationManager.AppSettings["from"]);

			message.Subject = @"test©";
			// message contains white space 
//            message.Body = @"abc©
// ©   ©
// ©
//
//
//";

//            message.IsBodyHtml = false;


//            message.Body = @"
//line 1
//
//line 2
//
//line 3";


			message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("text", Encoding.ASCII, "text/plain"));
			message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("html", Encoding.ASCII, "text/html"));



			var privateKey = PrivateKeySigner.Create(ConfigurationManager.AppSettings["privatekey"], SigningAlgorithm.RSASha1);

			var dkim = new DkimSigner(
				privateKey,
				ConfigurationManager.AppSettings["domain"],
				ConfigurationManager.AppSettings["selector"],
				new string[] { "From", "To", "Subject" }
				);



			var debugger = new ConsoleDebug();

			dkim.Debug = debugger;
			dkim.Encoding = Encoding.ASCII;
			dkim.BodyCanonicalization = DkimCanonicalizationAlgorithm.Relaxed;



	

			

			var signedMessage = dkim.SignMessage(message);

			
			var text = signedMessage.GetText();
			debugger.WriteLine();
			debugger.WriteContent("dkim", text);



		//    var domainkey = new DomainKeySigner(
		//privateKey,
		//ConfigurationManager.AppSettings["domain"],
		//ConfigurationManager.AppSettings["selector"],
		//new string[] { "From", "To", "Subject" }
		//);

			//signedMessage = domainkey.SignMessage(signedMessage);
			
			//text = signedMessage.GetText();
			//debugger.WriteContent("domainkey", text);

			new SmtpClient().Send(signedMessage);

		}
Beispiel #17
0
        public MailDemonService(string[] args, IConfiguration configuration)
        {
            IConfigurationSection rootSection = configuration.GetSection("mailDemon");

            Domain = (rootSection["domain"] ?? Domain);
            ip     = (string.IsNullOrWhiteSpace(rootSection["ip"]) ? IPAddress.Any : IPAddress.Parse(rootSection["ip"]));
            port   = rootSection.GetValue("port", port);
            maxFailuresPerIPAddress = rootSection.GetValue("maxFailuresPerIPAddress", maxFailuresPerIPAddress);
            maxConnectionCount      = rootSection.GetValue("maxConnectionCount", maxConnectionCount);
            maxMessageSize          = rootSection.GetValue("maxMessageSize", maxMessageSize);
            globalForwardAddress    = rootSection.GetValue("globalForwardAddress", globalForwardAddress);
            greeting = (rootSection["greeting"] ?? greeting).Replace("\r", string.Empty).Replace("\n", string.Empty);
            if (TimeSpan.TryParse(rootSection["failureLockoutTimespan"], out TimeSpan _failureLockoutTimespan))
            {
                failureLockoutTimespan = _failureLockoutTimespan;
            }
            failureLockoutTimespan = _failureLockoutTimespan;
            IConfigurationSection userSection = rootSection.GetSection("users");

            foreach (var child in userSection.GetChildren())
            {
                MailDemonUser user = new MailDemonUser(child["name"], child["displayName"], child["password"], child["address"], child["forwardAddress"], true);
                users.Add(user);
                MailDemonLog.Debug("Loaded user {0}", user);
            }
            requireEhloIpHostMatch = rootSection.GetValue <bool>("requireEhloIpHostMatch", requireEhloIpHostMatch);
            requireSpfMatch        = rootSection.GetValue <bool>("requireSpfMatch", requireSpfMatch);
            string dkimFile     = rootSection.GetValue <string>("dkimPemFile", null);
            string dkimSelector = rootSection.GetValue <string>("dkimSelector", null);

            if (File.Exists(dkimFile) && !string.IsNullOrWhiteSpace(dkimSelector))
            {
                try
                {
                    using (StringReader stringReader = new StringReader(File.ReadAllText(dkimFile)))
                    {
                        PemReader pemReader = new PemReader(stringReader);
                        object    pemObject = pemReader.ReadObject();
                        AsymmetricKeyParameter privateKey = ((AsymmetricCipherKeyPair)pemObject).Private;
                        dkimSigner = new DkimSigner(privateKey, Domain, dkimSelector);
                        MailDemonLog.Info("Loaded dkim file at {0}", dkimFile);
                    }
                }
                catch (Exception ex)
                {
                    MailDemonLog.Error(ex);
                }
            }
            sslCertificateFile           = rootSection["sslCertificateFile"];
            sslCertificatePrivateKeyFile = rootSection["sslCertificatePrivateKeyFile"];
            if (!string.IsNullOrWhiteSpace(sslCertificateFile))
            {
                sslCertificatePassword = (rootSection["sslCertificatePassword"] ?? string.Empty).ToSecureString();
            }
            TestSslCertificate();
            IConfigurationSection ignoreRegexSection = rootSection.GetSection("ignoreCertificateErrorsRegex");

            if (ignoreRegexSection != null)
            {
                foreach (var child in ignoreRegexSection.GetChildren())
                {
                    Regex re = new Regex(child["regex"].ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Singleline);
                    foreach (var domain in child.GetSection("domains").GetChildren())
                    {
                        ignoreCertificateErrorsRegex[domain.Value] = re;
                    }
                }
            }
        }
Beispiel #18
0
        /// <summary>
        /// Create a MimMessage so MailKit can send it
        /// </summary>
        /// <returns>The mail message.</returns>
        /// <param name="email">Email data.</param>
        private MimeMessage CreateMailMessage(IFluentEmail email)
        {
            var data = email.Data;

            var message = new MimeMessage();

            // fixes https://github.com/lukencode/FluentEmail/issues/228
            // if for any reason, subject header is not added, add it else update it.
            if (!message.Headers.Contains(HeaderId.Subject))
            {
                message.Headers.Add(HeaderId.Subject, Encoding.UTF8, data.Subject ?? string.Empty);
            }
            else
            {
                message.Headers[HeaderId.Subject] = data.Subject ?? string.Empty;
            }

            message.Headers.Add(HeaderId.Encoding, Encoding.UTF8.EncodingName);

            message.From.Add(new MailboxAddress(data.FromAddress.Name, data.FromAddress.EmailAddress));

            var builder = new BodyBuilder();

            if (!string.IsNullOrEmpty(data.PlaintextAlternativeBody))
            {
                builder.TextBody = data.PlaintextAlternativeBody;
                builder.HtmlBody = data.Body;
            }
            else if (!data.IsHtml)
            {
                builder.TextBody = data.Body;
            }
            else
            {
                builder.HtmlBody = data.Body;
            }

            data.Attachments.ForEach(x =>
            {
                MimeEntity attachment;
                if (x.Data != null)
                {
                    attachment = builder.Attachments.Add(x.Filename, x.Data, ContentType.Parse(x.ContentType));
                }
                else
                {
                    attachment = builder.Attachments.Add(x.Filename, x.DataBuffer, ContentType.Parse(x.ContentType));
                }

                attachment.ContentId = x.ContentId;
            });


            message.Body = builder.ToMessageBody();

            foreach (var header in data.Headers)
            {
                message.Headers.Add(header.Key, header.Value);
            }

            data.ToAddresses.ForEach(x =>
            {
                message.To.Add(new MailboxAddress(x.Name, x.EmailAddress));
            });

            data.CcAddresses.ForEach(x =>
            {
                message.Cc.Add(new MailboxAddress(x.Name, x.EmailAddress));
            });

            data.BccAddresses.ForEach(x =>
            {
                message.Bcc.Add(new MailboxAddress(x.Name, x.EmailAddress));
            });

            data.ReplyToAddresses.ForEach(x =>
            {
                message.ReplyTo.Add(new MailboxAddress(x.Name, x.EmailAddress));
            });

            switch (data.Priority)
            {
            case Priority.Low:
                message.Priority = MessagePriority.NonUrgent;
                break;

            case Priority.Normal:
                message.Priority = MessagePriority.Normal;
                break;

            case Priority.High:
                message.Priority = MessagePriority.Urgent;
                break;
            }

            if (_smtpClientOptions.Dkim != null && _smtpClientOptions.Dkim.Sign)
            {
                HeaderId[] headersToSign = new HeaderId[] { HeaderId.From, HeaderId.Subject, HeaderId.Date };

                DkimSigner signer = new DkimSigner(_smtpClientOptions.Dkim.Key, _smtpClientOptions.Dkim.Domain, _smtpClientOptions.Dkim.Selector)
                {
                    SignatureAlgorithm = DkimSignatureAlgorithm.RsaSha256,
                    HeaderCanonicalizationAlgorithm = DkimCanonicalizationAlgorithm.Relaxed,
                    BodyCanonicalizationAlgorithm   = DkimCanonicalizationAlgorithm.Relaxed,
                    AgentOrUserIdentifier           = $"@{_smtpClientOptions.Dkim.Domain}",
                    QueryMethod = "dns/txt",
                };

                message.Prepare(EncodingConstraint.EightBit);
                signer.Sign(message, headersToSign);
            }

            return(message);
        }