Example #1
0
        internal OpenPgpDigitalCertificate(PgpPublicKey pubkey)
        {
            var data    = pubkey.GetFingerprint();
            var builder = new StringBuilder();

            for (int i = 0; i < data.Length; i++)
            {
                builder.Append(data[i].ToString("X"));
            }

//			var trust = pubkey.GetTrustData ();
//			if (trust != null) {
//				TrustLevel = (TrustLevel) (trust[0] & 15);
//			} else {
//				TrustLevel = TrustLevel.None;
//			}

            Fingerprint = builder.ToString();
            PublicKey   = pubkey;

            foreach (string userId in pubkey.GetUserIds())
            {
                data = Encoding.UTF8.GetBytes(userId);
                InternetAddress address;
                int             index = 0;

                if (!InternetAddress.TryParse(ParserOptions.Default, data, ref index, data.Length, false, out address))
                {
                    continue;
                }

                Name = address.Name;

                var mailbox = address as MailboxAddress;
                if (mailbox == null)
                {
                    continue;
                }

                Email = mailbox.Address;
                break;
            }
        }
Example #2
0
        public static void SendEmail(InternetAddress to, string subject, string body)
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(Config.Read().Email.FromName, Config.Read().Email.FromAddress));
            message.To.Add(to);
            message.Subject = subject;
            message.Body    = new TextPart("plain")
            {
                Text = body
            };

            using (var client = new SmtpClient()) {
                client.CheckCertificateRevocation = false; // Linux 不写就用不了
                client.Connect(Config.Read().Email.SmtpHost, Config.Read().Email.SmtpPort, true);
                client.Authenticate(Config.Read().Email.SmtpUsername, Config.Read().Email.SmtpPassword);
                client.Send(message);
                client.Disconnect(true);
            }
        }
Example #3
0
        public void Send(InternetAddress from, InternetAddress to, GpgPrivateKeyInfo senderKey, GpgPublicKeyInfo recipientKey, string subject, Multipart content)
        {
            _log.Verbose("Sending message to {0}", to);

            try
            {
                var client = new SmtpClient();
                client.SslProtocols = System.Security.Authentication.SslProtocols.None;
                client.Connect(_config.MailServerHost, _config.MailServerPort);
                client.Authenticate(_config.MailAccountName, _config.MailAccountPassword);
                _log.Verbose("Connected to mail server {0}:{1}", _config.MailServerHost, _config.MailServerPort);

                if (senderKey != null && recipientKey != null)
                {
                    content = EncryptAndSign(content, senderKey, recipientKey);
                }
                else if (recipientKey != null)
                {
                    content = Encrypt(content, senderKey);
                }
                else if (senderKey != null)
                {
                    content = Sign(content, senderKey);
                }

                var message = new MimeMessage();
                message.From.Add(from);
                message.To.Add(to);
                message.Subject = subject;
                message.Body    = content;
                client.Send(message);

                _log.Info("Message sent to {0}", to);
            }
            catch (Exception exception)
            {
                _log.Error("Error sending mail to {0}", to);
                _log.Error(exception.ToString());
                throw exception;
            }
        }
Example #4
0
        private static IEnumerable <MimeMessage> MakeMessages(string email, int num)
        {
            var messages = new List <MimeMessage>();
            var random   = new Random();

            for (int i = 0; i < num; i++)
            {
                var message = new MimeMessage {
                    Subject = Phrases[0][random.Next(Phrases[0].Count)],
                    Body    = new BodyBuilder {
                        HtmlBody = GenerateText(random)
                    }.ToMessageBody()
                };
                message.From.Add(InternetAddress.Parse(
                                     $"{Names[random.Next(Names.Count)]} <{ConfigurationManager.AppSettings["Sender"]}>"));
                message.To.Add(InternetAddress.Parse(email));
                messages.Add(message);
            }

            return(messages);
        }
Example #5
0
        private static void AddAddresses(MimeMessage message, string[] addresses, Func <MimeMessage, InternetAddressList> addressListGetter, bool throwIfNoneValid = false)
        {
            var foundValid = false;

            if (addresses != null)
            {
                foreach (var address in addresses)
                {
                    if (InternetAddress.TryParse(address, out InternetAddress internetAddress))
                    {
                        addressListGetter(message).Add(internetAddress);
                        foundValid = true;
                    }
                }
            }

            if (throwIfNoneValid && foundValid == false)
            {
                throw new InvalidOperationException($"Email could not be sent. Could not parse a valid recipient address.");
            }
        }
Example #6
0
        /// <summary>
        /// Creates a simple MailMessage
        /// </summary>
        /// <param name="from">Mail from</param>
        /// <param name="to">Mail recipient</param>
        /// <param name="subject">Mail subject</param>
        /// <param name="body">Mail body</param>
        /// <exception cref="ArgumentException">Thrown if address could not be parsed.</exception>
        /// <returns>The created message.</returns>
        public static MimeMessage CreateMessage(string from, string to, string subject, string body)
        {
            if (!InternetAddress.TryParse(to, out var toAddress))
            {
                throw new ArgumentException("Could not parse recipient address.", nameof(to));
            }

            if (!InternetAddress.TryParse(from, out var fromAddress))
            {
                throw new ArgumentException("Could not parse sender address.", nameof(from));
            }

            return(new MimeMessage(
                       from: new[] { fromAddress },
                       to: new[] { toAddress },
                       subject: subject,
                       body: new TextPart(MimeKit.Text.TextFormat.Plain)
            {
                Text = body
            }));
        }
        private IEnumerable <MailboxAddress> FlattenInternetAddress(InternetAddress internetAddresses, int maxDepth, int currentDepth = 1)
        {
            if (currentDepth > maxDepth)
            {
                return new List <MailboxAddress> {
                }
            }
            ;

            if (internetAddresses.GetType().IsAssignableFrom(typeof(MailboxAddress)))
            {
                return(new List <MailboxAddress> {
                    (MailboxAddress)internetAddresses
                });
            }
            else
            {
                return(FlattenInternetAddress(internetAddresses, maxDepth, currentDepth));
            }
        }
    }
Example #8
0
        public void TestParseWhiteSpace()
        {
            try {
                InternetAddress.Parse("   ");
                Assert.Fail("InternetAddress.Parse() should fail to parse whitespace.");
            } catch (ParseException ex) {
                Assert.AreEqual(3, ex.TokenIndex, "ParseException did not have the correct token index.");
                Assert.AreEqual(3, ex.ErrorIndex, "ParseException did not have the error index.");
            } catch {
                Assert.Fail("InternetAddress.Parse() should throw ParseException.");
            }

            try {
                InternetAddressList.Parse("   ");
                Assert.Fail("InternetAddressList.Parse() should fail to parse whitespace.");
            } catch (ParseException ex) {
                Assert.AreEqual(3, ex.TokenIndex, "ParseException did not have the correct token index.");
                Assert.AreEqual(3, ex.ErrorIndex, "ParseException did not have the error index.");
            } catch {
                Assert.Fail("InternetAddressList.Parse() should throw ParseException.");
            }
        }
Example #9
0
		/// <param name="mailInfo">
		/// 
		/// @return </param>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private static javax.mail.Message setCommon(MailSenderInfo mailInfo) throws javax.mail.MessagingException
		private static Message setCommon(MailSenderInfo mailInfo)
		{

			//
			// 判断是否需要身份认证
			//
			MyAuthenticator authenticator = null;
			Properties pro = mailInfo.Properties;
			if (mailInfo.Validate)
			{
				// 如果需要身份认证,则创建一个密码验证器
				authenticator = new MyAuthenticator(mailInfo.UserName, mailInfo.Password);
			}

			// 根据邮件会话属性和密码验证器构造一个发送邮件的session
			Session sendMailSession = Session.getDefaultInstance(pro, authenticator);

			// 根据session创建一个邮件消息
			Message mailMessage = new MimeMessage(sendMailSession);

			// 创建邮件发送者地址
			Address from = new InternetAddress(mailInfo.FromAddress);

			// 设置邮件消息的发送者
			mailMessage.From = from;

			// 创建邮件的接收者地址,并设置到邮件消息中
			Address to = new InternetAddress(mailInfo.ToAddress);
			mailMessage.setRecipient(Message.RecipientType.TO, to);

			// 设置邮件消息的主题
			mailMessage.Subject = mailInfo.Subject;

			// 设置邮件消息发送的时间
			mailMessage.SentDate = DateTime.Now;

			return mailMessage;

		}
Example #10
0
    public static MimeMessage Forward(MimeMessage original, MailboxAddress from, InternetAddress to)
    {
        var message = new MimeMessage();

        message.From.Add(from);
        message.To.Add(to);

        // set the forwarded subject
        if (!original.Subject.StartsWith("FW:", StringComparison.OrdinalIgnoreCase))
        {
            message.Subject = "FW: " + original.Subject;
        }
        else
        {
            message.Subject = original.Subject;
        }

        // create the main textual body of the message
        var text = new TextPart("plain")
        {
            Text = transcribedMessage
        };

        // create the message/rfc822 attachment for the original message
        var rfc822 = new MessagePart {
            Message = original
        };

        // create a multipart/mixed container for the text body and the forwarded message
        var multipart = new Multipart("mixed");

        multipart.Add(text);
        multipart.Add(rfc822);

        // set the multipart as the body of the message
        message.Body = multipart;

        return(message);
    }
        private async Task <string> SendTestEmail(SmtpService service, string email)
        {
            try
            {
                await service.SendEmail(new MimeMessage(new List <InternetAddress>()
                {
                    InternetAddress.Parse(email)
                }, new List <InternetAddress>()
                {
                    InternetAddress.Parse(email)
                }, "BTCTransmuter Test Email", new TextPart(TextFormat.Plain)
                {
                    Text = "Just testing your email setup for BTC Transmuter (ノ◕ヮ◕)ノ*:・゚✧"
                }));

                return(null);
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
Example #12
0
        private static async Task <DbModel.Message> GetTestMessage1()
        {
            MimeMessage message = new MimeMessage();

            message.From.Add(InternetAddress.Parse("*****@*****.**"));
            message.To.Add(InternetAddress.Parse("*****@*****.**"));
            message.Cc.Add(InternetAddress.Parse("*****@*****.**"));

            message.Subject = "subject";
            BodyBuilder bodyBuilder = new BodyBuilder();

            bodyBuilder.HtmlBody = "<html>Hi</html>";
            bodyBuilder.TextBody = "Hi";
            bodyBuilder.Attachments.Add("file1", new MemoryStream(System.Text.Encoding.UTF8.GetBytes(testMessage1File1Content)), new ContentType("text", "plain")).ContentId = "file1";
            bodyBuilder.Attachments.Add("file2", new MemoryStream(System.Text.Encoding.UTF8.GetBytes(testMessage1File2Content)), new ContentType("text", "plain"));

            message.Body = bodyBuilder.ToMessageBody();

            var dbMessage = await new MessageConverter().ConvertAsync(
                new MemoryStream(Encoding.UTF8.GetBytes(message.ToString())), "*****@*****.**", "*****@*****.**");

            return(dbMessage);
        }
Example #13
0
		/// <summary>
		/// 发送html邮件
		/// </summary>
		/// <exception cref="MessagingException"> </exception>
		/// <exception cref="AddressException"> </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void sendHtmlMail(String from, String[] to, String title, String text) throws javax.mail.internet.AddressException, javax.mail.MessagingException
		public virtual void sendHtmlMail(string from, string[] to, string title, string text)
		{

			long start = DateTimeHelperClass.CurrentUnixTimeMillis();

			MimeMessage mimeMessage = mailSender.createMimeMessage();
			MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "GBK");

			InternetAddress[] toArray = new InternetAddress[to.Length];
			for (int i = 0; i < to.Length; i++)
			{
				toArray[i] = new InternetAddress(to[i]);
			}

			messageHelper.From = new InternetAddress(from);
			messageHelper.To = toArray;
			messageHelper.Subject = title;
			messageHelper.setText(text, true);
			mimeMessage = messageHelper.MimeMessage;
			mailSender.send(mimeMessage);
			long end = DateTimeHelperClass.CurrentUnixTimeMillis();
			LOG.info("send mail start:" + start + " end :" + end);
		}
Example #14
0
        public MimeMessage Create(InternetAddress from, InternetAddress to, GpgPrivateKeyInfo senderKey, GpgPublicKeyInfo recipientKey, string subject, Multipart content)
        {
            if (senderKey != null && recipientKey != null)
            {
                content = EncryptAndSign(content, senderKey, recipientKey);
            }
            else if (recipientKey != null)
            {
                content = Encrypt(content, recipientKey);
            }
            else if (senderKey != null)
            {
                content = Sign(content, senderKey);
            }

            var message = new MimeMessage();

            message.From.Add(from);
            message.To.Add(to);
            message.Subject = subject;
            message.Body    = content;

            return(message);
        }
Example #15
0
        private static List <InternetAddress> ParseInternetAddresses(string internetAddresses)

        {
            var result = new List <InternetAddress>();


            if (!string.IsNullOrWhiteSpace(internetAddresses))
            {
                foreach (var mailAddress in internetAddresses.Split(';'))

                {
                    var s = mailAddress.Trim();

                    InternetAddress resultItem;

                    if (InternetAddress.TryParse(s, out resultItem))
                    {
                        result.Add(resultItem);
                    }
                }
            }

            return(result);
        }
Example #16
0
        private void DhcpDiscover(DhcpMessage message)
        {
            Byte[] addressRequestData = message.GetOptionData(DhcpOption.AddressRequest);
            if (addressRequestData == null)
            {
                addressRequestData = message.ClientAddress;
            }

            InternetAddress addressRequest = new InternetAddress(addressRequestData);

            // Assume we're on an ethernet network
            Byte[] hardwareAddressData = new Byte[6];
            Array.Copy(message.ClientHardwareAddress, hardwareAddressData, 6);
            PhysicalAddress clientHardwareAddress = new PhysicalAddress(hardwareAddressData);


            // If this client is explicitly allowed, or they are not denied and the allow any flag is set
            if (this._mAcl.ContainsKey(clientHardwareAddress) && this._mAcl[clientHardwareAddress] ||
                !this._mAcl.ContainsKey(clientHardwareAddress) && this._mAllowAny)
            {
                this.SendOffer(message);
            }
            else
            {
                this.SendNak(message);
            }
        }
Example #17
0
        /// <summary>
        /// Parses a Message-Id header value.
        /// </summary>
        /// <remarks>
        /// Parses the Message-Id value, returning the addr-spec portion of the msg-id token.
        /// </remarks>
        /// <returns>The addr-spec portion of the msg-id token.</returns>
        /// <param name="buffer">The raw byte buffer to parse.</param>
        /// <param name="startIndex">The index into the buffer to start parsing.</param>
        /// <param name="length">The length of the buffer to parse.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="buffer"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
        /// a valid range in the byte array.
        /// </exception>
        public static string ParseMessageId(byte[] buffer, int startIndex, int length)
        {
            byte[] sentinels = { (byte)'>' };
            int    endIndex  = startIndex + length;
            int    index     = startIndex;
            string msgid;

            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            if (startIndex < 0 || startIndex > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("startIndex");
            }

            if (length < 0 || length > (buffer.Length - startIndex))
            {
                throw new ArgumentOutOfRangeException("length");
            }

            if (!ParseUtils.SkipCommentsAndWhiteSpace(buffer, ref index, endIndex, false))
            {
                return(null);
            }

            if (index >= endIndex)
            {
                return(null);
            }

            if (buffer[index] == '<')
            {
                // skip over the '<'
                index++;

                if (index >= endIndex)
                {
                    return(null);
                }
            }

            string localpart;

            if (!InternetAddress.TryParseLocalPart(buffer, ref index, endIndex, false, out localpart))
            {
                return(null);
            }

            if (index >= endIndex)
            {
                return(null);
            }

            if (buffer[index] == (byte)'>')
            {
                // The msgid token did not contain an @domain. Technically this is illegal, but for the
                // sake of maximum compatibility, I guess we have no choice but to accept it...
                return(localpart);
            }

            if (buffer[index] != (byte)'@')
            {
                // who the hell knows what we have here...
                return(null);
            }

            // skip over the '@'
            index++;

            if (!ParseUtils.SkipCommentsAndWhiteSpace(buffer, ref index, endIndex, false))
            {
                return(null);
            }

            if (index >= endIndex)
            {
                return(null);
            }

            if (buffer[index] == (byte)'>')
            {
                // The msgid token was in the form "<local-part@>". Technically this is illegal, but for
                // the sake of maximum compatibility, I guess we have no choice but to accept it...
                // https://github.com/jstedfast/MimeKit/issues/102
                return(localpart + "@");
            }

            string domain;

            if (!ParseUtils.TryParseDomain(buffer, ref index, endIndex, sentinels, false, out domain))
            {
                return(null);
            }

            msgid = localpart + "@" + domain;

            // Note: some Message-Id's are broken and in the form "<local-part@domain@domain>"
            // https://github.com/jstedfast/MailKit/issues/138
            while (index < endIndex && buffer[index] == (byte)'@')
            {
                index++;

                if (!ParseUtils.TryParseDomain(buffer, ref index, endIndex, sentinels, false, out domain))
                {
                    break;
                }

                msgid += "@" + domain;
            }

            return(msgid);
        }
Example #18
0
        /// <summary>
        /// Enumerates the message-id references such as those that can be found in
        /// the In-Reply-To or References header.
        /// </summary>
        /// <remarks>
        /// Incrementally parses Message-Ids (such as those from a References header
        /// in a MIME message) from the supplied buffer starting at the given index
        /// and spanning across the specified number of bytes.
        /// </remarks>
        /// <returns>The references.</returns>
        /// <param name="buffer">The raw byte buffer to parse.</param>
        /// <param name="startIndex">The index into the buffer to start parsing.</param>
        /// <param name="length">The length of the buffer to parse.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="buffer"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
        /// a valid range in the byte array.
        /// </exception>
        public static IEnumerable <string> EnumerateReferences(byte[] buffer, int startIndex, int length)
        {
            ParseUtils.ValidateArguments(buffer, startIndex, length);

            byte[] sentinels = { (byte)'>' };
            int    endIndex  = startIndex + length;
            int    index     = startIndex;
            string msgid;

            do
            {
                if (!ParseUtils.SkipCommentsAndWhiteSpace(buffer, ref index, endIndex, false))
                {
                    break;
                }

                if (index >= endIndex)
                {
                    break;
                }

                if (buffer[index] == '<')
                {
                    // skip over the '<'
                    index++;

                    if (index >= endIndex)
                    {
                        break;
                    }

                    string localpart;
                    if (!InternetAddress.TryParseLocalPart(buffer, ref index, endIndex, false, out localpart))
                    {
                        continue;
                    }

                    if (index >= endIndex)
                    {
                        break;
                    }

                    if (buffer[index] == (byte)'>')
                    {
                        // The msgid token did not contain an @domain. Technically this is illegal, but for the
                        // sake of maximum compatibility, I guess we have no choice but to accept it...
                        index++;

                        yield return(localpart);

                        continue;
                    }

                    if (buffer[index] != (byte)'@')
                    {
                        // who the hell knows what we have here... ignore it and continue on?
                        continue;
                    }

                    // skip over the '@'
                    index++;

                    if (!ParseUtils.SkipCommentsAndWhiteSpace(buffer, ref index, endIndex, false))
                    {
                        break;
                    }

                    if (index >= endIndex)
                    {
                        break;
                    }

                    if (buffer[index] == (byte)'>')
                    {
                        // The msgid token was in the form "<local-part@>". Technically this is illegal, but for
                        // the sake of maximum compatibility, I guess we have no choice but to accept it...
                        // https://github.com/jstedfast/MimeKit/issues/102
                        index++;

                        yield return(localpart + "@");

                        continue;
                    }

                    string domain;
                    if (!ParseUtils.TryParseDomain(buffer, ref index, endIndex, sentinels, false, out domain))
                    {
                        continue;
                    }

                    msgid = localpart + "@" + domain;

                    // Note: some Message-Id's are broken and in the form "<local-part@domain@domain>"
                    // https://github.com/jstedfast/MailKit/issues/138
                    while (index < endIndex && buffer[index] == (byte)'@')
                    {
                        int saved = index;

                        index++;

                        if (!ParseUtils.TryParseDomain(buffer, ref index, endIndex, sentinels, false, out domain))
                        {
                            index = saved;
                            break;
                        }

                        msgid += "@" + domain;
                    }

                    yield return(msgid);
                }
                else if (!ParseUtils.SkipWord(buffer, ref index, endIndex, false))
                {
                    index++;
                }
            } while (index < endIndex);

            yield break;
        }
Example #19
0
        public async Task <bool> Send(Email emailToSend, string login, string pass)
        {
            var           emailMessage = new MimeMessage();
            List <string> emptyList    = new List <string>();

            string emailLogin = login == null ? "*****@*****.**" : login;

            List <string> emailTo  = !string.IsNullOrEmpty(emailToSend.Receiver) ? emailToSend.Receiver.Split(';').ToList() : emptyList;
            List <string> emailCc  = !string.IsNullOrEmpty(emailToSend.CarbonCopy) ? emailToSend.CarbonCopy.Split(';').ToList() : emptyList;
            List <string> emailBcc = !string.IsNullOrEmpty(emailToSend.BlindCarbonCopy) ? emailToSend.BlindCarbonCopy.Split(';').ToList() : emptyList;


            emailMessage.From.Add(new MailboxAddress(emailLogin));
            emailMessage.To.Add(new MailboxAddress(emailTo[0]));


            if (emailTo.Count > 1)
            {
                List <InternetAddress> lists = new List <InternetAddress>();
                foreach (var email in emailTo.Skip(1))
                {
                    lists.Add(InternetAddress.Parse(email));
                    emailMessage.To.AddRange(lists);
                }
            }

            if (emailCc.Any())
            {
                emailMessage.Cc.Add(new MailboxAddress(emailCc[0]));

                if (emailCc.Count > 1)
                {
                    List <InternetAddress> lists = new List <InternetAddress>();
                    foreach (var email in emailCc.Skip(1))
                    {
                        lists.Add(InternetAddress.Parse(email));
                        emailMessage.Cc.AddRange(lists);
                    }
                }
            }


            if (emailBcc.Any())
            {
                emailMessage.Cc.Add(new MailboxAddress(emailBcc[0]));

                if (emailBcc.Count > 1)
                {
                    List <InternetAddress> lists = new List <InternetAddress>();
                    foreach (var email in emailBcc.Skip(1))
                    {
                        lists.Add(InternetAddress.Parse(email));
                        emailMessage.Cc.AddRange(lists);
                    }
                }
            }

            emailMessage.Subject = emailToSend.Subject;
            emailMessage.Body    = new TextPart("plain")
            {
                Text = emailToSend.Message
            };

            try
            {
                using (var client = new SmtpClient())
                {
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    await client.ConnectAsync("smtp.gmail.com", 587);

                    if (string.IsNullOrEmpty(pass))
                    {
                        await client.AuthenticateAsync("*****@*****.**", "PawelNa100%");
                    }
                    else
                    {
                        await client.AuthenticateAsync(emailLogin, pass);
                    }

                    await client.SendAsync(emailMessage);

                    await client.DisconnectAsync(true);
                }
                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Example #20
0
        private void DhcpDiscover(DhcpMessage message)
        {
            Byte[] addressRequestData = message.GetOptionData(DhcpOption.AddressRequest);
            if (addressRequestData == null)
            {
                addressRequestData = message.ClientAddress;
            }

            InternetAddress addressRequest = new InternetAddress(addressRequestData);

            // Assume we're on an ethernet network
            Byte[] hardwareAddressData = new Byte[6];
            Array.Copy(message.ClientHardwareAddress, hardwareAddressData, 6);
            PhysicalAddress clientHardwareAddress = new PhysicalAddress(hardwareAddressData);

            AddressLease offer = null;

            // If this client is explicitly allowed, or they are not denied and the allow any flag is set
            if (this.m_Acl.ContainsKey(clientHardwareAddress) && this.m_Acl[clientHardwareAddress] ||
                !this.m_Acl.ContainsKey(clientHardwareAddress) && this.m_AllowAny)
            {
                if (this.m_Reservations.ContainsKey(clientHardwareAddress))
                {
                    offer = new AddressLease(clientHardwareAddress, this.m_Reservations[clientHardwareAddress], DateTime.Now.Add(this.m_LeaseDuration));
                }
                else
                {
                    lock (this.m_LeaseSync)
                    {
                        if (!addressRequest.Equals(InternetAddress.Empty))
                        {
                            if (this.m_InactiveLeases.ContainsKey(addressRequest))
                            {
                                offer = this.m_InactiveLeases[addressRequest];
                                this.m_InactiveLeases.Remove(addressRequest);
                                this.m_ActiveLeases.Add(addressRequest, offer);
                            }
                            else if (this.m_ActiveLeases.ContainsKey(addressRequest) && this.m_ActiveLeases[addressRequest].Owner.Equals(clientHardwareAddress))
                            {
                                offer = this.m_ActiveLeases[addressRequest];
                            }
                        }
                        else if (this.m_InactiveLeases.Count > 0)
                        {
                            offer = this.m_InactiveLeases.Values[0];
                            this.m_InactiveLeases.Remove(offer.Address);
                            this.m_ActiveLeases.Add(offer.Address, offer);
                        }
                    }
                }
            }

            if (offer == null)
            {
                this.SendNak(message);
            }
            else
            {
                offer.Acknowledged = false;
                offer.Expiration = DateTime.Now.Add(this.m_OfferTimeout);
                offer.SessionId = message.SessionId;
                offer.Owner = clientHardwareAddress;
                this.SendOffer(message, offer);
            }
        }
Example #21
0
 public void Send(InternetAddress from, InternetAddress to, string subject, Multipart content)
 {
     Send(Create(from, to, subject, content));
 }
Example #22
0
 private static void AddEmailRecipient(MimeMessage message, InternetAddress to)
 {
     message.To.Add(to);
 }
Example #23
0
 public void Send(InternetAddress to, GpgPrivateKeyInfo senderKey, GpgPublicKeyInfo recipientKey, string subject, Multipart content)
 {
     Send(new MailboxAddress(Global.Config.SystemMailAddress), to, senderKey, recipientKey, subject, content);
 }
Example #24
0
        /// <summary>
        /// Enumerates the message-id references such as those that can be found in
        /// the In-Reply-To or References header.
        /// </summary>
        /// <remarks>
        /// Incrementally parses Message-Ids (such as those from a References header
        /// in a MIME message) from the supplied buffer starting at the given index
        /// and spanning across the specified number of bytes.
        /// </remarks>
        /// <returns>The references.</returns>
        /// <param name="buffer">The raw byte buffer to parse.</param>
        /// <param name="startIndex">The index into the buffer to start parsing.</param>
        /// <param name="length">The length of the buffer to parse.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="buffer"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
        /// a valid range in the byte array.
        /// </exception>
        public static IEnumerable <string> EnumerateReferences(byte[] buffer, int startIndex, int length)
        {
            byte[]          sentinels = { (byte)'>' };
            int             endIndex  = startIndex + length;
            int             index     = startIndex;
            InternetAddress addr;
            string          msgid;

            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            if (startIndex < 0 || startIndex > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("startIndex");
            }

            if (length < 0 || length > (buffer.Length - startIndex))
            {
                throw new ArgumentOutOfRangeException("length");
            }

            do
            {
                if (!ParseUtils.SkipCommentsAndWhiteSpace(buffer, ref index, endIndex, false))
                {
                    break;
                }

                if (index >= endIndex)
                {
                    break;
                }

                if (buffer[index] == '<')
                {
                    if (!InternetAddress.TryParseMailbox(ParserOptions.Default, buffer, startIndex, ref index, endIndex, "", 65001, false, out addr))
                    {
                        break;
                    }

                    msgid = ((MailboxAddress)addr).Address;

                    // Note: some message-id's are broken and in the form local-part@domain@domain
                    // https://github.com/jstedfast/MailKit/issues/138
                    while (index < endIndex && buffer[index] == (byte)'@')
                    {
                        int    saved = index;
                        string domain;

                        index++;

                        if (!ParseUtils.TryParseDomain(buffer, ref index, endIndex, sentinels, false, out domain))
                        {
                            index = saved;
                            break;
                        }

                        msgid += "@" + domain;
                    }

                    yield return(msgid);
                }
                else if (!ParseUtils.SkipWord(buffer, ref index, endIndex, false))
                {
                    index++;
                }
            } while (index < endIndex);

            yield break;
        }
Example #25
0
        static bool TryParse(string text, ref int index, out InternetAddress addr)
        {
            string     name, route, user, domain;
            DomainList domains;

            addr = null;

            if (text[index] != '(')
            {
                return(false);
            }

            index++;

            if (!TryParse(text, ref index, out name))
            {
                return(false);
            }

            if (!TryParse(text, ref index, out route))
            {
                return(false);
            }

            if (!TryParse(text, ref index, out user))
            {
                return(false);
            }

            if (!TryParse(text, ref index, out domain))
            {
                return(false);
            }

            while (index < text.Length && text[index] == ' ')
            {
                index++;
            }

            if (index >= text.Length || text[index] != ')')
            {
                return(false);
            }

            index++;

            if (domain != null)
            {
                var address = user + "@" + domain;

                if (route != null && DomainList.TryParse(route, out domains))
                {
                    addr = new MailboxAddress(name, domains, address);
                }
                else
                {
                    addr = new MailboxAddress(name, address);
                }
            }
            else if (user != null)
            {
                addr = new GroupAddress(user);
            }

            return(true);
        }
Example #26
0
 public OnNewDHCPClientEvent(String mac_, InternetAddress ip_)
 {
     mac = mac_;
     ip = ip_;
 }
Example #27
0
 void removeReservation(PhysicalAddress pf, InternetAddress ip)
 {
     m_Reservations.Remove(pf);
     if (!ip.IsEmpty)
     {
         AddressLease offer = this.m_InactiveLeases.Values[0];
         offer.Address = ip;
         this.m_ActiveLeases.Add(offer.Address, offer);
     }
 }
Example #28
0
        private void DhcpRequest(DhcpMessage message)
        {
            Byte[] addressRequestData = message.GetOptionData(DhcpOption.AddressRequest);
            if (addressRequestData == null)
            {
                addressRequestData = message.ClientAddress;
            }

            InternetAddress addressRequest = new InternetAddress(addressRequestData);

            if (addressRequest.IsEmpty)
            {
                this.SendNak(message);
                return;
            }

            // Assume we're on an ethernet network
            Byte[] hardwareAddressData = new Byte[6];
            Array.Copy(message.ClientHardwareAddress, hardwareAddressData, 6);
            PhysicalAddress clientHardwareAddress = new PhysicalAddress(hardwareAddressData);

            AddressLease assignment = null;
            Boolean ack = false;

            // If this client is explicitly allowed, or they are not denied and the allow any flag is set
            if (this.m_Acl.ContainsKey(clientHardwareAddress) && this.m_Acl[clientHardwareAddress] ||
                !this.m_Acl.ContainsKey(clientHardwareAddress) && this.m_AllowAny)
            {
                if (this.m_Reservations.ContainsKey(clientHardwareAddress))
                {
                    assignment = new AddressLease(clientHardwareAddress, this.m_Reservations[clientHardwareAddress], DateTime.Now.Add(this.m_LeaseDuration));
                    if (addressRequest.Equals(assignment.Address))
                    {
                        ack = true;
                    }
                }
                else
                {
                    lock (this.m_LeaseSync)
                    {
                        if (this.m_ActiveLeases.ContainsKey(addressRequest) &&
                            (this.m_ActiveLeases[addressRequest].Owner.Equals(clientHardwareAddress) || this.m_ActiveLeases[addressRequest].SessionId == message.SessionId))
                        {
                            assignment = this.m_ActiveLeases[addressRequest];
                            assignment.Acknowledged = true;
                            assignment.Owner = clientHardwareAddress;
                            assignment.Expiration = DateTime.Now.Add(this.m_LeaseDuration);
                            ack = true;
                        }
                    }
                }
            }

            if (ack)
            {
                this.SendAck(message, assignment);
            }
            else
            {
                this.SendNak(message);
            }
        }
Example #29
0
 public void Send(InternetAddress from, InternetAddress to, GpgPrivateKeyInfo senderKey, GpgPublicKeyInfo recipientKey, string subject, Multipart content)
 {
     Send(Create(from, to, senderKey, recipientKey, subject, content));
 }
Example #30
0
        private async Task SendEmailSmtpAsync(ReadyEmail email)
        {
            var smtp = _emailOptions.SmtpServer;

            if (smtp == null || smtp.Accounts.Length == 0)
            {
                return;
            }

            SmtpAccount?account = null;

            if (string.IsNullOrEmpty(email.From))
            {
                account = smtp.Accounts[0];
            }
            else
            {
                foreach (var a in smtp.Accounts)
                {
                    if (string.Equals(a.Address, email.From, StringComparison.OrdinalIgnoreCase))
                    {
                        account = a;
                    }
                }
            }

            if (account == null)
            {
                _logger.LogError("No smtp user configured for address '{address}'", email.From);
                return;
            }

            var from = email.From ?? account.Address ?? account.Username;

            try
            {
                using var client = new SmtpClient();

                var sso = Enum.Parse <SecureSocketOptions>(smtp.Mode);
                await client.ConnectAsync(smtp.Host, smtp.Port, sso);

                var creds = new NetworkCredential(account.Username, account.Password);
                await client.AuthenticateAsync(new SaslMechanismLogin(creds));

                var message = new MimeMessage();

                message.From.Add(InternetAddress.Parse(from));
                message.To.Add(InternetAddress.Parse(email.To));
                message.Cc.AddRange(Array.ConvertAll(email.Cc, InternetAddress.Parse));
                message.Bcc.AddRange(Array.ConvertAll(email.Bcc, InternetAddress.Parse));

                message.Subject = email.Subject;
                message.Body    = new TextPart(TextFormat.Html)
                {
                    Text = email.Html
                };

                await client.SendAsync(message);

                await client.DisconnectAsync(true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Unable to send email {event} from {from} to {to}",
                                 email.EventName, from, email.To);
            }
        }
Example #31
0
        static void Main(string[] args)
        {
            DhcpServerConfigurationSection dhcpConfig = ConfigurationManager.GetSection("dhcpServer") as DhcpServerConfigurationSection;
            DhcpServer server = new DhcpServer();

            if (dhcpConfig != null)
            {
                if (dhcpConfig != null)
                {
                    if (dhcpConfig.NetworkInterface >= 0)
                    {
                        server.DhcpInterface = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[dhcpConfig.NetworkInterface];
                    }

                    server.StartAddress  = InternetAddress.Parse(dhcpConfig.StartAddress.Trim());
                    server.EndAddress    = InternetAddress.Parse(dhcpConfig.EndAddress.Trim());
                    server.Subnet        = InternetAddress.Parse(dhcpConfig.Subnet.Trim());
                    server.Gateway       = InternetAddress.Parse(dhcpConfig.Gateway.Trim());
                    server.LeaseDuration = dhcpConfig.LeaseDuration;
                    server.OfferTimeout  = dhcpConfig.OfferTimeout;
                    server.DnsSuffix     = dhcpConfig.DnsSuffix;

                    server.StartAddress = InternetAddress.Parse("2.0.4.1");
                    server.EndAddress   = InternetAddress.Parse("2.0.4.10");
                    server.Subnet       = InternetAddress.Parse("255.255.255.0");

                    foreach (InternetAddressElement dnsServer in dhcpConfig.DnsServers)
                    {
                        server.DnsServers.Add(InternetAddress.Parse(dnsServer.IPAddress.Trim()));
                    }

                    foreach (PhysicalAddressElement macAllow in dhcpConfig.MacAllowList)
                    {
                        if (macAllow.PhysicalAddress.Trim() == "*")
                        {
                            server.ClearAcls();
                            server.AllowAny = true;
                            break;
                        }
                        else
                        {
                            server.AddAcl(PhysicalAddress.Parse(macAllow.PhysicalAddress), false);
                        }
                    }

                    foreach (PhysicalAddressElement macDeny in dhcpConfig.MacDenyList)
                    {
                        if (macDeny.PhysicalAddress.Trim() == "*")
                        {
                            server.ClearAcls();
                            server.AllowAny = false;
                            break;
                        }
                        else
                        {
                            server.AddAcl(PhysicalAddress.Parse(macDeny.PhysicalAddress), true);
                        }
                    }

                    foreach (PhysicalAddressMappingElement macReservation in dhcpConfig.MacReservationList)
                    {
                        server.addReservation(macReservation.PhysicalAddress, macReservation.IPAddress);
                    }
                }

                server.Start();
                Console.WriteLine("DHCP Service Running.");
                Console.WriteLine("Hit [Enter] to Terminate.");

                Console.ReadLine();
            }
        }
 /// <summary>
 /// Get domain from an email address
 /// </summary>
 /// <param name="emailAddress">Email address</param>
 /// <returns>Domain</returns>
 public static string GetDomain(this InternetAddress emailAddress)
 {
     return(emailAddress.ToString().GetDomainFromEmailAddress());
 }
Example #33
0
 public bool IsInRange(InternetAddress address)
 {
     return IsInRange(address.IpAddress);
 }
        public async Task SendPromoAsync(string subject, string emailBody, IEnumerable <string> allEmails)
        {
            var from = new MailboxAddress("De las Artes", _sender);

            InternetAddress address;
            var             destination = new List <KeyValuePair <InternetAddress, string> >();

            if (_env.IsProduction())
            {
                destination.AddRange(allEmails.Where(x => InternetAddress.TryParse(x, out address))
                                     .Select(x => new KeyValuePair <InternetAddress, string>(InternetAddress.Parse(x), x)));
            }
            else
            {
                destination.Add(new KeyValuePair <InternetAddress, string>(from, _sender));
            }


            foreach (KeyValuePair <InternetAddress, string> email in destination)
            {
                var msg = new MimeMessage();
                msg.From.Add(from);
                msg.To.Add(email.Key);
                msg.Subject = subject;
                var uniqueBody = emailBody.Replace("#emailunsubscribe#", email.Value);
                msg.Body = (new BodyBuilder()
                {
                    HtmlBody = uniqueBody
                }).ToMessageBody();
                await SendMailAsync(msg);
            }
        }
Example #35
0
 public void Send(InternetAddress to, string subject, Multipart content)
 {
     Send(to, null, null, subject, content);
 }
Example #36
0
 public AddressLease(PhysicalAddress owner, InternetAddress address)
     : this(owner, address, DateTime.Now.AddDays(1))
 {
 }
Example #37
0
 public AddressLease(PhysicalAddress owner, InternetAddress address, DateTime expiration)
 {
     this.m_Owner = owner;
     this.m_Address = address;
     this.m_Expiration = expiration;
 }
Example #38
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(String[] args)
        {
            DhcpServerConfigurationSection dhcpConfig = ConfigurationManager.GetSection("dhcpServer") as DhcpServerConfigurationSection;
            DhcpServer server = new DhcpServer();

            if (dhcpConfig != null)
            {
                if (dhcpConfig.NetworkInterface >= 0)
                {
                    server.DhcpInterface = NetworkInterface.GetAllNetworkInterfaces()[dhcpConfig.NetworkInterface];
                }

                server.StartAddress  = InternetAddress.Parse(dhcpConfig.StartAddress.Trim());
                server.EndAddress    = InternetAddress.Parse(dhcpConfig.EndAddress.Trim());
                server.Subnet        = InternetAddress.Parse(dhcpConfig.Subnet.Trim());
                server.Gateway       = InternetAddress.Parse(dhcpConfig.Gateway.Trim());
                server.LeaseDuration = dhcpConfig.LeaseDuration;
                server.OfferTimeout  = dhcpConfig.OfferTimeout;
                server.DnsSuffix     = dhcpConfig.DnsSuffix;

                foreach (InternetAddressElement dnsServer in dhcpConfig.DnsServers)
                {
                    server.DnsServers.Add(InternetAddress.Parse(dnsServer.IPAddress.Trim()));
                }

                foreach (PhysicalAddressElement macAllow in dhcpConfig.MacAllowList)
                {
                    if (macAllow.PhysicalAddress.Trim() == "*")
                    {
                        server.ClearAcls();
                        server.AllowAny = true;
                        break;
                    }
                    else
                    {
                        server.AddAcl(PhysicalAddress.Parse(macAllow.PhysicalAddress), false);
                    }
                }

                foreach (PhysicalAddressElement macDeny in dhcpConfig.MacDenyList)
                {
                    if (macDeny.PhysicalAddress.Trim() == "*")
                    {
                        server.ClearAcls();
                        server.AllowAny = false;
                        break;
                    }
                    else
                    {
                        server.AddAcl(PhysicalAddress.Parse(macDeny.PhysicalAddress), true);
                    }
                }

                foreach (PhysicalAddressMappingElement macReservation in dhcpConfig.MacReservationList)
                {
                    server.addReservation(macReservation.PhysicalAddress, macReservation.IPAddress);
                }
            }

            if (args.Length > 0 && (ContainsSwitch(args, "console") || ContainsSwitch(args, "debug")))
            {
                if (ContainsSwitch(args, "debug"))
                {
                    Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
                }

                DhcpHost host = new DhcpHost(server);
                host.ManualStart(args);

                Console.WriteLine("DHCP Service Running.");
                Console.WriteLine("Hit [Enter] to Terminate.");

                Console.ReadLine();

                host.ManualStop();
            }
            else
            {
                ServiceBase[] ServicesToRun;

                ServicesToRun = new ServiceBase[] { new DhcpHost(server) };

                ServiceBase.Run(ServicesToRun);
            }
        }
 /// <summary>
 /// Gets the internet address as an MimeKit object.
 /// </summary>
 /// <param name="mailAddress">The mail address.</param>
 /// <returns>
 /// The email address as an MimeKit object.
 /// </returns>
 private static InternetAddress GetInternetAddress(MailAddress mailAddress)
 {
     return(InternetAddress.Parse(mailAddress.ToString()));
 }
Example #40
0
 public void Send(InternetAddress to, string subject, Multipart content)
 {
     Send(new MailboxAddress(_config.SystemMailAddress), to, subject, content);
 }