예제 #1
1
        public void TestEncodingMailboxWithArabicName()
        {
            var mailbox = new MailboxAddress ("هل تتكلم اللغة الإنجليزية /العربية؟", "*****@*****.**");
            var list = new InternetAddressList ();
            list.Add (mailbox);

            var expected = "=?utf-8?b?2YfZhCDYqtiq2YPZhNmFINin2YTZhNi62Kk=?=\n =?utf-8?b?INin2YTYpdmG2KzZhNmK2LLZitipIC/Yp9mE2LnYsdio2YrYqdif?=\n\t<*****@*****.**>";
            var actual = list.ToString (UnixFormatOptions, true);

            Assert.AreEqual (expected, actual, "Encoding arabic mailbox did not match expected result: {0}", expected);
            Assert.IsTrue (InternetAddressList.TryParse (actual, out list), "Failed to parse arabic mailbox");
            Assert.AreEqual (mailbox.Name, list[0].Name);
        }
예제 #2
0
		public void TestSimpleAddrSpec ()
		{
			var expected = new InternetAddressList ();
			var mailbox = new MailboxAddress ("", "");
			InternetAddressList result;
			string text;

			expected.Add (mailbox);

			text = "*****@*****.**";
			mailbox.Address = "*****@*****.**";
			Assert.IsTrue (InternetAddressList.TryParse (text, out result), "Failed to parse: {0}", text);
			AssertInternetAddressListsEqual (text, expected, result);

			result = InternetAddressList.Parse (text);
			AssertInternetAddressListsEqual (text, expected, result);

			text = "fejj";
			mailbox.Address = "fejj";
			Assert.IsTrue (InternetAddressList.TryParse (text, out result), "Failed to parse: {0}", text);
			AssertInternetAddressListsEqual (text, expected, result);

			result = InternetAddressList.Parse (text);
			AssertInternetAddressListsEqual (text, expected, result);
		}
예제 #3
0
		internal MimeMessage (ParserOptions options, IEnumerable<Header> headers)
		{
			addresses = new Dictionary<string, InternetAddressList> (icase);
			Headers = new HeaderList (options);

			// initialize our address lists
			foreach (var name in StandardAddressHeaders) {
				var list = new InternetAddressList ();
				list.Changed += InternetAddressListChanged;
				addresses.Add (name, list);
			}

			references = new MessageIdList ();
			references.Changed += ReferencesChanged;
			inreplyto = null;

			Headers.Changed += HeadersChanged;

			// add all of our message headers...
			foreach (var header in headers) {
				if (header.Field.StartsWith ("Content-", StringComparison.OrdinalIgnoreCase))
					continue;

				Headers.Add (header);
			}
		}
예제 #4
0
		static void AssertParse (string text, string encoded, InternetAddressList expected)
		{
			var buffer = Encoding.UTF8.GetBytes (text);
			InternetAddressList result = null;

			try {
				result = InternetAddressList.Parse (text);
			} catch {
				Assert.Fail ("Parse(string): {0}", text);
			}
			AssertInternetAddressListsEqual (encoded, expected, result);

			try {
				result = InternetAddressList.Parse (buffer);
			} catch {
				Assert.Fail ("Parse(byte[]): {0}", text);
			}
			AssertInternetAddressListsEqual (encoded, expected, result);

			try {
				result = InternetAddressList.Parse (buffer, 0);
			} catch {
				Assert.Fail ("Parse(byte[], int): {0}", text);
			}
			AssertInternetAddressListsEqual (encoded, expected, result);

			try {
				result = InternetAddressList.Parse (buffer, 0, buffer.Length);
			} catch {
				Assert.Fail ("Parse(byte[], int, int): {0}", text);
			}
			AssertInternetAddressListsEqual (encoded, expected, result);
		}
예제 #5
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MailKit.Envelope"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="Envelope"/>.
		/// </remarks>
		public Envelope ()
		{
			From = new InternetAddressList ();
			Sender = new InternetAddressList ();
			ReplyTo = new InternetAddressList ();
			To = new InternetAddressList ();
			Cc = new InternetAddressList ();
			Bcc = new InternetAddressList ();
		}
예제 #6
0
		static void AssertInternetAddressListsEqual (string text, InternetAddressList expected, InternetAddressList result)
		{
			Assert.AreEqual (expected.Count, result.Count, "Unexpected number of addresses: {0}", text);

			for (int i = 0; i < expected.Count; i++) {
				Assert.AreEqual (expected.GetType (), result.GetType (),
				                 "Address #{0} differs in type: {1}", i, text);

				Assert.AreEqual (expected[i].ToString (), result[i].ToString (), "Display strings differ for {0}", text);
			}
		}
예제 #7
0
        public void TestDecodedMailboxHasCorrectCharsetEncoding()
        {
            var latin1 = Encoding.GetEncoding ("iso-8859-1");
            var mailbox = new MailboxAddress (latin1, "Kristoffer Brånemyr", "*****@*****.**");
            var list = new InternetAddressList ();
            list.Add (mailbox);

            var encoded = list.ToString (UnixFormatOptions, true);

            InternetAddressList parsed;
            Assert.IsTrue (InternetAddressList.TryParse (encoded, out parsed), "Failed to parse address");
            Assert.AreEqual (latin1.HeaderName, parsed[0].Encoding.HeaderName, "Parsed charset does not match");
        }
		static void AssertTryParse (string text, string encoded, InternetAddressList expected)
		{
			var buffer = Encoding.UTF8.GetBytes (text);
			InternetAddressList result;

			Assert.IsTrue (InternetAddressList.TryParse (text, out result), "TryParse(string): {0}", text);
			AssertInternetAddressListsEqual (encoded, expected, result);

			Assert.IsTrue (InternetAddressList.TryParse (buffer, out result), "TryParse(byte[]): {0}", text);
			AssertInternetAddressListsEqual (encoded, expected, result);

			Assert.IsTrue (InternetAddressList.TryParse (buffer, 0, out result), "TryParse(byte[], int): {0}", text);
			AssertInternetAddressListsEqual (encoded, expected, result);

			Assert.IsTrue (InternetAddressList.TryParse (buffer, 0, buffer.Length, out result), "TryParse(byte[] int, int): {0}", text);
			AssertInternetAddressListsEqual (encoded, expected, result);
		}
		public void TestArgumentExceptions ()
		{
			var mailbox = new MailboxAddress ("MimeKit Unit Tests", "*****@*****.**");
			var list = new InternetAddressList ();

			list.Add (new MailboxAddress ("Example User", "*****@*****.**"));

			Assert.Throws<ArgumentNullException> (() => new InternetAddressList (null));
			Assert.Throws<ArgumentNullException> (() => list.Add (null));
			Assert.Throws<ArgumentNullException> (() => list.AddRange (null));
			Assert.Throws<ArgumentNullException> (() => list.CompareTo (null));
			Assert.Throws<ArgumentNullException> (() => list.Contains (null));
			Assert.Throws<ArgumentNullException> (() => list.CopyTo (null, 0));
			Assert.Throws<ArgumentOutOfRangeException> (() => list.CopyTo (new InternetAddress[0], -1));
			Assert.Throws<ArgumentNullException> (() => list.IndexOf (null));
			Assert.Throws<ArgumentOutOfRangeException> (() => list.Insert (-1, mailbox));
			Assert.Throws<ArgumentNullException> (() => list.Insert (0, null));
			Assert.Throws<ArgumentNullException> (() => list.Remove (null));
			Assert.Throws<ArgumentOutOfRangeException> (() => list.RemoveAt (-1));
			Assert.Throws<ArgumentOutOfRangeException> (() => list[-1] = mailbox);
			Assert.Throws<ArgumentNullException> (() => list[0] = null);
		}
		public void TestObsoleteMailboxRoutingSyntax ()
		{
			const string text = "Routed Address <@route:[email protected]>";
			var expected = new InternetAddressList ();

			expected.Add (new MailboxAddress ("Routed Address", new [] { "route" }, "*****@*****.**"));

			AssertParseAndTryParse (text, text, expected);
		}
		public void TestMailboxWithDotsInTheName ()
		{
			const string encoded = "\"Nathaniel S. Borenstein\" <*****@*****.**>";
			const string text = "Nathaniel S. Borenstein <*****@*****.**>";
			var expected = new InternetAddressList ();

			expected.Add (new MailboxAddress ("Nathaniel S. Borenstein", "*****@*****.**"));

			AssertParseAndTryParse (text, encoded, expected);
		}
		public void TestLocalGroupWithoutSemicolon ()
		{
			const string text = "Local recipients: phil, joe, alex, bob";
			const string encoded = "Local recipients: phil, joe, alex, bob;";
			var expected = new InternetAddressList ();

			expected.Add (new GroupAddress ("Local recipients", new InternetAddress[] {
				new MailboxAddress ("", "phil"),
				new MailboxAddress ("", "joe"),
				new MailboxAddress ("", "alex"),
				new MailboxAddress ("", "bob"),
			}));

			AssertTryParse (text, encoded, expected);

			//Assert.Throws<ParseException> (() => InternetAddressList.Parse (text), "Parsing should have failed.");
		}
		public void TestMailboxesWithRfc2047EncodedNames ()
		{
			var expected = new InternetAddressList ();
			var mailbox = new MailboxAddress ("", "");
			string text;

			expected.Add (mailbox);

			mailbox.Name = "Kristoffer Brånemyr";
			mailbox.Address = "*****@*****.**";
			text = "=?iso-8859-1?q?Kristoffer_Br=E5nemyr?= <*****@*****.**>";
			AssertParseAndTryParse (text, "Kristoffer =?iso-8859-1?q?Br=E5nemyr?= <*****@*****.**>", expected);

			mailbox.Name = "François Pons";
			mailbox.Address = "*****@*****.**";
			text = "=?iso-8859-1?q?Fran=E7ois?= Pons <*****@*****.**>";
			AssertParseAndTryParse (text, text, expected);
		}
예제 #14
0
        static void ExtractRecipientTable(TnefReader reader, MimeMessage message)
        {
            var prop  = reader.TnefPropertyReader;
            var chars = new char[1024];
            var buf   = new byte[1024];

            // Note: The RecipientTable uses rows of properties...
            while (prop.ReadNextRow())
            {
                InternetAddressList list = null;
                string name = null, addr = null;

                while (prop.ReadNextProperty())
                {
                    var    type = prop.ValueType;
                    object value;

                    switch (prop.PropertyTag.Id)
                    {
                    case TnefPropertyId.RecipientType:
                        int recipientType = prop.ReadValueAsInt32();
                        switch (recipientType)
                        {
                        case 1: list = message.To; break;

                        case 2: list = message.Cc; break;

                        case 3: list = message.Bcc; break;

                        default:
                            Assert.Fail("Invalid recipient type.");
                            break;
                        }
                        //Console.WriteLine ("RecipientTable Property: {0} = {1}", prop.PropertyTag.Id, recipientType);
                        break;

                    case TnefPropertyId.TransmitableDisplayName:
                        if (string.IsNullOrEmpty(name))
                        {
                            name = prop.ReadValueAsString();
                            //Console.WriteLine ("RecipientTable Property: {0} = {1}", prop.PropertyTag.Id, name);
                        }
                        else
                        {
                            //Console.WriteLine ("RecipientTable Property: {0} = {1}", prop.PropertyTag.Id, prop.ReadValueAsString ());
                        }
                        break;

                    case TnefPropertyId.DisplayName:
                        name = prop.ReadValueAsString();
                        //Console.WriteLine ("RecipientTable Property: {0} = {1}", prop.PropertyTag.Id, name);
                        break;

                    case TnefPropertyId.EmailAddress:
                        if (string.IsNullOrEmpty(addr))
                        {
                            addr = prop.ReadValueAsString();
                            //Console.WriteLine ("RecipientTable Property: {0} = {1}", prop.PropertyTag.Id, addr);
                        }
                        else
                        {
                            //Console.WriteLine ("RecipientTable Property: {0} = {1}", prop.PropertyTag.Id, prop.ReadValueAsString ());
                        }
                        break;

                    case TnefPropertyId.SmtpAddress:
                        // The SmtpAddress, if it exists, should take precedence over the EmailAddress
                        // (since the SmtpAddress is meant to be used in the RCPT TO command).
                        addr = prop.ReadValueAsString();
                        //Console.WriteLine ("RecipientTable Property: {0} = {1}", prop.PropertyTag.Id, addr);
                        break;

                    case TnefPropertyId.Addrtype:
                        Assert.AreEqual(typeof(string), type);
                        value = prop.ReadValueAsString();
                        break;

                    case TnefPropertyId.Rowid:
                        Assert.AreEqual(typeof(int), type);
                        value = prop.ReadValueAsInt64();
                        break;

                    case TnefPropertyId.SearchKey:
                        Assert.AreEqual(typeof(byte[]), type);
                        value = prop.ReadValueAsBytes();
                        break;

                    case TnefPropertyId.SendRichInfo:
                        Assert.AreEqual(typeof(bool), type);
                        value = prop.ReadValueAsBoolean();
                        break;

                    case TnefPropertyId.DisplayType:
                        Assert.AreEqual(typeof(int), type);
                        value = prop.ReadValueAsInt16();
                        break;

                    case TnefPropertyId.SendInternetEncoding:
                        Assert.AreEqual(typeof(int), type);
                        value = prop.ReadValueAsBoolean();
                        break;

                    default:
                        Assert.Throws <ArgumentNullException> (() => prop.ReadTextValue(null, 0, chars.Length));
                        Assert.Throws <ArgumentOutOfRangeException> (() => prop.ReadTextValue(chars, -1, chars.Length));
                        Assert.Throws <ArgumentOutOfRangeException> (() => prop.ReadTextValue(chars, 0, -1));

                        Assert.Throws <ArgumentNullException> (() => prop.ReadRawValue(null, 0, buf.Length));
                        Assert.Throws <ArgumentOutOfRangeException> (() => prop.ReadRawValue(buf, -1, buf.Length));
                        Assert.Throws <ArgumentOutOfRangeException> (() => prop.ReadRawValue(buf, 0, -1));

                        if (type == typeof(int) || type == typeof(long) || type == typeof(bool) || type == typeof(double) || type == typeof(float))
                        {
                            Assert.Throws <InvalidOperationException> (() => prop.ReadValueAsString());
                            Assert.Throws <InvalidOperationException> (() => prop.ReadValueAsGuid());
                        }
                        else if (type == typeof(string))
                        {
                            Assert.Throws <InvalidOperationException> (() => prop.ReadValueAsBoolean());
                            Assert.Throws <InvalidOperationException> (() => prop.ReadValueAsDouble());
                            Assert.Throws <InvalidOperationException> (() => prop.ReadValueAsFloat());
                            Assert.Throws <InvalidOperationException> (() => prop.ReadValueAsInt16());
                            Assert.Throws <InvalidOperationException> (() => prop.ReadValueAsInt32());
                            Assert.Throws <InvalidOperationException> (() => prop.ReadValueAsInt64());
                            Assert.Throws <InvalidOperationException> (() => prop.ReadValueAsGuid());
                        }

                        value = prop.ReadValue();
                        //Console.WriteLine ("RecipientTable Property (unhandled): {0} = {1}", prop.PropertyTag.Id, value);
                        Assert.AreEqual(type, value.GetType(), "Unexpected value type for {0}: {1}", prop.PropertyTag, value.GetType().Name);
                        break;
                    }
                }

                Assert.IsNotNull(list, "The recipient type was never specified.");
                Assert.IsNotNull(addr, "The address was never specified.");

                if (list != null)
                {
                    list.Add(new MailboxAddress(name, addr));
                }
            }
        }
예제 #15
0
        protected override void Execute(NativeActivityContext context)
        {
            string             username    = Email.Get(context);    //发送端账号
            string             password    = Password.Get(context); //发送端密码(这个客户端重置后的密码)
            string             server      = Server.Get(context);   //邮件服务器
            Int32              port        = Port.Get(context);     //端口号
            Int32              counts      = Counts.Get(context);
            List <object>      configList  = new List <object>();
            Pop3Client         emailClient = new Pop3Client();
            List <MimeMessage> emails      = new List <MimeMessage>();


            string mailTopicKey    = MailTopicKey.Get(context);
            string mailSenderKey   = MailSenderKey.Get(context);
            string mailTextBodyKey = MailTextBodyKey.Get(context);

            try
            {
                emailClient.Connect(server, port, SecureConnection);
                emailClient.Authenticate(username, password);
                for (int i = emailClient.Count - 1, j = 0; i >= 0 && j < counts; i--, j++)
                {
                    MimeMessage message = emailClient.GetMessage(i);

                    InternetAddressList Sender = message.From;
                    string SenderStr           = Sender[0].Name;
                    string Topic = message.Subject;


                    if (mailTopicKey != null && mailTopicKey != "")
                    {
                        if (Topic == null || Topic == "")
                        {
                            j--;
                            continue;
                        }
                        if (!Topic.Contains(mailTopicKey))
                        {
                            j--;
                            continue;
                        }
                    }
                    if (mailSenderKey != null && mailSenderKey != "")
                    {
                        if (SenderStr == null || SenderStr == "")
                        {
                            j--;
                            continue;
                        }
                        if (!SenderStr.Contains(mailSenderKey))
                        {
                            j--;
                            continue;
                        }
                    }
                    if (mailTextBodyKey != null && mailTextBodyKey != "")
                    {
                        if (message.TextBody == null || message.TextBody == "")
                        {
                            j--;
                            continue;
                        }
                        if (!message.TextBody.Contains(mailTextBodyKey))
                        {
                            j--;
                            continue;
                        }
                    }

                    emails.Add(message);
                    if (DeleteMessages)
                    {
                        emailClient.DeleteMessage(i);
                    }
                }
                MailMsgList.Set(context, emails);
                emailClient.Disconnect(true);
            }
            catch (Exception e)
            {
                SharedObject.Instance.Output(SharedObject.enOutputType.Error, "获取POP3邮件失败", e.Message);
                emailClient.Disconnect(true);
            }


            configList.Add(server);
            configList.Add(port);
            configList.Add(SecureConnection);
            configList.Add(username);
            configList.Add(password);
            configList.Add("");

            if (Body != null)
            {
                object[] buff = configList.ToArray();
                context.ScheduleAction(Body, emails, emailClient, buff);
            }
        }
		public void TestEncodingMailboxWithJapaneseName ()
		{
			const string expected = "=?utf-8?b?54uC44Gj44Gf44GT44Gu5LiW44Gn54uC44GG44Gq44KJ5rCX44Gv56K644GL44Gg?=\n =?utf-8?b?44CC?= <*****@*****.**>";
			var mailbox = new MailboxAddress ("狂ったこの世で狂うなら気は確かだ。", "*****@*****.**");
			var list = new InternetAddressList ();
			list.Add (mailbox);

			var actual = list.ToString (UnixFormatOptions, true);

			Assert.AreEqual (expected, actual, "Encoding japanese mailbox did not match expected result: {0}", expected);
			Assert.IsTrue (InternetAddressList.TryParse (actual, out list), "Failed to parse japanese mailbox");
			Assert.AreEqual (mailbox.Name, list[0].Name);
		}
예제 #17
0
        static void ExtractRecipientTable(TnefReader reader, MimeMessage message)
        {
            var prop = reader.TnefPropertyReader;

            // Note: The RecipientTable uses rows of properties...
            while (prop.ReadNextRow())
            {
                InternetAddressList list = null;
                string name = null, addr = null;

                while (prop.ReadNextProperty())
                {
                    switch (prop.PropertyTag.Id)
                    {
                    case TnefPropertyId.RecipientType:
                        int recipientType = prop.ReadValueAsInt32();
                        switch (recipientType)
                        {
                        case 1: list = message.To; break;

                        case 2: list = message.Cc; break;

                        case 3: list = message.Bcc; break;

                        default:
                            Assert.Fail("Invalid recipient type.");
                            break;
                        }
                        //Console.WriteLine ("RecipientTable Property: {0} = {1}", prop.PropertyTag.Id, recipientType);
                        break;

                    case TnefPropertyId.TransmitableDisplayName:
                        if (string.IsNullOrEmpty(name))
                        {
                            name = prop.ReadValueAsString();
                            //Console.WriteLine ("RecipientTable Property: {0} = {1}", prop.PropertyTag.Id, name);
                        }
                        else
                        {
                            //Console.WriteLine ("RecipientTable Property: {0} = {1}", prop.PropertyTag.Id, prop.ReadValueAsString ());
                        }
                        break;

                    case TnefPropertyId.DisplayName:
                        name = prop.ReadValueAsString();
                        //Console.WriteLine ("RecipientTable Property: {0} = {1}", prop.PropertyTag.Id, name);
                        break;

                    case TnefPropertyId.EmailAddress:
                        if (string.IsNullOrEmpty(addr))
                        {
                            addr = prop.ReadValueAsString();
                            //Console.WriteLine ("RecipientTable Property: {0} = {1}", prop.PropertyTag.Id, addr);
                        }
                        else
                        {
                            //Console.WriteLine ("RecipientTable Property: {0} = {1}", prop.PropertyTag.Id, prop.ReadValueAsString ());
                        }
                        break;

                    case TnefPropertyId.SmtpAddress:
                        // The SmtpAddress, if it exists, should take precedence over the EmailAddress
                        // (since the SmtpAddress is meant to be used in the RCPT TO command).
                        addr = prop.ReadValueAsString();
                        //Console.WriteLine ("RecipientTable Property: {0} = {1}", prop.PropertyTag.Id, addr);
                        break;

                    default:
                        //Console.WriteLine ("RecipientTable Property (unhandled): {0} = {1}", prop.PropertyTag.Id, prop.ReadValue ());
                        break;
                    }
                }

                Assert.IsNotNull(list, "The recipient type was never specified.");
                Assert.IsNotNull(addr, "The address was never specified.");

                if (list != null)
                {
                    list.Add(new MailboxAddress(name, addr));
                }
            }
        }
예제 #18
0
 private void CopyRecips(List <EmailRecipient> recips, EmailRecipientType type, InternetAddressList outputList)
 {
     foreach (var recip in recips.Where(x => x.Type == type))
     {
         outputList.Add(new MailboxAddress(Encoding.UTF8, recip.Name, recip.Address));
     }
 }
예제 #19
0
        static bool TryParse(string text, ref int index, out InternetAddressList list)
        {
            MailboxAddress mailbox;

            list = null;

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

            if (index >= text.Length)
            {
                return(false);
            }

            if (text[index] != '(')
            {
                if (index + 3 <= text.Length && text.Substring(index, 3) == "NIL")
                {
                    list   = new InternetAddressList();
                    index += 3;
                    return(true);
                }

                return(false);
            }

            index++;

            if (index >= text.Length)
            {
                return(false);
            }

            list = new InternetAddressList();

            do
            {
                if (text[index] == ')')
                {
                    break;
                }

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

                list.Add(mailbox);

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

            if (index >= text.Length)
            {
                return(false);
            }

            index++;

            return(true);
        }
예제 #20
0
        /// <inheritdoc />
        public override string SendMail(MailInfo mailInfo, SmtpInfo smtpInfo = null)
        {
            // validate smtp server
            if (smtpInfo == null || string.IsNullOrEmpty(smtpInfo.Server))
            {
                if (string.IsNullOrWhiteSpace(Host.SMTPServer))
                {
                    return("SMTP Server not configured");
                }

                smtpInfo = new SmtpInfo
                {
                    Server         = Host.SMTPServer,
                    Authentication = Host.SMTPAuthentication,
                    Username       = Host.SMTPUsername,
                    Password       = Host.SMTPPassword,
                    EnableSSL      = Host.EnableSMTPSSL,
                };
            }

            var mailMessage = new MimeMessage();

            mailMessage.From.Add(ParseAddressWithDisplayName(displayName: mailInfo.FromName, address: mailInfo.From));
            if (!string.IsNullOrEmpty(mailInfo.Sender))
            {
                mailMessage.Sender = MailboxAddress.Parse(mailInfo.Sender);
            }

            // translate semi-colon delimiters to commas as ASP.NET 2.0 does not support semi-colons
            if (!string.IsNullOrEmpty(mailInfo.To))
            {
                mailInfo.To = mailInfo.To.Replace(";", ",");
                mailMessage.To.AddRange(InternetAddressList.Parse(mailInfo.To));
            }

            if (!string.IsNullOrEmpty(mailInfo.CC))
            {
                mailInfo.CC = mailInfo.CC.Replace(";", ",");
                mailMessage.Cc.AddRange(InternetAddressList.Parse(mailInfo.CC));
            }

            if (!string.IsNullOrEmpty(mailInfo.BCC))
            {
                mailInfo.BCC = mailInfo.BCC.Replace(";", ",");
                mailMessage.Bcc.AddRange(InternetAddressList.Parse(mailInfo.BCC));
            }

            if (!string.IsNullOrEmpty(mailInfo.ReplyTo))
            {
                mailInfo.ReplyTo = mailInfo.ReplyTo.Replace(";", ",");
                mailMessage.ReplyTo.AddRange(InternetAddressList.Parse(mailInfo.ReplyTo));
            }

            mailMessage.Priority = (MessagePriority)mailInfo.Priority;

            // Only modify senderAddress if smtpAuthentication is enabled
            // Can be "0", empty or Null - anonymous, "1" - basic, "2" - NTLM.
            if (smtpInfo.Authentication == "1" || smtpInfo.Authentication == "2")
            {
                // if the senderAddress is the email address of the Host then switch it smtpUsername if different
                // if display name of senderAddress is empty, then use Host.HostTitle for it
                if (mailMessage.Sender != null)
                {
                    var senderAddress     = mailInfo.Sender;
                    var senderDisplayName = mailInfo.FromName;
                    var needUpdateSender  = false;
                    if (smtpInfo.Username.Contains("@") && senderAddress == Host.HostEmail &&
                        !senderAddress.Equals(smtpInfo.Username, StringComparison.InvariantCultureIgnoreCase))
                    {
                        senderAddress    = smtpInfo.Username;
                        needUpdateSender = true;
                    }

                    if (string.IsNullOrEmpty(senderDisplayName))
                    {
                        senderDisplayName = Host.SMTPPortalEnabled ? PortalSettings.Current.PortalName : Host.HostTitle;
                        needUpdateSender  = true;
                    }

                    if (needUpdateSender)
                    {
                        mailMessage.Sender = ParseAddressWithDisplayName(displayName: senderDisplayName, address: senderAddress);
                    }
                }
                else if (smtpInfo.Username.Contains("@"))
                {
                    mailMessage.Sender = ParseAddressWithDisplayName(
                        displayName: Host.SMTPPortalEnabled ? PortalSettings.Current.PortalName : Host.HostTitle,
                        address: smtpInfo.Username);
                }
            }

            var builder = new BodyBuilder
            {
                TextBody = Mail.ConvertToText(mailInfo.Body),
            };

            if (mailInfo.BodyFormat == MailFormat.Html)
            {
                builder.HtmlBody = mailInfo.Body;
            }

            // attachments
            if (mailInfo.Attachments != null)
            {
                foreach (var attachment in mailInfo.Attachments.Where(attachment => attachment.Content != null))
                {
                    builder.Attachments.Add(attachment.Filename, attachment.Content, ContentType.Parse(attachment.ContentType));
                }
            }

            // message
            mailMessage.Subject = HtmlUtils.StripWhiteSpace(mailInfo.Subject, true);
            mailMessage.Body    = builder.ToMessageBody();

            smtpInfo.Server = smtpInfo.Server.Trim();

            if (!SmtpServerRegex.IsMatch(smtpInfo.Server))
            {
                return(Localize.GetString("SMTPConfigurationProblem"));
            }

            try
            {
                var smtpHostParts = smtpInfo.Server.Split(':');
                var host          = smtpHostParts[0];
                var port          = 25;

                if (smtpHostParts.Length > 1)
                {
                    // port is guaranteed to be of max 5 digits numeric by the RegEx check
                    port = int.Parse(smtpHostParts[1]);
                    if (port < 1 || port > 65535)
                    {
                        return(Localize.GetString("SmtpInvalidPort"));
                    }
                }

                // to workaround problem in 4.0 need to specify host name
                using (var smtpClient = new SmtpClient())
                {
                    smtpClient.Connect(host, port, SecureSocketOptions.Auto);

                    switch (smtpInfo.Authentication)
                    {
                    case "":
                    case "0":     // anonymous
                        break;

                    case "1":     // basic
                        if (!string.IsNullOrEmpty(smtpInfo.Username) &&
                            !string.IsNullOrEmpty(smtpInfo.Password))
                        {
                            smtpClient.Authenticate(smtpInfo.Username, smtpInfo.Password);
                        }

                        break;

                    case "2":     // NTLM (Not Supported by MailKit)
                        throw new NotSupportedException("NTLM authentication is not supported by MailKit provider");
                    }

                    smtpClient.Send(mailMessage);
                    smtpClient.Disconnect(true);
                }

                return(string.Empty);
            }
            catch (Exception exc)
            {
                var retValue = Localize.GetString("SMTPConfigurationProblem") + " ";

                // mail configuration problem
                if (exc.InnerException != null)
                {
                    retValue += string.Concat(exc.Message, Environment.NewLine, exc.InnerException.Message);
                    Exceptions.Exceptions.LogException(exc.InnerException);
                }
                else
                {
                    retValue += exc.Message;
                    Exceptions.Exceptions.LogException(exc);
                }

                return(retValue);
            }
        }
예제 #21
0
        public async Task <IActionResult> ConfirmOrderAsync(CheckoutViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.GetUserAsync(User);

                var cart      = _repository.GetCartByUserId(user.Id);
                var cartItem  = _repository.GetCartItemByCartId(cart.Id);
                var countries = _repository.GetCountries();
                model.Country = countries;
                cart.CartItem = cartItem;

                MimeMessage message = new MimeMessage();

                MailboxAddress from = new MailboxAddress("DevitoAnonymo porudžbina",
                                                         _configuration["from"]);
                message.From.Add(from);

                InternetAddressList list = new InternetAddressList();
                list.Add(new MailboxAddress(user.FirstName + " " + user.LastName, user.Email)); //user email
                list.Add(new MailboxAddress("MKOClothing", "*****@*****.**"));       //MKOClothing email
                list.Add(new MailboxAddress("DevitoAnonytmo office", "*****@*****.**"));    //davidov email
                message.To.AddRange(list);
                //--------------------------------------------
                message.Subject = "Nova porudžbina";

                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);


                var order = new Order
                {
                    Orderdate     = DateTime.Now,
                    User          = user,
                    PaymentMethod = model.PaymentMethod,
                    OrderNumber   = cart.Id + user.PhoneNumber + cart.CartItem.FirstOrDefault().Id + Math.Round((DateTime.Now.ToUniversalTime() - epoch).TotalSeconds)
                };

                var mailHtmlBody = "<h1>Porudžbina - DevitoAnonymo.com</h1><br/><hr/><table><tbody>" +
                                   "<tr><th>Broj porudžbine</th><td style='width: 200px'>" + order.OrderNumber + "</td></tr>" +
                                   "<tr><th>Ime</th><td style='width: 200px'>" + model.FirstName + "</td></tr>" +
                                   "<tr><th>Prezime</th><td style='width: 200px'>" + model.LastName + "</td></tr>" +
                                   "<tr><th>Adresa</th><td style='width: 200px'>" + model.Address + "</td></tr>" +
                                   "<tr><th>Poštanski broj</th><td style='width: 200px'>" + model.PostalNumber + "</td></tr>" +
                                   "<tr><th>Grad</th><td style='width: 200px'>" + model.City + "</td></tr>" +
                                   "<tr><th>Država</th><td style='width: 200px'>" + model.Country.SingleOrDefault(c => c.Id == model.CountryId).Title + "</td></tr>" +
                                   "<tr><th>Broj telefona</th><td style='width: 200px'>" + model.PhoneNumber + "</td></tr>";


                if (model.PaymentMethod == PaymentMethod.Pouzećem)
                {
                    mailHtmlBody += "<tr><th>Ukupna cena za naplatu: </th><td style='width: 200px'>" + cart.TotalPrice + " RSD</td></tr>";
                }
                else
                {
                    if (model.PaymentMethod == PaymentMethod.Paypal)
                    {
                        mailHtmlBody += "<tr><th>Ukupna cena za naplatu: </th><td style='width: 400px;color:green'>" + cart.TotalPrice + " RSD<strong> - PLAĆENO PUTEM PAYPAL-A</strong></td></tr>";
                    }
                }

                var orderItems = new List <OrderItem>();

                mailHtmlBody +=
                    "</tbody></table><hr/>" +
                    "<h3>Naručeni artikli: </h3><hr/>";
                foreach (var c in cart.CartItem)
                {
                    mailHtmlBody += "<table><tbody>" +
                                    "<tr><th>Broj artikla: </th><td style='width: 200px'>" + c.Product.ItemNumber + "</td></tr>" +
                                    "<tr><th>Naziv: </th><td style='width: 200px'>" + c.Product.Title + "</td></tr>" +
                                    "<tr><th>Veličina: </th><td style='width: 200px'>" + c.Size + "</td></tr>" +
                                    "<tr><th>Količina: </th><td style='width: 200px'>" + c.Quantity + "</td></tr>" +
                                    "</tbody></table><hr/>";



                    var orderItem = new OrderItem
                    {
                        Product   = c.Product,
                        Quantity  = c.Quantity,
                        Size      = c.Size,
                        UnitPrice = c.Product.Price
                    };

                    orderItems.Add(orderItem);
                }

                mailHtmlBody += "<br/><p><strong>Ukoliko postoji problem sa porudžbinom, javite se na email: [email protected]</strong></p>";

                order.OrderItems = orderItems;


                BodyBuilder bodyBuilder = new BodyBuilder();
                bodyBuilder.HtmlBody = mailHtmlBody;

                message.Body = bodyBuilder.ToMessageBody();

                SmtpClient client = new SmtpClient();
                await client.ConnectAsync(_configuration["mailHost"], 465, true);

                await client.AuthenticateAsync(_configuration["from"], _configuration["appPass"]);

                await client.SendAsync(message);

                await client.DisconnectAsync(true);

                client.Dispose();

                _repository.AddEntity(order);

                _repository.RemoveEntity(cart);

                if (_repository.SaveAll())
                {
                    _flashMessage.Confirmation("Uspešno ste poručili artikle. Na email vam je poslata priznanica sa detaljima porudžbine. ");
                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    _flashMessage.Warning("Greška pri obradi vašeg zahteva. ");
                    return(RedirectToAction("Index", "Home"));
                }
            }
            else
            {
                return(View(model));
            }
        }
예제 #22
0
        async Task ForUsersAsync(IQueryable <AppUser> qry, string subj, string body, string from, InternetAddressList replyTo, CancellationToken cancellationToken)
        {
            var page = 0;
            PagedList <AppUser> users;

            do
            {
                users = await qry.GetPageAsync(page ++, PAGE_SIZE);

                CreateDispatch(users, subj, body, from, replyTo, cancellationToken);
            } while (users.MorePages);
        }
예제 #23
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                //Console.WriteLine("Testing"+ _emailHelper.SenderEmail);
                return(Page());
            }

            var userMessage  = new BodyBuilder();
            var recipients   = COMPANY_EMAIL + ";" + FeedbackForm.UserEmailAddress;
            var emailSubject = "Pluto BV Website Feedback";

            InternetAddressList recipientList = new InternetAddressList();

            recipientList.Add(new MailboxAddress(FeedbackForm.UserEmailAddress));
            recipientList.Add(new MailboxAddress(COMPANY_EMAIL));

            var mimeMessage = new MimeMessage();

            mimeMessage.From.Add(new MailboxAddress(_emailHelper.SenderName, _emailHelper.SenderEmail));
            //mimeMessage.To.Add(new MailboxAddress(FeedbackForm.UserEmailAddress));
            mimeMessage.To.AddRange(recipientList);
            mimeMessage.Subject = emailSubject;

            StringBuilder sbEmailBody = new StringBuilder();

            try
            {
                if (_emailHelper.IsEmailEnabled == "YES")
                {
                    //To revisit this as this a feedback from website and not
                    //Append the collections from the form

                    userMessage.TextBody =
                        $@"Dear {FeedbackForm.UserName}
    
The following details were submitted successfully. A member of our team will be in touch soon: 
    
    
    Name:     {FeedbackForm.UserName};
    Postcode: {FeedbackForm.UserPostcode} 
    Email:    {FeedbackForm.UserEmailAddress}
    Phone:    {FeedbackForm.UserPhoneNumber}
    
    Message: {FeedbackForm.UserMessage}

    
    Thanks for the feedback...
    
    Kind Regards
    PlutoBvServices Ltd";


                    mimeMessage.Body = userMessage.ToMessageBody();

                    using (var client = new SmtpClient())
                    {
                        //for demo purposes, accept all the ssl certificates (incase server supports STARTTLS)
                        client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                        // The third parameter is useSSL (true if the client should make an SSL-wrapped
                        // connection to the server; otherwise, false).

                        await client.ConnectAsync(_emailHelper.Server, _emailHelper.Port);

                        // Note: only needed if the SMTP server requires authentication
                        await client.AuthenticateAsync(_emailHelper.SenderEmail, _emailHelper.Password);

                        await client.SendAsync(mimeMessage);

                        await client.DisconnectAsync(true);
                    }
                }

                else
                {
                    System.Console.WriteLine("NOt ENABLED");
                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            }



            ModelState.Clear();
            return(RedirectToPage("/Index")); // return  Page();
        }
		public void TestEncodingSimpleMailboxWithQuotedName ()
		{
			const string expected = "\"Stedfast, Jeffrey\" <*****@*****.**>";
			var mailbox = new MailboxAddress ("Stedfast, Jeffrey", "*****@*****.**");
			var list = new InternetAddressList ();
			list.Add (mailbox);

			var actual = list.ToString (UnixFormatOptions, true);

			Assert.AreEqual (expected, actual, "Encoding quoted mailbox did not match expected result: {0}", expected);
		}
		public void TestEncodingSimpleMailboxWithLatin1Name ()
		{
			var latin1 = Encoding.GetEncoding ("iso-8859-1");
			var mailbox = new MailboxAddress (latin1, "Kristoffer Brånemyr", "*****@*****.**");
			var list = new InternetAddressList ();
			list.Add (mailbox);

			var expected = "Kristoffer =?iso-8859-1?q?Br=E5nemyr?= <*****@*****.**>";
			var actual = list.ToString (UnixFormatOptions, true);

			Assert.AreEqual (expected, actual, "Encoding latin1 mailbox did not match expected result: {0}", expected);

			mailbox = new MailboxAddress (latin1, "Tõivo Leedjärv", "*****@*****.**");
			list = new InternetAddressList ();
			list.Add (mailbox);

			expected = "=?iso-8859-1?b?VIH1aXZvIExlZWRqgeRydg==?= <*****@*****.**>";
			actual = list.ToString (UnixFormatOptions, true);

			Assert.AreEqual (expected, actual, "Encoding latin1 mailbox did not match expected result: {0}", expected);
		}
예제 #26
0
 internal MailMessageBuilder WithToAddress(string email)
 {
     _inner.To.AddRange(InternetAddressList.Parse(email));
     return(this);
 }
		public void TestUnsupportedCharsetExceptionNotThrown ()
		{
			var mailbox = new MailboxAddress (Encoding.UTF8, "狂ったこの世で狂うなら気は確かだ。", "*****@*****.**");
			var list = new InternetAddressList ();
			list.Add (mailbox);

			var encoded = list.ToString (true);

			encoded = encoded.Replace ("utf-8", "x-unknown");

			InternetAddressList parsed;

			try {
				Assert.IsTrue (InternetAddressList.TryParse (encoded, out parsed), "Failed to parse address");
			} catch (Exception ex) {
				Assert.Fail ("Exception thrown parsing address with unsupported charset: {0}", ex);
			}
		}
예제 #28
0
파일: Envelope.cs 프로젝트: wxtech/MailKit
 static void EncodeAddressList(StringBuilder builder, InternetAddressList list)
 {
     builder.Append('(');
     EncodeInternetAddressListAddresses(builder, list);
     builder.Append(')');
 }
예제 #29
0
        protected override void Execute(NativeActivityContext context)
        {
            string username   = Email.Get(context);             //发送端账号
            string password   = Password.Get(context);          //发送端密码(这个客户端重置后的密码)
            string server     = Server.Get(context);            //邮件服务器
            Int32  port       = Port.Get(context);              //端口号
            Int32  counts     = Counts.Get(context);            //检索邮件数
            string mainFolder = MainFolder.Get(context);        //邮件文件夹

            string mailTopicKey    = MailTopicKey.Get(context);
            string mailSenderKey   = MailSenderKey.Get(context);
            string mailTextBodyKey = MailTextBodyKey.Get(context);

            List <object>      configList = new List <object>();
            List <MimeMessage> emails     = new List <MimeMessage>();
            ImapClient         client     = new ImapClient();
            SearchQuery        query;
            IList <UniqueId>   uidss;

            try
            {
                client.CheckCertificateRevocation          = false;
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                client.Connect(server, port, SecureConnection);
                client.Authenticate(username, password);

                if (OnlyUnreadMessages || _AllUnreadMessages)
                {
                    query = SearchQuery.NotSeen;
                }
                else
                {
                    query = SearchQuery.All;
                }

                List <IMailFolder> mailFolderList = client.GetFolders(client.PersonalNamespaces[0]).ToList();
                IMailFolder        folder         = client.GetFolder(mainFolder);
                folder.Open(FolderAccess.ReadWrite);
                emails = new List <MimeMessage>();
                if (_AllUnreadMessages)
                {
                    query = SearchQuery.NotSeen;
                    uidss = folder.Search(query);
                    for (int i = uidss.Count - 1; i >= 0; i--)
                    {
                        MimeMessage message = folder.GetMessage(new UniqueId(uidss[i].Id));
                        emails.Add(message);
                        if (MarkAsRead)
                        {
                            folder.AddFlags(new UniqueId(uidss[i].Id), MessageFlags.Seen, true);//如果设置为true,则不会发出MessageFlagsChanged事件
                        }
                        if (DeleteMessages)
                        {
                            folder.AddFlags(new UniqueId(uidss[i].Id), MessageFlags.Deleted, true);//如果设置为true,则不会发出MessageFlagsChanged事件
                        }
                    }
                }
                else
                {
                    uidss = folder.Search(query);
                    for (int i = uidss.Count - 1, j = 0; i >= 0 && j < counts; i--, j++)
                    {
                        MimeMessage message = folder.GetMessage(new UniqueId(uidss[i].Id));

                        InternetAddressList Sender = message.From;
                        string SenderStr           = Sender.Mailboxes.First().Address;
                        string Topic = message.Subject;
                        if (mailTopicKey != null && mailTopicKey != "")
                        {
                            if (Topic == null || Topic == "")
                            {
                                j--;
                                continue;
                            }
                            if (!Topic.Contains(mailTopicKey))
                            {
                                j--;
                                continue;
                            }
                        }
                        if (mailSenderKey != null && mailSenderKey != "")
                        {
                            if (SenderStr == null || SenderStr == "")
                            {
                                j--;
                                continue;
                            }
                            if (!SenderStr.Contains(mailSenderKey))
                            {
                                j--;
                                continue;
                            }
                        }
                        if (mailTextBodyKey != null && mailTextBodyKey != "")
                        {
                            if (message.TextBody == null || message.TextBody == "")
                            {
                                j--;
                                continue;
                            }
                            if (!message.TextBody.Contains(mailTextBodyKey))
                            {
                                j--;
                                continue;
                            }
                        }

                        emails.Add(message);
                        if (MarkAsRead)
                        {
                            folder.AddFlags(new UniqueId(uidss[i].Id), MessageFlags.Seen, true);//如果设置为true,则不会发出MessageFlagsChanged事件
                        }
                        if (DeleteMessages)
                        {
                            folder.AddFlags(new UniqueId(uidss[i].Id), MessageFlags.Deleted, true);//如果设置为true,则不会发出MessageFlagsChanged事件
                        }
                    }
                }

                //获取搜索结果的摘要信息(我们需要UID和BODYSTRUCTURE每条消息,以便我们可以提取文本正文和附件)(获取全部邮件)
                //var items = folder.Fetch(uidss, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure);
                MailMsgList.Set(context, emails);
                client.Disconnect(true);

                configList.Add(server);
                configList.Add(port);
                configList.Add(SecureConnection);
                configList.Add(username);
                configList.Add(password);
                configList.Add(mainFolder);
            }
            catch (Exception e)
            {
                client.Disconnect(true);
                SharedObject.Instance.Output(SharedObject.enOutputType.Error, "获取IMAP邮件失败", e.Message);
            }
            if (Body != null)
            {
                object[] buff = configList.ToArray();
                context.ScheduleAction(Body, emails, client, buff);
            }
        }
예제 #30
0
파일: Envelope.cs 프로젝트: wxtech/MailKit
        static bool TryParse(string text, ref int index, out InternetAddressList list)
        {
            list = null;

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

            if (index >= text.Length)
            {
                return(false);
            }

            if (text[index] != '(')
            {
                if (index + 3 <= text.Length && text.Substring(index, 3) == "NIL")
                {
                    list   = new InternetAddressList();
                    index += 3;
                    return(true);
                }

                return(false);
            }

            index++;

            if (index >= text.Length)
            {
                return(false);
            }

            list = new InternetAddressList();
            var stack = new List <InternetAddressList> ();
            int sp    = 0;

            stack.Add(list);

            do
            {
                if (text[index] == ')')
                {
                    break;
                }

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

                if (addr != null)
                {
                    var group = addr as GroupAddress;

                    stack[sp].Add(addr);

                    if (group != null)
                    {
                        stack.Add(group.Members);
                        sp++;
                    }
                }
                else if (sp > 0)
                {
                    stack.RemoveAt(sp);
                    sp--;
                }

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

            // Note: technically, we should check that sp == 0 as well, since all groups should
            // be popped off the stack, but in the interest of being liberal in what we accept,
            // we'll ignore that.
            if (index >= text.Length)
            {
                return(false);
            }

            index++;

            return(true);
        }
		public void TestSimpleMailboxes ()
		{
			var expected = new InternetAddressList ();
			var mailbox = new MailboxAddress ("", "");
			string text;

			expected.Add (mailbox);

			mailbox.Name = "Jeffrey Stedfast";
			mailbox.Address = "*****@*****.**";
			text = "Jeffrey Stedfast <*****@*****.**>";
			AssertParseAndTryParse (text, text, expected);

			mailbox.Name = "this is a folded name";
			mailbox.Address = "*****@*****.**";
			text = "this is\n\ta folded name <*****@*****.**>";
			AssertParseAndTryParse (text, "this is a folded name <*****@*****.**>", expected);

			mailbox.Name = "Jeffrey fejj Stedfast";
			mailbox.Address = "*****@*****.**";
			text = "Jeffrey \"fejj\" Stedfast <*****@*****.**>";
			AssertParseAndTryParse (text, "Jeffrey fejj Stedfast <*****@*****.**>", expected);

			mailbox.Name = "Jeffrey \"fejj\" Stedfast";
			mailbox.Address = "*****@*****.**";
			text = "\"Jeffrey \\\"fejj\\\" Stedfast\" <*****@*****.**>";
			AssertParseAndTryParse (text, text, expected);

			mailbox.Name = "Stedfast, Jeffrey";
			mailbox.Address = "*****@*****.**";
			text = "\"Stedfast, Jeffrey\" <*****@*****.**>";
			AssertParseAndTryParse (text, text, expected);

			mailbox.Name = "Jeffrey Stedfast";
			mailbox.Address = "*****@*****.**";
			text = "[email protected] (Jeffrey Stedfast)";
			AssertParseAndTryParse (text, "Jeffrey Stedfast <*****@*****.**>", expected);

			mailbox.Name = "Jeffrey Stedfast";
			mailbox.Address = "*****@*****.**";
			text = "Jeffrey Stedfast <fejj(recursive (comment) block)@helixcode.(and a comment here)com>";
			AssertParseAndTryParse (text, "Jeffrey Stedfast <*****@*****.**>", expected);

			mailbox.Name = "Jeffrey Stedfast";
			mailbox.Address = "*****@*****.**";
			text = "Jeffrey Stedfast <[email protected].>";
			AssertParseAndTryParse (text, "Jeffrey Stedfast <*****@*****.**>", expected);
		}
예제 #32
0
 static void AssertParseAndTryParse(string text, string encoded, InternetAddressList expected)
 {
     AssertTryParse(text, encoded, expected);
     AssertParse(text, encoded, expected);
 }
		public void TestListWithGroupAndAddrspec ()
		{
			const string text = "GNOME Hackers: Miguel de Icaza <*****@*****.**>, Havoc Pennington <*****@*****.**>;, [email protected]";
			const string encoded = "GNOME Hackers: Miguel de Icaza <*****@*****.**>, Havoc Pennington\n\t<*****@*****.**>;, [email protected]";
			var expected = new InternetAddressList ();

			expected.Add (new GroupAddress ("GNOME Hackers", new InternetAddress[] {
				new MailboxAddress ("Miguel de Icaza", "*****@*****.**"),
				new MailboxAddress ("Havoc Pennington", "*****@*****.**")
			}));
			expected.Add (new MailboxAddress ("", "*****@*****.**"));

			AssertParseAndTryParse (text, encoded, expected);
		}
예제 #34
0
        public void TestSimpleMailboxes()
        {
            var expected = new InternetAddressList();
            var mailbox  = new MailboxAddress("", "");
            InternetAddressList result;
            string text;

            expected.Add(mailbox);

            mailbox.Name    = "Jeffrey Stedfast";
            mailbox.Address = "*****@*****.**";
            text            = "Jeffrey Stedfast <*****@*****.**>";
            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);

            mailbox.Name    = "this is a folded name";
            mailbox.Address = "*****@*****.**";
            text            = "this is\n\ta folded name <*****@*****.**>";
            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);

            mailbox.Name    = "Jeffrey fejj Stedfast";
            mailbox.Address = "*****@*****.**";
            text            = "Jeffrey \"fejj\" Stedfast <*****@*****.**>";
            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);

            mailbox.Name    = "Jeffrey \"fejj\" Stedfast";
            mailbox.Address = "*****@*****.**";
            text            = "\"Jeffrey \\\"fejj\\\" Stedfast\" <*****@*****.**>";
            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);

            mailbox.Name    = "Stedfast, Jeffrey";
            mailbox.Address = "*****@*****.**";
            text            = "\"Stedfast, Jeffrey\" <*****@*****.**>";
            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);

            mailbox.Name    = "Jeffrey Stedfast";
            mailbox.Address = "*****@*****.**";
            text            = "[email protected] (Jeffrey Stedfast)";
            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);

            mailbox.Name    = "Jeffrey Stedfast";
            mailbox.Address = "*****@*****.**";
            text            = "Jeffrey Stedfast <fejj(recursive (comment) block)@helixcode.(and a comment here)com>";
            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);

            mailbox.Name    = "Jeffrey Stedfast";
            mailbox.Address = "*****@*****.**";
            text            = "Jeffrey Stedfast <[email protected].>";
            Assert.IsTrue(InternetAddressList.TryParse(text, out result), "Failed to parse: {0}", text);
            AssertInternetAddressListsEqual(text, expected, result);

            result = InternetAddressList.Parse(text);
            AssertInternetAddressListsEqual(text, expected, result);
        }
		public void TestExampleGroupWithCommentsFromRfc5322 ()
		{
			const string text = "A Group(Some people):Chris Jones <c@(Chris's host.)public.example>, [email protected], John <*****@*****.**> (my dear friend); (the end of the group)";
			const string encoded = "A Group: Chris Jones <*****@*****.**>, [email protected], John <*****@*****.**>;";
			var expected = new InternetAddressList ();

			expected.Add (new GroupAddress ("A Group", new InternetAddress[] {
				new MailboxAddress ("Chris Jones", "*****@*****.**"),
				new MailboxAddress ("", "*****@*****.**"),
				new MailboxAddress ("John", "*****@*****.**")
			}));

			AssertParseAndTryParse (text, encoded, expected);
		}
예제 #36
0
        static void AssertInternetAddressListsEqual(string text, InternetAddressList expected, InternetAddressList result)
        {
            Assert.AreEqual(expected.Count, result.Count, "Unexpected number of addresses: {0}", text);

            for (int i = 0; i < expected.Count; i++)
            {
                Assert.AreEqual(expected.GetType(), result.GetType(),
                                "Address #{0} differs in type: {1}", i, text);

                Assert.AreEqual(expected[i].ToString(), result[i].ToString(), "Display strings differ for {0}", text);
            }
        }
		public void TestMailboxWith8bitName ()
		{
			const string encoded = "Patrik =?iso-8859-1?b?RqVkbHRzdHKldm0=?= <*****@*****.**>";
			const string text = "Patrik F¥dltstr¥vm <*****@*****.**>";
			var expected = new InternetAddressList ();

			expected.Add (new MailboxAddress ("Patrik F¥dltstr¥vm", "*****@*****.**"));

			AssertParseAndTryParse (text, encoded, expected);
		}
예제 #38
0
        public void TestSorting()
        {
            var messages = new List <MessageSummary> ();
            IList <MessageSummary> sorted;
            MessageSummary         summary;

            summary                  = new MessageSummary(0);
            summary.Envelope         = new Envelope();
            summary.Envelope.Date    = DateTimeOffset.Now;
            summary.Envelope.Subject = "aaaa";
            summary.Envelope.From    = InternetAddressList.Parse("Jeffrey Stedfast <*****@*****.**>");
            summary.Envelope.To      = InternetAddressList.Parse("Jeffrey Stedfast <*****@*****.**>");
            summary.Envelope.Cc      = new InternetAddressList();
            summary.MessageSize      = 520;
            messages.Add(summary);

            summary                  = new MessageSummary(1);
            summary.Envelope         = new Envelope();
            summary.Envelope.Date    = DateTimeOffset.Now;
            summary.Envelope.Subject = "bbbb";
            summary.Envelope.From    = InternetAddressList.Parse("Jeffrey Stedfast <*****@*****.**>");
            summary.Envelope.To      = InternetAddressList.Parse("Jeffrey Stedfast <*****@*****.**>");
            summary.Envelope.Cc      = new InternetAddressList();
            summary.MessageSize      = 265;
            messages.Add(summary);

            summary                  = new MessageSummary(2);
            summary.Envelope         = new Envelope();
            summary.Envelope.Date    = DateTimeOffset.Now;
            summary.Envelope.Subject = "cccc";
            summary.Envelope.From    = InternetAddressList.Parse("Jeffrey Stedfast <*****@*****.**>");
            summary.Envelope.To      = InternetAddressList.Parse("Jeffrey Stedfast <*****@*****.**>");
            summary.Envelope.Cc      = new InternetAddressList();
            summary.MessageSize      = 520;
            messages.Add(summary);

            sorted = MessageSorter.Sort(messages, new [] { OrderBy.Arrival });
            Assert.AreEqual(0, sorted[0].Index, "Sorting by arrival failed.");
            Assert.AreEqual(1, sorted[1].Index, "Sorting by arrival failed.");
            Assert.AreEqual(2, sorted[2].Index, "Sorting by arrival failed.");

            sorted = MessageSorter.Sort(messages, new [] { OrderBy.ReverseArrival });
            Assert.AreEqual(2, sorted[0].Index, "Sorting by reverse arrival failed.");
            Assert.AreEqual(1, sorted[1].Index, "Sorting by reverse arrival failed.");
            Assert.AreEqual(0, sorted[2].Index, "Sorting by reverse arrival failed.");

            sorted = MessageSorter.Sort(messages, new [] { OrderBy.Subject });
            Assert.AreEqual(0, sorted[0].Index, "Sorting by subject failed.");
            Assert.AreEqual(1, sorted[1].Index, "Sorting by subject failed.");
            Assert.AreEqual(2, sorted[2].Index, "Sorting by subject failed.");

            sorted = MessageSorter.Sort(messages, new [] { OrderBy.ReverseSubject });
            Assert.AreEqual(2, sorted[0].Index, "Sorting by reverse subject failed.");
            Assert.AreEqual(1, sorted[1].Index, "Sorting by reverse subject failed.");
            Assert.AreEqual(0, sorted[2].Index, "Sorting by reverse subject failed.");

            sorted = MessageSorter.Sort(messages, new [] { OrderBy.Size });
            Assert.AreEqual(1, sorted[0].Index, "Sorting by size failed.");

            sorted = MessageSorter.Sort(messages, new [] { OrderBy.Size, OrderBy.Subject });
            Assert.AreEqual(1, sorted[0].Index, "Sorting by size+subject failed.");
            Assert.AreEqual(0, sorted[1].Index, "Sorting by size+subject failed.");
            Assert.AreEqual(2, sorted[2].Index, "Sorting by size+subject failed.");

            sorted = MessageSorter.Sort(messages, new [] { OrderBy.ReverseSize, OrderBy.ReverseSubject });
            Assert.AreEqual(2, sorted[0].Index, "Sorting by size+subject failed.");
            Assert.AreEqual(0, sorted[1].Index, "Sorting by size+subject failed.");
            Assert.AreEqual(1, sorted[2].Index, "Sorting by size+subject failed.");
        }
		public void TestObsoleteMailboxRoutingSyntaxWithEmptyDomains ()
		{
			const string text = "Routed Address <@route1,,@route2,,,@route3:[email protected]>";
			const string encoded = "Routed Address <@route1,@route2,@route3:[email protected]>";
			var expected = new InternetAddressList ();

			expected.Add (new MailboxAddress ("Routed Address", new [] { "route1", "route2", "route3" }, "*****@*****.**"));

			AssertParseAndTryParse (text, encoded, expected);
		}
예제 #40
0
        public async Task Send(string from, string fromEmail, string toEmail, string subject, string body, SmtpSettings smtpSettings, CancellationToken cancellationToken = default)
        {
            var msg = new MimeMessage(InternetAddressList.Parse($"{from} <{fromEmail}>"), InternetAddressList.Parse(toEmail), subject, new TextPart("html")
            {
                Text = body
            });

            using var client = new SmtpClient();
            using (var depTrack = _telemetryLogger.TrackDependency("Email", nameof(EmailSender), nameof(client.ConnectAsync))) {
                await client.ConnectAsync(smtpSettings.Server, smtpSettings.Port, smtpSettings.SecureSocketOptions, cancellationToken);

                depTrack.Success();
            }
            if (!string.IsNullOrWhiteSpace(smtpSettings.User))
            {
                using var depTrack = _telemetryLogger.TrackDependency("Email", nameof(EmailSender), nameof(client.AuthenticateAsync));
                await client.AuthenticateAsync(smtpSettings.User, smtpSettings.Password, cancellationToken);

                depTrack.Success();
            }
            using (var depTrack = _telemetryLogger.TrackDependency("Email", nameof(EmailSender), nameof(client.SendAsync))) {
                await client.SendAsync(msg, cancellationToken);

                depTrack.Success();
            }
            using (var depTrack = _telemetryLogger.TrackDependency("Email", nameof(EmailSender), nameof(client.DisconnectAsync))) {
                await client.DisconnectAsync(true, cancellationToken);

                depTrack.Success();
            }
        }
		public void TestCompareTo ()
		{
			var list1 = new InternetAddressList ();

			list1.Add (new GroupAddress ("Local recipients", new InternetAddress[] {
				new MailboxAddress ("", "phil"),
				new MailboxAddress ("", "joe"),
				new MailboxAddress ("", "alex"),
				new MailboxAddress ("", "bob"),
			}));
			list1.Add (new MailboxAddress ("Joey", "*****@*****.**"));
			list1.Add (new MailboxAddress ("Chandler", "*****@*****.**"));

			var list2 = new InternetAddressList ();

			list2.Add (new MailboxAddress ("Chandler", "*****@*****.**"));
			list2.Add (new GroupAddress ("Local recipients", new InternetAddress[] {
				new MailboxAddress ("", "phil"),
				new MailboxAddress ("", "joe"),
				new MailboxAddress ("", "alex"),
				new MailboxAddress ("", "bob"),
			}));
			list2.Add (new MailboxAddress ("Joey", "*****@*****.**"));

			Assert.IsTrue (list1.CompareTo (list2) > 0, "CompareTo() should return < 0.");
			Assert.IsTrue (list2.CompareTo (list1) < 0, "CompareTo() should return > 0.");
		}
예제 #42
0
		internal MimeMessage (ParserOptions options)
		{
			addresses = new Dictionary<string, InternetAddressList> (StringComparer.OrdinalIgnoreCase);
			Headers = new HeaderList (options);

			// initialize our address lists
			foreach (var name in StandardAddressHeaders) {
				var list = new InternetAddressList ();
				list.Changed += InternetAddressListChanged;
				addresses.Add (name, list);
			}

			references = new MessageIdList ();
			references.Changed += ReferencesChanged;
			inreplyto = null;

			Headers.Changed += HeadersChanged;
		}
		public void TestEncodingMailboxWithReallyLongWord ()
		{
			const string expected = "=?us-ascii?q?reeeeeeeeeeeeeeaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaallllllllllll?=\n =?us-ascii?q?llllllllllllllllllllllllllllllllllllllllllly?= long word\n\t<*****@*****.**>";
			const string name = "reeeeeeeeeeeeeeaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaallllllllllllllllllllllllllllllllllllllllllllllllllllllly long word";
			var mailbox = new MailboxAddress (name, "*****@*****.**");
			var list = new InternetAddressList ();
			list.Add (mailbox);

			var actual = list.ToString (UnixFormatOptions, true);

			Assert.AreEqual (expected, actual, "Encoding really long mailbox did not match expected result: {0}", expected);
			Assert.IsTrue (InternetAddressList.TryParse (actual, out list), "Failed to parse really long mailbox");
			Assert.AreEqual (mailbox.Name, list[0].Name);
		}
예제 #44
0
        static void ExtractRecipientTable(TnefReader reader, MimeMessage message)
        {
            var prop = reader.TnefPropertyReader;

            // Note: The RecipientTable uses rows of properties...
            while (prop.ReadNextRow())
            {
                string transmitableDisplayName = null;
                string recipientDisplayName    = null;
                string displayName             = string.Empty;
                InternetAddressList list       = null;
                string addr = null;

                while (prop.ReadNextProperty())
                {
                    switch (prop.PropertyTag.Id)
                    {
                    case TnefPropertyId.RecipientType:
                        int recipientType = prop.ReadValueAsInt32();
                        switch (recipientType)
                        {
                        case 1: list = message.To; break;

                        case 2: list = message.Cc; break;

                        case 3: list = message.Bcc; break;
                        }
                        break;

                    case TnefPropertyId.TransmitableDisplayName:
                        transmitableDisplayName = prop.ReadValueAsString();
                        break;

                    case TnefPropertyId.RecipientDisplayName:
                        recipientDisplayName = prop.ReadValueAsString();
                        break;

                    case TnefPropertyId.DisplayName:
                        displayName = prop.ReadValueAsString();
                        break;

                    case TnefPropertyId.EmailAddress:
                        if (string.IsNullOrEmpty(addr))
                        {
                            addr = prop.ReadValueAsString();
                        }
                        break;

                    case TnefPropertyId.SmtpAddress:
                        // The SmtpAddress, if it exists, should take precedence over the EmailAddress
                        // (since the SmtpAddress is meant to be used in the RCPT TO command).
                        addr = prop.ReadValueAsString();
                        break;
                    }
                }

                if (list != null && !string.IsNullOrEmpty(addr))
                {
                    var name = recipientDisplayName ?? transmitableDisplayName ?? displayName;

                    list.Add(new MailboxAddress(name, addr));
                }
            }
        }
		public void TestEncodingSimpleAddressList ()
		{
			const string expectedEncoded = "Kristoffer =?iso-8859-1?q?Br=E5nemyr?= <*****@*****.**>, Jeffrey Stedfast\n\t<*****@*****.**>";
			const string expectedDisplay = "\"Kristoffer Brånemyr\" <*****@*****.**>, \"Jeffrey Stedfast\" <*****@*****.**>";
			var latin1 = Encoding.GetEncoding ("iso-8859-1");
			var options = FormatOptions.Default.Clone ();
			var list = new InternetAddressList ();

			list.Add (new MailboxAddress (latin1, "Kristoffer Brånemyr", "*****@*****.**"));
			list.Add (new MailboxAddress ("Jeffrey Stedfast", "*****@*****.**"));

			options.NewLineFormat = NewLineFormat.Unix;

			var display = list.ToString (options, false);
			Assert.AreEqual (expectedDisplay, display, "Display value does not match the expected result: {0}", display);

			var encoded = list.ToString (options, true);
			Assert.AreEqual (expectedEncoded, encoded, "Encoded value does not match the expected result: {0}", display);
		}
예제 #46
0
파일: Sender.cs 프로젝트: Denuin/SendMail
        public async Task <bool> Send(Dictionary <string, string> argsMap)
        {
            bool result = false;

            string[] to      = argsMap["-to"].Split(';');
            string[] from    = argsMap["-from"].Split(',');
            string   subject = argsMap["-subject"];
            string   body    = argsMap["-body"];

            string[] smtp = argsMap["-smtp"].Split(':');
            string[] user = argsMap["-user"].Split('/');

            string[] att = null;
            if (argsMap.TryGetValue("-att", out string valueAtt))
            {
                att = valueAtt.Split(';');
            }

            if (smtp?.Length != 2)
            {
                Console.WriteLine("Send Error: -smtp格式有误!");
                return(result);
            }
            if (user?.Length != 2)
            {
                Console.WriteLine("Send Error: -user格式有误!");
                return(result);
            }

            #region 发邮件

            _smtp.ConnectAsync(smtp[0], Convert.ToInt32(smtp[1]), SecureSocketOptions.StartTls).Wait();
            _smtp.AuthenticateAsync(user[0], user[1]).Wait();

            _smtp.MessageSent += (sender, args) =>
            {
                Console.WriteLine($"Send Message: {args.Response}");
            };

            var message = new MimeMessage();
            InternetAddressList list = new InternetAddressList();
            foreach (var p in to)
            {
                list.Add(new MailboxAddress(p, p));
            }
            message.To.AddRange(list);
            if (from.Length > 1)
            {
                message.From.Add(new MailboxAddress(from[0], from[1]));
            }
            else
            {
                message.From.Add(new MailboxAddress(from[0], from[0]));
            }
            message.Subject = subject;

            var builder = new BodyBuilder();
            if (att != null)
            {
                foreach (var p in att)
                {
                    if (File.Exists(p))
                    {
                        builder.Attachments.Add(p);
                    }
                    else
                    {
                        Console.WriteLine($"提示: 附件文件 {p} 不存在。");
                    }
                }
            }
            builder.TextBody = body;
            message.Body     = builder.ToMessageBody();
            await _smtp.SendAsync(message);

            #endregion 发邮件

            return(result);
        }
		public void TestEquality ()
		{
			var list1 = new InternetAddressList ();

			list1.Add (new GroupAddress ("Local recipients", new InternetAddress[] {
				new MailboxAddress ("", "phil"),
				new MailboxAddress ("", "joe"),
				new MailboxAddress ("", "alex"),
				new MailboxAddress ("", "bob"),
			}));
			list1.Add (new MailboxAddress ("Joey", "*****@*****.**"));
			list1.Add (new MailboxAddress ("Chandler", "*****@*****.**"));

			var list2 = new InternetAddressList ();

			list2.Add (new MailboxAddress ("Chandler", "*****@*****.**"));
			list2.Add (new GroupAddress ("Local recipients", new InternetAddress[] {
				new MailboxAddress ("", "phil"),
				new MailboxAddress ("", "joe"),
				new MailboxAddress ("", "alex"),
				new MailboxAddress ("", "bob"),
			}));
			list2.Add (new MailboxAddress ("Joey", "*****@*****.**"));

			Assert.IsTrue (list1.Equals (list2), "The 2 lists should be equal.");
		}
예제 #48
0
        /// <summary>
        /// Asynchronously produces e-mails and notification messages for all intended recipients based on the specified event type.
        /// </summary>
        /// <param name="args">An object that holds issue-related event data.</param>
        /// <param name="cancellationToken">The token used to cancel an ongoing async operation.</param>
        /// <returns></returns>
        public override async Task ProcessAsync(SysEventArgs args, CancellationToken cancellationToken = default(CancellationToken))
        {
            // give a chance to the base message producer to process the event
            await base.ProcessAsync(args, cancellationToken);

            if (!(args is SysEventArgs <Issue> e))
            {
                throw new ArgumentException($"Must be of type {nameof(SysEventArgs<Issue>)}.", nameof(args));
            }

            var issue    = e.Data ?? throw new ArgumentNullException("Data");
            var user     = (e.User as AppUser) ?? throw new ArgumentNullException("User");
            var settings = e.ObjectState as EmailSettingsViewModel ?? throw new ArgumentNullException("ObjectState", $"ObjectState must be of type {nameof(EmailSettingsViewModel)}");

            var notifs = settings.Notifications;

            _emailNotificationsEnabled = notifs.Enabled ?? false;

            try
            {
                if (issue.User == null && e.EventType != SysEventType.IssueDeleted)
                {
                    issue = await _issueRepo.All(q => q.QueryIssues(id: issue.Id, withIncludes: true)).SingleOrDefaultAsync();
                }

                var fullName          = user.FullName();
                var userName          = user.UserName;
                var notify            = false;
                var outgoing          = settings.Outgoing;
                var from              = outgoing.FromDisplay;
                var useFromNameForAll = outgoing.UseFromNameForAll ?? false;
                var replyToAddrList   = new InternetAddressList();

                if (!string.IsNullOrWhiteSpace(outgoing.ReplyTo))
                {
                    replyToAddrList.AddRange(outgoing.ReplyTo);
                }

                EmailTemplate temp;
                var           templates = settings.Templates;

                switch (e.EventType)
                {
                case SysEventType.IssueCreated:
                {
                    // Sent to technicians when a new ticket arrives. All technicians that have permissions to the category get one of these.

                    // Ticket confirmation notification  (the one users get after submitting a new ticket)?
                    notify = notifs.TicketConfirmationNotification ?? false;

                    if (notify && user.SendEmail && user.EmailConfirmed)
                    {
                        // "Ticket confirmation" email template: Sent to the ticket-submitter after the app received his ticket.
                        temp = templates.TicketConfirmation;

                        var m = CreateMessage(
                            temp.ReplaceSubject(issue.Subject).ToString(),
                            temp.ReplaceBody(issue.Body, issue.Subject)
                            .Replace("#Numero_ticket#", $"{issue.Id}")
                            .Replace("#Articles_Base_Connaissances#", string.Empty)
                            //.Replace("#Suggested_KB_articles#", string.Empty)
                            .ToString(),
                            from,
                            to: user.Email
                            );

                        m.ReplyTo.AddRange(replyToAddrList);
                        Enqueue(WrapMessage(m, user.Id));
                    }

                    temp = templates.NewTicket;
                    var subj = temp.ReplaceSubject(issue.Subject).ToString();
                    var body = temp.ReplaceBody(issue.Body, issue.Subject).Replace("#Numero_ticket#", $"{issue.Id}").ToString();

                    from = user.GetEmailAddress();

                    // notify all admins?
                    if (notifs.NotifyAllAdmins ?? false)
                    {
                        var qry = _userRepo.All(q => q.NotDisabled().Admins().Not(user.Id).CanReceiveEmails());
                        await ForUsersAsync(qry, subj, body, from, replyToAddrList, cancellationToken);
                    }

                    // notify techs in their categories?
                    if (notifs.NotifyTechs ?? false)
                    {
                        var qry = _userRepo.All(q => q.NotDisabled().Techs().Not(user.Id).CanReceiveEmails());
                        await ForUsersAsync(qry, subj, body, from, replyToAddrList, cancellationToken);
                    }
                }
                break;

                case SysEventType.IssueAssigned:
                {
                    // Notify ALL technicians in a category when another technician TAKES a ticket
                    temp = await TemplateForUpdate($"{fullName} a pris en charge la résolution du ticket #{issue.Id}.");

                    if (user.IsTech && (notifs.NotifyAllTechsOnTechTakeOver ?? false))
                    {
                        await NotifyTechs(temp);
                    }

                    // notify ticket owner
                    NotifyOwner(temp);
                }
                break;

                case SysEventType.IssueUpdated:
                {
                    // Sent to both technicians and ticket-submitter (and all ticket-subscribers if any) when a new reply is added to the ticket
                    temp = await TemplateForUpdate($"Le ticket #{issue.Id} a été mis à jour par {fullName}.");

                    if (issue.UpdatedByUser)
                    {
                        from = user.GetEmailAddress();
                        var techsNotified = false;

                        // Notify ALL technicians in a category when a customer updates a ticket
                        // (not just the ticket-technician and ticket-subscribers)?
                        if (issue.UpdatedForTechView || (notifs.NotifyAllTechsOnCustomerUpdate ?? false))
                        {
                            await NotifyTechs(temp);

                            techsNotified = true;
                        }

                        await NotifyAssignee(temp);

                        // send to all subscribers but the submitter
                        var qry = _subsRepo.All(q => q.QueryIssueSubscribers(issue.Id).But(user.Id));

                        if (techsNotified)
                        {
                            qry = qry.NotTechs(); // exclude the techs who've been notified previously
                        }
                        await ForSubscribersAsync(qry, temp.Subject, temp.Body, from, replyToAddrList, cancellationToken);
                    }
                    else
                    {
                        // send to submitter
                        NotifyOwner(temp);

                        // send to subscribers except the owner and updater
                        var qry = _subsRepo.All(q => q.QueryIssueSubscribers(issue.Id).But(user.Id).But(issue.User.Id));

                        await ForSubscribersAsync(qry, temp.Subject, temp.Body, from, replyToAddrList, cancellationToken);
                    }
                }
                break;

                case SysEventType.IssueClosed:
                {
                    // Sent to subscribers when a ticket is closed. Note that "Ticket closed notifications" setting has to be on.
                    if (notifs.TicketClosedNotification ?? false)
                    {
                        temp = await TemplateForUpdate($"Le ticket #{issue.Id} a été fermé par {fullName}.");

                        NotifyOwner(temp);
                    }
                }

                break;

                case SysEventType.IssueReopened:
                    // no template for this scenario?
                    break;

                case SysEventType.IssueDeleted:
                    // no template for this scenario?
                    break;

                default:
                    // definitely no template for this scenario!
                    break;
                }

                Consumer.Notify();

                async Task <EmailTemplate> TemplateForUpdate(string whatHappened)
                {
                    var comments = await _commentRepo.GetAsync(q => q.QueryCommentsForIssue(issue.Id).Skip(0).Take(3).ToArray());

                    var recent = string.Empty;

                    if (comments.Length > 0)
                    {
                        try
                        {
                            recent = await _emailTemplatesViewRender.RenderToStringAsync(TEMPLATE_RECENT_COMMENTS, comments);
                        }
                        catch (Exception ex)
                        {
                            Logger.LogWarning(ex, "An error occured while rendering the recent comments e-mail template.");

                            var sb = new StringBuilder("<h3>Messages récents</h3>");

                            foreach (var c in comments)
                            {
                                sb.AppendLine();
                                sb.AppendLine(c.Body);
                            }

                            recent = sb.ReplaceLineBreaks().ToString().Trim();
                        }
                    }

                    temp = templates.TicketUpdated;
                    var subj = temp.ReplaceSubject(issue.Subject).ToString();
                    var body = temp
                               .ReplaceBody(issue.Body, issue.Subject)
                               .Replace("#Quoi_De_Neuf#", whatHappened)
                               .Replace("#Messages_recents#", recent)
                               .Replace("#Categorie#", issue.Category?.Name)
                               .Replace("#Statut#", issue.Status?.Name)
                               .Replace("#Priorite#", UtilExtensions.PriorityName(issue.Priority))
                               //.Replace("#What_Happened#", whatHappened)
                               //.Replace("#Recent_messages#", recent)
                               //.Replace("#Category#", catname)
                               //.Replace("#Status#", statname)
                               //.Replace("#Priority#", priority)
                               .ToString();

                    return(new EmailTemplate {
                        Body = body, Subject = subj
                    });
                }

                async Task NotifyTechs(EmailTemplate et)
                {
                    var qry = _userRepo.All(q => q.NotDisabled().Techs().Not(user.Id).CanReceiveEmails());

                    await ForUsersAsync(qry, et.Subject, et.Body, from, replyToAddrList, cancellationToken);
                }

                async Task NotifyAssignee(EmailTemplate et)
                {
                    if (issue.IsAssigned())
                    {
                        var owner = await _userRepo.GetAsync(q => q.Find(issue.AssignedToUserId));

                        if (owner != null)
                        {
                            EnqueueTemplate(et, owner);
                        }
                    }
                }

                void NotifyOwner(EmailTemplate et)
                {
                    var owner = issue.User;

                    if (owner.SendEmail && owner.Id != user.Id)
                    {
                        EnqueueTemplate(et, owner);
                    }
                }

                void SetFromName(AppUser u)
                {
                    if (!useFromNameForAll)
                    {
                        from = user.GetEmailAddress();
                    }
                }

                void EnqueueTemplate(EmailTemplate et, AppUser owner)
                {
                    SetFromName(owner);
                    Enqueue(WrapMessage(CreateMessage(et.Subject, et.Body, from, owner.Email), owner.Id));
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, $"Error while producing issue e-mails in {nameof(ProcessAsync)}.");
            }
        }
예제 #49
0
		void AddAddresses (Header header, InternetAddressList list)
		{
			int length = header.RawValue.Length;
			List<InternetAddress> parsed;
			int index = 0;

			// parse the addresses in the new header and add them to our address list
			if (!InternetAddressList.TryParse (Headers.Options, header.RawValue, ref index, length, false, false, out parsed))
				return;

			list.Changed -= InternetAddressListChanged;
			list.AddRange (parsed);
			list.Changed += InternetAddressListChanged;
		}
예제 #50
0
        /// <summary>
        /// Build MimeMessage, inject user text and Eml file as message/rfc822 attachment
        /// </summary>
        /// <PARAM name="text"></PARAM>
        /// <PARAM name="emlMessageList"></PARAM>
        /// <PARAM name="from"></PARAM>
        /// <PARAM name="toList"></PARAM>
        /// <PARAM name="ccList"></PARAM>
        /// <PARAM name="bccList"></PARAM>
        /// <returns></returns>
        public static MimeMessage BuildMimeMessageWithEmlAsRFC822Attachment(TextPart text, List <MimeMessage> emlMessageList,
                                                                            MailboxAddress from, InternetAddressList toList, InternetAddressList ccList, InternetAddressList bccList)
        {
            var message = new MimeMessage();

            message.From.Add(from);
            message.To.AddRange(toList);
            if (ccList.Count > 0)
            {
                message.Cc.AddRange(ccList);
            }
            if (bccList.Count > 0)
            {
                message.Bcc.AddRange(bccList);
            }

            MimeMessage firstMessage = emlMessageList[0];

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

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

            multipart.Add(text);
            foreach (var emlMessage in emlMessageList)
            {
                // create the message/rfc822 attachment for the original message
                var rfc822 = new MessagePart {
                    Message = emlMessage
                };
                multipart.Add(rfc822);
            }

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

            return(message);
        }
예제 #51
0
		void SerializeAddressList (string field, InternetAddressList list)
		{
			var builder = new StringBuilder (" ");
			var options = FormatOptions.Default;
			int lineLength = field.Length + 2;

			list.Encode (options, builder, ref lineLength);
			builder.Append (options.NewLine);

			var raw = Encoding.UTF8.GetBytes (builder.ToString ());

			ReplaceHeader (field.ToHeaderId (), field, raw);
		}
예제 #52
0
        static void SendMailMime(MailInputs maildata)
        {
            try
            {
                //---------------------
                //  Configuration

                //  User setup
                string User     = maildata.User;
                string UserName = maildata.User;
                string pssw     = maildata.Password;

                //  Server setup
                string server = maildata.Server;
                int    port   = Convert.ToInt32(maildata.Port);

                //  Mail setup
                string attachment  = maildata.Attachment;
                string MailBody    = maildata.Body;
                string MailSubject = maildata.Subject;

                string toAddressString  = maildata.To;
                string ccAddressString  = maildata.Cc;
                string bccAddressString = maildata.Bcc;

                //--------------------

                MimeMessage message = new MimeMessage();

                MailboxAddress from = new MailboxAddress(UserName, User);
                message.From.Add(from);

                if (!string.IsNullOrEmpty(toAddressString))
                {
                    InternetAddressList toList = new InternetAddressList();
                    toList.AddRange(MimeKit.InternetAddressList.Parse(toAddressString));
                    message.To.AddRange(toList);
                }


                if (!string.IsNullOrEmpty(ccAddressString))
                {
                    InternetAddressList ccList = new InternetAddressList();
                    ccList.AddRange(MimeKit.InternetAddressList.Parse(ccAddressString));
                    message.Cc.AddRange(ccList);
                }


                if (!string.IsNullOrEmpty(bccAddressString))
                {
                    InternetAddressList bccList = new InternetAddressList();
                    bccList.AddRange(MimeKit.InternetAddressList.Parse(bccAddressString));
                    message.Bcc.AddRange(bccList);
                }

                //Mail body

                BodyBuilder bodyBuilder = new BodyBuilder();
                //bodyBuilder.HtmlBody = "<h1>This is a mail body</h1>";
                message.Subject = MailSubject;
                if (!string.IsNullOrEmpty(MailBody))
                {
                    bodyBuilder.TextBody = MailBody;
                }


                //
                if (!string.IsNullOrEmpty(attachment))
                {
                    bodyBuilder.Attachments.Add(attachment);
                }

                message.Body = bodyBuilder.ToMessageBody();


                SmtpClient client = new SmtpClient();


                client.Connect(server, port, SecureSocketOptions.None);
                client.Authenticate(User, pssw);


                client.Send(message);
                client.Disconnect(true);
                client.Dispose();



                Console.WriteLine("");
                //Console.ReadLine();

                //............................
            }
            catch (Exception ep)
            {
                Console.WriteLine("failed to send email with the following error:");
                Console.WriteLine(ep.Message);
                Console.ReadLine();
            }
        }
예제 #53
0
		void ReloadAddressList (HeaderId id, InternetAddressList list)
		{
			// clear the address list and reload
			list.Changed -= InternetAddressListChanged;
			list.Clear ();

			foreach (var header in Headers) {
				if (header.Id != id)
					continue;

				int length = header.RawValue.Length;
				List<InternetAddress> parsed;
				int index = 0;

				if (!InternetAddressList.TryParse (Headers.Options, header.RawValue, ref index, length, false, false, out parsed))
					continue;

				list.AddRange (parsed);
			}

			list.Changed += InternetAddressListChanged;
		}
예제 #54
0
        public static void Main(string[] args)
        {
            AppDomain currentDomain = AppDomain.CurrentDomain;

            currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

            string dataPath        = GetLocalAppDataPath();
            string MBoxViewerPath  = Path.Combine(dataPath, "MBoxViewer");
            string MailServicePath = Path.Combine(MBoxViewerPath, "MailService");
            string TempPath        = Path.Combine(MailServicePath, "Temp");

            string okFilePath               = MailServicePath + "\\ForwardMailSuccess.txt";
            string errorFilePath            = MailServicePath + "\\ForwardMailError.txt";
            string errorFilePathOldInstance = MailServicePath + "\\ForwardMailError2.txt";

            System.IO.DirectoryInfo info = Directory.CreateDirectory(TempPath);

            string loggerFilePath = FindKeyinArgs(args, "--logger-file");
            var    logger         = new FileLogger();

            logger.Open(loggerFilePath);
            logger.Log("Logger Open");

            try
            {
                // File.Delete doesn't seem to generate exceptions if file doesn't exist
                //if (File.Exists(okFilePath)
                File.Delete(okFilePath);
                //if (File.Exists(errorFilePath)
                File.Delete(errorFilePath);
                File.Delete(errorFilePathOldInstance);
            }
            catch (Exception ex)
            {
                string txt = String.Format("Delete Critical Files Failed\n{0}\n{1}\n{2}\n\n{3}",
                                           okFilePath, errorFilePath, errorFilePathOldInstance, ex.Message);
                bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, txt);
                logger.Log("Exception in Delete Critical Files: ", ex.ToString());
                System.Environment.Exit(ExitCodes.ExitMailAddress);
            }

            int numArgs = args.GetLength(0);

            if ((numArgs <= 0) || ((numArgs % 2) != 0))
            {
                string errorText = String.Format("Invalid command argument list: {0} .", String.Join(" ", args));
                bool   rval      = FileUtils.CreateWriteCloseFile(errorFilePath, errorText + "\n");
                logger.Log(errorText);
                System.Environment.Exit(ExitCodes.ExitCmdArguments);
            }

            /*
             * if (numArgs <= 0)
             * {
             *  logger.Log(@"Usage: --from addr --to addr1,addr2,.. --cc addr1,addr2,.. -bcc addr1,addr2,..
             *      --user login-user-name --passwd --login-user-password --smtp smtp-server-name", "");
             *  Debug.Assert(true == false);
             *  System.Environment.Exit(1);
             * }
             */
            string     instance               = "";
            IniFile    smtpIni                = null;
            EMailInfo  mailInfo               = new EMailInfo();
            SMTPConfig smtpConfig             = new SMTPConfig();
            string     smtpConfigFilePath     = "";
            string     UserPassword           = "";
            string     protocolLoggerFilePath = "";

            int tcpListenPort = 0;

            logger.Log("Command line argument list:");
            for (int j = 0, i = 0; j < numArgs; j = j + 2, i++)
            {
                string key = args[j];
                string val = args[j + 1];

                if (!key.StartsWith("--"))
                {
                    string errorText = String.Format("Invalid key: {0} ", key);
                    bool   rval      = FileUtils.CreateWriteCloseFile(errorFilePath, errorText + "\n");
                    logger.Log(errorText);
                    System.Environment.Exit(ExitCodes.ExitCmdArguments);
                }
                if ((j + 1) >= numArgs)
                {
                    string errorText = String.Format("Found key: {0} without value.", key);
                    bool   rval      = FileUtils.CreateWriteCloseFile(errorFilePath, errorText + "\n");
                    logger.Log(errorText);
                    System.Environment.Exit(ExitCodes.ExitCmdArguments);
                }
                if (key.CompareTo("--instance-id") == 0)
                {
                    instance = val;
                }
                else if (key.CompareTo("--smtp-protocol-logger") == 0)
                {
                    protocolLoggerFilePath = val;
                }
                else if (key.CompareTo("--from") == 0)
                {
                    mailInfo.From = val;
                }
                else if (key.CompareTo("--to") == 0)
                {
                    mailInfo.To = val;
                }
                else if (key.CompareTo("--cc") == 0)
                {
                    mailInfo.CC = val;
                }
                else if (key.CompareTo("--bcc") == 0)
                {
                    mailInfo.BCC = val;
                }
                else if (key.CompareTo("--user") == 0)
                {
                    mailInfo.To = val;
                }
                else if (key.CompareTo("--passwd") == 0)
                {
                    UserPassword = val;
                }
                else if (key.CompareTo("--smtp-cnf") == 0)
                {
                    smtpConfigFilePath = val;
                }
                else if (key.CompareTo("--tcp-port") == 0)
                {
                    tcpListenPort = int.Parse(val);
                }
                else if (key.CompareTo("--eml-file") == 0)
                {
                    mailInfo.EmlFilePath = val;
                }
                else if (key.CompareTo("--mail-text-file") == 0)
                {
                    mailInfo.TextFilePath = val;
                }
                else if (key.CompareTo("--logger-file") == 0)
                {
                    ; // see FindKeyinArgs(args, "--logger-file");
                }
                else
                {
                    logger.Log(String.Format("    Unknown Key: {0} {1}", args[j], args[j + 1]));
                }
                logger.Log(String.Format("    {0} {1}", args[j], args[j + 1]));
            }

            if (smtpConfigFilePath.Length == 0)
            {
                string errorText = String.Format("required --smtp-cnf command line argument missing.");
                bool   rval      = FileUtils.CreateWriteCloseFile(errorFilePath, errorText + "\n");
                logger.Log(errorText);
                System.Environment.Exit(ExitCodes.ExitCmdArguments);
            }

            if (!File.Exists(smtpConfigFilePath))
            {
                string errorText = String.Format("SMTP configuration file {0} doesn't exist.", smtpConfigFilePath);
                bool   rval      = FileUtils.CreateWriteCloseFile(errorFilePath, errorText + "\n");
                logger.Log(errorText);
                System.Environment.Exit(ExitCodes.ExitCmdArguments);
            }
            try
            {
                if (protocolLoggerFilePath.Length > 0)
                {
                    File.Delete(protocolLoggerFilePath);
                }
            }
            catch (Exception /*ex*/) {; } // ignore

            smtpIni = new IniFile(smtpConfigFilePath);

            string ActiveMailService = smtpIni.IniReadValue("MailService", "ActiveMailService");

            smtpConfig.MailServiceName   = smtpIni.IniReadValue(ActiveMailService, "MailServiceName");
            smtpConfig.SmtpServerAddress = smtpIni.IniReadValue(ActiveMailService, "SmtpServerAddress");
            smtpConfig.SmtpServerPort    = int.Parse(smtpIni.IniReadValue(ActiveMailService, "SmtpServerPort"));
            smtpConfig.UserAccount       = smtpIni.IniReadValue(ActiveMailService, "UserAccount");
            if (UserPassword.Length > 0)
            {
                smtpConfig.UserPassword = UserPassword;
            }
            else
            {
                smtpConfig.UserPassword = smtpIni.IniReadValue(ActiveMailService, "UserPassword");
            }
            smtpConfig.EncryptionType = int.Parse(smtpIni.IniReadValue(ActiveMailService, "EncryptionType"));

            logger.Log(smtpConfig.ToString());

            // Uncomment when you exec this application from MBoxViewer
            //smtpConfig.UserPassword = "";
            if (smtpConfig.UserPassword.Length == 0)
            {
                logger.Log("Waiting to receive password");
                smtpConfig.UserPassword = WaitForPassword(tcpListenPort, logger, errorFilePath);

                if (smtpConfig.UserPassword.Length > 0)
                {
                    logger.Log("Received non empty password");
                    //logger.Log("Received non empty password: "******"Received empty password");
                }

                int found = smtpConfig.UserPassword.IndexOf(":");
                if (found <= 0)
                {
                    // Old instance , log to differnt file
                    bool rval = FileUtils.CreateWriteCloseFile(errorFilePathOldInstance, "Received invalid id:password. Exitting\n");
                    System.Environment.Exit(ExitCodes.ExitCmdArguments);
                }
                string id     = smtpConfig.UserPassword.Substring(0, found);
                string passwd = smtpConfig.UserPassword.Substring(found + 1);
                smtpConfig.UserPassword = passwd;

                logger.Log("Command line instance id: ", instance);
                logger.Log("Received instance id: ", id);
                //logger.Log("Received password: "******"Received password: "******"xxxxxxxxxxxx");

                if (id.CompareTo(instance) != 0)
                {
                    // Old instance , log to different file
                    bool rval = FileUtils.CreateWriteCloseFile(errorFilePathOldInstance, "This is old instance. Exitting\n");
                    System.Environment.Exit(ExitCodes.ExitCmdArguments);
                }
            }

            MimeKit.ParserOptions opt = new MimeKit.ParserOptions();

            var From = new MailboxAddress("", smtpConfig.UserAccount);
            //
            InternetAddressList CCList  = new InternetAddressList();
            InternetAddressList BCCList = new InternetAddressList();
            InternetAddressList ToList  = new InternetAddressList();

            try
            {
                if (mailInfo.To.Length > 0)
                {
                    ToList = MimeKit.InternetAddressList.Parse(opt, mailInfo.To);
                }
                if (mailInfo.CC.Length > 0)
                {
                    CCList = MimeKit.InternetAddressList.Parse(opt, mailInfo.CC);
                }
                if (mailInfo.BCC.Length > 0)
                {
                    BCCList = MimeKit.InternetAddressList.Parse(opt, mailInfo.BCC);
                }
            }
            catch (Exception ex)
            {
                bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Parsing Internet Address list Failed\n", ex.Message);
                logger.Log("Exception in InternetAddressList.Parse: ", ex.ToString());
                System.Environment.Exit(ExitCodes.ExitMailAddress);
            }

            //
            string emlFilePath = mailInfo.EmlFilePath;

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

            try
            {
                text.Text = File.ReadAllText(mailInfo.TextFilePath, Encoding.UTF8);
            }
            catch (Exception ex)
            {
                bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Building Mime Mesage Failed\n", ex.Message);
                logger.Log("Exception in Building Mime Message: ", ex.ToString());
                System.Environment.Exit(ExitCodes.ExitMimeMessage);
            }

            logger.Log("Forwarding Eml file:", emlFilePath);
            MimeMessage msg = null;

            try
            {
                var message = new MimeMessage();
                message = MimeKit.MimeMessage.Load(emlFilePath);

                List <MimeMessage> mimeMessages = new List <MimeMessage>();
                mimeMessages.Add(message);

                msg = BuildMimeMessageWithEmlAsRFC822Attachment(text, mimeMessages, From, ToList, CCList, BCCList);
            }
            catch (Exception ex)
            {
                bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Building Mime Mesage Failed\n", ex.Message);
                logger.Log("Exception in Building Mime Message: ", ex.ToString());
                System.Environment.Exit(ExitCodes.ExitMimeMessage);
            }

            logger.Log("BuildMimeMessageWithEmlAsRFC822Attachment Done");

            //string msgAsString = MailkitConvert.ToString(msg);
            //string msgAsString = msg.ToString();
            //logger.Log("\n", msgAsString);

            // OAUTH2 works on Google but requires verification by Google and it seems to be chargable option if number of users > 100
            // Another problem is that ClientSecret can't be hardcoded in the application
            // For now we will just rely on User Account and User Password for authentication
            SaslMechanism oauth2    = null;;
            bool          useOAUTH2 = false;

            if (useOAUTH2)
            {
                string appClientId     = "xxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";
                string appClientSecret = "yyyyyyyyyyyyyyyyyyyyyyyyyyy";

                var accessScopes = new[]
                {
                    // that is the only scope that works per info from jstedfast
                    "https://mail.google.com/",
                };

                var clientSecrets = new ClientSecrets
                {
                    ClientId     = appClientId,
                    ClientSecret = appClientSecret
                };
                oauth2 = GetAuth2Token(smtpConfig.UserAccount, clientSecrets, accessScopes);
            }

            IProtocolLogger smtpProtocolLogger = null;

            if (protocolLoggerFilePath.Length > 0)
            {
                smtpProtocolLogger = new ProtocolLogger(protocolLoggerFilePath);
            }
            else
            {
                smtpProtocolLogger = new NullProtocolLogger();
            }

            using (var client = new SmtpClient(smtpProtocolLogger))
            {
                try
                {
                    client.Connect(smtpConfig.SmtpServerAddress, smtpConfig.SmtpServerPort, (SecureSocketOptions)smtpConfig.EncryptionType);
                }
                catch (Exception ex)
                {
                    bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Connect to SMTP Server Failed\n", ex.Message);
                    logger.Log("Exception in Connect: ", ex.ToString());
                    System.Environment.Exit(ExitCodes.ExitConnect);
                }

                logger.Log(String.Format("Connected to {0} mail service", smtpConfig.MailServiceName));

                try
                {
                    if (useOAUTH2)
                    {
                        client.Authenticate(oauth2);
                    }
                    else
                    {
                        client.Authenticate(smtpConfig.UserAccount, smtpConfig.UserPassword);
                    }
                }
                catch (Exception ex)
                {
                    bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "SMTP Authentication Failed\n", ex.Message);
                    logger.Log("Exception in Authenticate: ", ex.ToString());
                    System.Environment.Exit(ExitCodes.ExitAuthenticate);
                }
                logger.Log("SMTP Authentication Succeeded");

                // Clear smtpConfig.UserPassword in case it cores
                smtpConfig.UserPassword = "";

                try
                {
                    client.Send(msg);
                }
                catch (Exception ex)
                {
                    bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Send Failed\n", ex.Message);
                    logger.Log("Exception in Send to SMTP Server: ", ex.ToString());

                    //string msgString = MailkitConvert.ToString(msg);
                    //string msgAsString = msg.ToString();

                    // To help to investigate Warning place at the begining of the serialized MimeMessage
                    // X - MimeKit - Warning: Do NOT use ToString() to serialize messages! Use one of the WriteTo() methods instead!
                    //logger.Log("\n", msgString);

                    System.Environment.Exit(ExitCodes.ExitSend);
                }

                string txt = "Mail Sending Succeeded";
                logger.Log(txt);
                bool retval = FileUtils.CreateWriteCloseFile(okFilePath, txt);

                try
                {
                    client.Disconnect(true);
                }
                catch (Exception ex)
                {
                    // Ignore, not a fatal error
                    //bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Send Failed\n", ex.Message);
                    logger.Log("Exception in Disconnect to SMTP Server: ", ex.ToString());
                }
                logger.Log("SMTP Client Disconnected. All done.");
            }
            System.Environment.Exit(ExitCodes.ExitOk);
        }