public void SendMessage() {
     string msg = "";
     switch (CurrEmailType) {
         case EmailType.PRENOTA:
             msg = PrenotaSubject;
             FromMailAddress = PrenotaFromAddress;
             break;
         case EmailType.INFO:
             msg = InfoSubject;
             FromMailAddress = InfoFromAddress;
             break;
     }
     string subject = string.Format(msg, Message.Nome, DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
     string body = string.Format("Nome : {0}\nNumero : {1}\nE-Mail : {2}\nMessaggio :\n{3}", Message.Nome, Message.Telefono, Message.Email, Message.Messaggio);
     var message = new MimeMessage();
     message.From.Add(FromMailAddress);
     message.To.Add(ToAddress);
     message.Subject = subject;
     message.Body = new TextPart("plain") {Text = body};
     try {
         using (var client = new SmtpClient()) {
             client.Connect("smtp.gmail.com", 465, true);
             client.AuthenticationMechanisms.Remove("XOAUTH");
             client.Authenticate("*****@*****.**", "At066bn1!");
             client.Send(message);
             client.Disconnect(true);
         }
         Result = EmailResult.SUCCESS;
         MessageResult = "Messaggio inviato correttamente";
     } catch (Exception ex) {
         Result = EmailResult.FAIL;
         MessageResult = ex.Message;
     }
 }
Beispiel #2
1
 /*
  * tries to sign a MimeEntity
  */
 public static MimeEntity SignEntity(MimeEntity entity, MailboxAddress signer)
 {
     using (WindowsSecureMimeContext ctx = new WindowsSecureMimeContext(sys.StoreLocation.CurrentUser))
     {
         return MultipartSigned.Create(ctx, signer, DigestAlgorithm.Sha1, entity);
     }
 }
        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);
        }
Beispiel #4
0
		public void TestPgpMimeSigning ()
		{
			var self = new MailboxAddress ("MimeKit UnitTests", "*****@*****.**");

			var cleartext = new TextPart ("plain");
			cleartext.Text = "This is some cleartext that we'll end up signing...";

			using (var ctx = new DummyOpenPgpContext ()) {
				var multipart = MultipartSigned.Create (ctx, self, DigestAlgorithm.Sha1, cleartext);
				Assert.AreEqual (2, multipart.Count, "The multipart/signed has an unexpected number of children.");

				var protocol = multipart.ContentType.Parameters["protocol"];
				Assert.AreEqual (ctx.SignatureProtocol, protocol, "The multipart/signed protocol does not match.");

				Assert.IsInstanceOfType (typeof (TextPart), multipart[0], "The first child is not a text part.");
				Assert.IsInstanceOfType (typeof (ApplicationPgpSignature), multipart[1], "The second child is not a detached signature.");

				var signatures = multipart.Verify (ctx);
				Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
				foreach (var signature in signatures) {
					try {
						bool valid = signature.Verify ();

						Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
					} catch (DigitalSignatureVerifyException ex) {
						Assert.Fail ("Failed to verify signature: {0}", ex);
					}
				}
			}
		}
Beispiel #5
0
 public void FormPasswordResetEmailModel(User user, string token,
                                         string passwordResetTemplate, IConfiguration configuration)
 {
     Reciever = new MimeKit.MailboxAddress(user.Email);
     Subject  = Constants.Constants.PASSWORD_RESET_EMAIL_SUBJECT;
     Message  = EmailHelper.PasswordResetTemplateGenerator(user, token, passwordResetTemplate, configuration);
 }
		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);
		}
        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");
        }
 /*
  * returns true if email address can sign email
  */
 public static bool CanSign(string email)
 {
     try
     {
         MailboxAddress signer = new MailboxAddress("", email);
         TextPart entity = new TextPart("text");
         using (WindowsSecureMimeContext ctx = new WindowsSecureMimeContext(sys.StoreLocation.CurrentUser))
         {
             MultipartSigned.Create(ctx, signer, DigestAlgorithm.Sha1, entity);
             return true;
         }
     }
     catch
     {
         return false;
     }
 }
		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);
		}
Beispiel #10
0
        public void TestPgpMimeEncryption()
        {
            var self = new MailboxAddress ("MimeKit UnitTests", "*****@*****.**");
            var recipients = new List<MailboxAddress> ();

            // encrypt to ourselves...
            recipients.Add (self);

            var cleartext = new TextPart ("plain");
            cleartext.Text = "This is some cleartext that we'll end up encrypting...";

            using (var ctx = new DummyOpenPgpContext ()) {
                var encrypted = MultipartEncrypted.Create (ctx, recipients, cleartext);

                //using (var file = File.Create ("pgp-encrypted.asc"))
                //	encrypted.WriteTo (file);

                var decrypted = encrypted.Decrypt (ctx);

                Assert.IsInstanceOfType (typeof (TextPart), decrypted, "Decrypted part is not the expected type.");
                Assert.AreEqual (cleartext.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
            }
        }
Beispiel #11
0
		public void TestMimeMessageSign ()
		{
			var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing..." };
			var self = new MailboxAddress ("MimeKit UnitTests", "*****@*****.**");
			var message = new MimeMessage { Subject = "Test of signing with OpenPGP" };

			message.From.Add (self);
			message.Body = body;

			using (var ctx = new DummyOpenPgpContext ()) {
				message.Sign (ctx);

				Assert.IsInstanceOf<MultipartSigned> (message.Body);

				var multipart = (MultipartSigned) message.Body;

				Assert.AreEqual (2, multipart.Count, "The multipart/signed has an unexpected number of children.");

				var protocol = multipart.ContentType.Parameters["protocol"];
				Assert.AreEqual (ctx.SignatureProtocol, protocol, "The multipart/signed protocol does not match.");

				Assert.IsInstanceOf<TextPart> (multipart[0], "The first child is not a text part.");
				Assert.IsInstanceOf<ApplicationPgpSignature> (multipart[1], "The second child is not a detached signature.");

				var signatures = multipart.Verify (ctx);
				Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
				foreach (var signature in signatures) {
					try {
						bool valid = signature.Verify ();

						Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
					} catch (DigitalSignatureVerifyException ex) {
						Assert.Fail ("Failed to verify signature: {0}", ex);
					}
				}
			}
		}
Beispiel #12
0
        public void MessagesAvailable()
        {
            RunE2ETest(context => {
                string messageSubject = Guid.NewGuid().ToString();
                using (SmtpClient smtpClient = new SmtpClient())
                {
                    smtpClient.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
                    smtpClient.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    smtpClient.CheckCertificateRevocation          = false;
                    MimeMessage message = new MimeMessage();
                    message.To.Add(MailboxAddress.Parse("*****@*****.**"));
                    message.From.Add(MailboxAddress.Parse("*****@*****.**"));

                    message.Subject = messageSubject;
                    message.Body    = new TextPart()
                    {
                        Text = "Body of end to end test"
                    };

                    smtpClient.Connect("localhost", context.SmtpPortNumber, SecureSocketOptions.StartTls, new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token);
                    smtpClient.Send(message);
                    smtpClient.Disconnect(true, new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token);
                }


                using (ImapClient imapClient = new ImapClient())
                {
                    imapClient.Connect("localhost", context.ImapPortNumber);
                    imapClient.Authenticate("user", "password");
                    imapClient.Inbox.Open(MailKit.FolderAccess.ReadOnly);
                    var imapMessage = imapClient.Inbox.FirstOrDefault();
                    Assert.NotNull(imapMessage);
                    Assert.Equal(messageSubject, imapMessage.Subject);
                }
            });
        }
Beispiel #13
0
        private void RunSending(IDatabase database, Mailing mailing)
        {
            int remainingCount = 0;

            foreach (var sending in database.Query <Sending>(DC.Equal("mailingid", mailing.Id.Value)))
            {
                if (sending.Status.Value == SendingStatus.Created)
                {
                    if (_maxMailsCount > 0)
                    {
                        _maxMailsCount--;
                        var header    = mailing.Header.Value;
                        var footer    = mailing.Footer.Value;
                        var htmlText  = mailing.HtmlText.Value;
                        var plainText = mailing.PlainText.Value;

                        if (header != null)
                        {
                            htmlText  = HtmlWorker.ConcatHtml(header.HtmlText.Value, htmlText);
                            plainText = header.PlainText.Value + plainText;
                        }

                        if (footer != null)
                        {
                            htmlText  = HtmlWorker.ConcatHtml(htmlText, footer.HtmlText.Value);
                            plainText = plainText + footer.PlainText.Value;
                        }

                        var translation = new Translation(database);
                        var translator  = new Translator(translation, sending.Address.Value.Contact.Value.Language.Value);
                        var templator   = new Templator(new ContactContentProvider(translator, sending.Address.Value.Contact.Value));
                        htmlText  = templator.Apply(htmlText);
                        plainText = templator.Apply(plainText);

                        try
                        {
                            var language = sending.Address.Value.Contact.Value.Language.Value;
                            var from     = new MimeKit.MailboxAddress(
                                mailing.Sender.Value.MailName.Value[language],
                                mailing.Sender.Value.MailAddress.Value[language]);
                            var to = new MimeKit.MailboxAddress(
                                sending.Address.Value.Contact.Value.ShortHand,
                                sending.Address.Value.Address.Value);
                            var senderKey = mailing.Sender.Value.GpgKeyId.Value == null ? null :
                                            new GpgPrivateKeyInfo(
                                mailing.Sender.Value.GpgKeyId.Value,
                                mailing.Sender.Value.GpgKeyPassphrase.Value);
                            var content  = new Multipart("alternative");
                            var textPart = new TextPart("plain")
                            {
                                Text = plainText
                            };
                            textPart.ContentTransferEncoding = ContentEncoding.QuotedPrintable;
                            content.Add(textPart);
                            var htmlPart = new TextPart("html")
                            {
                                Text = htmlText
                            };
                            htmlPart.ContentTransferEncoding = ContentEncoding.QuotedPrintable;
                            content.Add(htmlPart);

                            Global.Mail.Send(from, to, senderKey, null, mailing.Subject.Value, content);
                            sending.Status.Value   = SendingStatus.Sent;
                            sending.SentDate.Value = DateTime.UtcNow;
                            database.Save(sending);
                            Journal(database, mailing, sending.Address.Value.Contact.Value,
                                    "MailTask.Journal.Sent",
                                    "Journal entry sent mail",
                                    "Task sent mail {0}",
                                    t => mailing.Title.Value);
                        }
                        catch (Exception exception)
                        {
                            sending.Status.Value         = SendingStatus.Failed;
                            sending.FailureMessage.Value = exception.Message;
                            sending.SentDate.Value       = DateTime.UtcNow;
                            database.Save(sending);
                            Journal(database, mailing, sending.Address.Value.Contact.Value,
                                    "MailTask.Journal.Failed",
                                    "Journal entry sending mail failed",
                                    "Task failed sending mail {0}",
                                    t => mailing.Title.Value);
                        }
                    }
                    else
                    {
                        remainingCount++;
                    }
                }
            }

            if (remainingCount < 1)
            {
                mailing.Status.Value   = MailingStatus.Sent;
                mailing.SentDate.Value = DateTime.UtcNow;
                database.Save(mailing);
                Global.Log.Notice("Mailing {0} has finished sending", mailing.Title);
            }
            else
            {
                Global.Log.Notice("Mailing {0} needs to send {1} more mails", mailing.Title, remainingCount);
            }
        }
Beispiel #14
0
        /// <summary>
        /// Tries to parse the given input buffer into a new <see cref="MimeKit.MailboxAddress"/> instance.
        /// </summary>
        /// <remarks>
        /// Parses a single <see cref="MailboxAddress"/>. If the address is not a mailbox address or
        /// there is more than a single mailbox address, then parsing will fail.
        /// </remarks>
        /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
        /// <param name="options">The parser options to use.</param>
        /// <param name="buffer">The input buffer.</param>
        /// <param name="startIndex">The starting index of the input buffer.</param>
        /// <param name="mailbox">The parsed mailbox address.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="options"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="buffer"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <paramref name="startIndex"/> is out of range.
        /// </exception>
        public static bool TryParse(ParserOptions options, byte[] buffer, int startIndex, out MailboxAddress mailbox)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

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

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

            int endIndex = buffer.Length;
            int index    = startIndex;

            if (!TryParse(options, buffer, ref index, endIndex, false, out mailbox))
            {
                return(false);
            }

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

            return(true);
        }
Beispiel #15
0
        internal static bool TryParse(ParserOptions options, byte[] text, ref int index, int endIndex, bool throwOnError, out MailboxAddress mailbox)
        {
            var             flags = AddressParserFlags.AllowMailboxAddress;
            InternetAddress address;

            if (throwOnError)
            {
                flags |= AddressParserFlags.ThrowOnError;
            }

            if (!TryParse(options, text, ref index, endIndex, 0, flags, out address))
            {
                mailbox = null;
                return(false);
            }

            mailbox = (MailboxAddress)address;

            return(true);
        }
Beispiel #16
0
 /// <summary>
 /// Try to parse the given input buffer into a new <see cref="MailboxAddress"/> instance.
 /// </summary>
 /// <remarks>
 /// Parses a single <see cref="MailboxAddress"/>. If the address is not a mailbox address or
 /// there is more than a single mailbox address, then parsing will fail.
 /// </remarks>
 /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
 /// <param name="buffer">The input buffer.</param>
 /// <param name="startIndex">The starting index of the input buffer.</param>
 /// <param name="length">The number of bytes in the input buffer to parse.</param>
 /// <param name="mailbox">The parsed mailbox address.</param>
 /// <exception cref="System.ArgumentNullException">
 /// <paramref name="buffer"/> is <c>null</c>.
 /// </exception>
 /// <exception cref="System.ArgumentOutOfRangeException">
 /// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
 /// a valid range in the byte array.
 /// </exception>
 public static bool TryParse(byte[] buffer, int startIndex, int length, out MailboxAddress mailbox)
 {
     return(TryParse(ParserOptions.Default, buffer, startIndex, length, out mailbox));
 }
Beispiel #17
0
        /// <summary>
        /// Try to parse the given input buffer into a new <see cref="MailboxAddress"/> instance.
        /// </summary>
        /// <remarks>
        /// Parses a single <see cref="MailboxAddress"/>. If the address is not a mailbox address or
        /// there is more than a single mailbox address, then parsing will fail.
        /// </remarks>
        /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
        /// <param name="options">The parser options to use.</param>
        /// <param name="buffer">The input buffer.</param>
        /// <param name="startIndex">The starting index of the input buffer.</param>
        /// <param name="mailbox">The parsed mailbox address.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="options"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="buffer"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <paramref name="startIndex"/> is out of range.
        /// </exception>
        public static bool TryParse(ParserOptions options, byte[] buffer, int startIndex, out MailboxAddress mailbox)
        {
            ParseUtils.ValidateArguments(options, buffer, startIndex);

            int endIndex = buffer.Length;
            int index    = startIndex;

            if (!TryParse(options, buffer, ref index, endIndex, false, out mailbox))
            {
                return(false);
            }

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

            return(true);
        }
 /*
  * tries to sign and encrypt a MimeEntity
  */
 public static MimeEntity SignAndEncryptEntity(MimeEntity entity, MailboxAddress signer, IEnumerable<MailboxAddress> list)
 {
     using (WindowsSecureMimeContext ctx = new WindowsSecureMimeContext(sys.StoreLocation.CurrentUser))
     {
         return ApplicationPkcs7Mime.SignAndEncrypt(ctx, signer, DigestAlgorithm.Sha1, list, entity);
     }
 }
Beispiel #19
0
		/// <summary>
		/// Send the specified message using the supplied sender and recipients.
		/// </summary>
		/// <remarks>
		/// Sends the message by uploading it to an SMTP server using the supplied sender and recipients.
		/// </remarks>
		/// <param name="options">The formatting options.</param>
		/// <param name="message">The message.</param>
		/// <param name="sender">The mailbox address to use for sending the message.</param>
		/// <param name="recipients">The mailbox addresses that should receive the message.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="options"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="message"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="sender"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="recipients"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="SmtpClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="SmtpClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// Authentication is required before sending a message.
		/// </exception>
		/// <exception cref="System.InvalidOperationException">
		/// <para>A sender has not been specified.</para>
		/// <para>-or-</para>
		/// <para>No recipients have been specified.</para>
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// Internationalized formatting was requested but is not supported by the server.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation has been canceled.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="SmtpCommandException">
		/// The SMTP command failed.
		/// </exception>
		/// <exception cref="SmtpProtocolException">
		/// An SMTP protocol exception occurred.
		/// </exception>
		public override void Send (FormatOptions options, MimeMessage message, MailboxAddress sender, IEnumerable<MailboxAddress> recipients, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null)
		{
			if (options == null)
				throw new ArgumentNullException ("options");

			if (message == null)
				throw new ArgumentNullException ("message");

			if (sender == null)
				throw new ArgumentNullException ("sender");

			if (recipients == null)
				throw new ArgumentNullException ("recipients");

			var rcpts = recipients.ToList ();

			if (rcpts.Count == 0)
				throw new InvalidOperationException ("No recipients have been specified.");

			Send (options, message, sender, rcpts, cancellationToken, progress);
		}
Beispiel #20
0
		void RcptTo (MimeMessage message, MailboxAddress mailbox, CancellationToken cancellationToken)
		{
			var command = string.Format ("RCPT TO:<{0}>", mailbox.Address);

			if ((capabilities & SmtpCapabilities.Dsn) != 0) {
				var notify = GetDeliveryStatusNotifications (message, mailbox);

				if (notify.HasValue)
					command += " NOTIFY=" + GetNotifyString (notify.Value);
			}

			if ((capabilities & SmtpCapabilities.Pipelining) != 0) {
				QueueCommand (SmtpCommand.RcptTo, command, cancellationToken);
				return;
			}

			ProcessRcptToResponse (SendCommand (command, cancellationToken), mailbox);
		}
Beispiel #21
0
 /// <summary>
 /// Try to parse the given text into a new <see cref="MailboxAddress"/> instance.
 /// </summary>
 /// <remarks>
 /// Parses a single <see cref="MailboxAddress"/>. If the address is not a mailbox address or
 /// there is more than a single mailbox address, then parsing will fail.
 /// </remarks>
 /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
 /// <param name="text">The text.</param>
 /// <param name="mailbox">The parsed mailbox address.</param>
 /// <exception cref="System.ArgumentNullException">
 /// <paramref name="text"/> is <c>null</c>.
 /// </exception>
 public static bool TryParse(string text, out MailboxAddress mailbox)
 {
     return(TryParse(ParserOptions.Default, text, out mailbox));
 }
Beispiel #22
0
 /// <summary>
 /// Try to parse the given input buffer into a new <see cref="MailboxAddress"/> instance.
 /// </summary>
 /// <remarks>
 /// Parses a single <see cref="MailboxAddress"/>. If the address is not a mailbox address or
 /// there is more than a single mailbox address, then parsing will fail.
 /// </remarks>
 /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
 /// <param name="buffer">The input buffer.</param>
 /// <param name="mailbox">The parsed mailbox address.</param>
 /// <exception cref="System.ArgumentNullException">
 /// <paramref name="buffer"/> is <c>null</c>.
 /// </exception>
 public static bool TryParse(byte[] buffer, out MailboxAddress mailbox)
 {
     return(TryParse(ParserOptions.Default, buffer, out mailbox));
 }
Beispiel #23
0
		void Send (FormatOptions options, MimeMessage message, MailboxAddress sender, IList<MailboxAddress> recipients, CancellationToken cancellationToken, ITransferProgress progress)
		{
			CheckDisposed ();

			if (!IsConnected)
				throw new ServiceNotConnectedException ("The SmtpClient is not connected.");

			var format = options.Clone ();
			format.International = format.International || sender.IsInternational || recipients.Any (x => x.IsInternational);
			format.HiddenHeaders.Add (HeaderId.ContentLength);
			format.HiddenHeaders.Add (HeaderId.ResentBcc);
			format.HiddenHeaders.Add (HeaderId.Bcc);
			format.NewLineFormat = NewLineFormat.Dos;

			if (format.International && (Capabilities & SmtpCapabilities.UTF8) == 0)
				throw new NotSupportedException ("The SMTP server does not support the SMTPUTF8 extension.");

			if (format.International && (Capabilities & SmtpCapabilities.EightBitMime) == 0)
				throw new NotSupportedException ("The SMTP server does not support the 8BITMIME extension.");

			// prepare the message
			if ((Capabilities & SmtpCapabilities.BinaryMime) != 0)
				message.Prepare (EncodingConstraint.None, MaxLineLength);
			else if ((Capabilities & SmtpCapabilities.EightBitMime) != 0)
				message.Prepare (EncodingConstraint.EightBit, MaxLineLength);
			else
				message.Prepare (EncodingConstraint.SevenBit, MaxLineLength);

			// figure out which SMTP extensions we need to use
			var visitor = new ContentTransferEncodingVisitor (capabilities);
			visitor.Visit (message);

			var extensions = visitor.SmtpExtensions;

			if (format.International)
				extensions |= SmtpExtension.UTF8;

			try {
				// Note: if PIPELINING is supported, MailFrom() and RcptTo() will
				// queue their commands instead of sending them immediately.
				MailFrom (message, sender, extensions, cancellationToken);

				var unique = new HashSet<string> (StringComparer.OrdinalIgnoreCase);
				foreach (var recipient in recipients) {
					if (unique.Add (recipient.Address))
						RcptTo (message, recipient, cancellationToken);
				}

				// Note: if PIPELINING is supported, this will flush all outstanding
				// MAIL FROM and RCPT TO commands to the server and then process all
				// of their responses.
				FlushCommandQueue (sender, recipients, cancellationToken);

				if ((extensions & SmtpExtension.BinaryMime) != 0)
					Bdat (format, message, cancellationToken, progress);
				else
					Data (format, message, cancellationToken, progress);
			} catch (ServiceNotAuthenticatedException) {
				// do not disconnect
				throw;
			} catch (SmtpCommandException) {
				Reset (cancellationToken);
				throw;
			} catch {
				Disconnect ();
				throw;
			}
		}
Beispiel #24
0
        internal static bool TryParseMailbox(ParserOptions options, byte[] text, int startIndex, ref int index, int endIndex, string name, int codepage, bool throwOnError, out InternetAddress address)
        {
            DomainList route = null;
            Encoding   encoding;

            try {
                encoding = Encoding.GetEncoding(codepage);
            } catch {
                encoding = Encoding.UTF8;
            }

            address = null;

            // skip over the '<'
            index++;
            if (index >= endIndex)
            {
                if (throwOnError)
                {
                    throw new ParseException(string.Format("Incomplete mailbox at offset {0}", startIndex), startIndex, index);
                }

                return(false);
            }

            if (text[index] == (byte)'@')
            {
                if (!DomainList.TryParse(text, ref index, endIndex, throwOnError, out route))
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Invalid route in mailbox at offset {0}", startIndex), startIndex, index);
                    }

                    return(false);
                }

                if (index + 1 >= endIndex || text[index] != (byte)':')
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Incomplete route in mailbox at offset {0}", startIndex), startIndex, index);
                    }

                    return(false);
                }

                index++;
            }

            string addrspec;

            if (!TryParseAddrspec(text, ref index, endIndex, (byte)'>', throwOnError, out addrspec))
            {
                return(false);
            }

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

            if (index >= endIndex || text[index] != (byte)'>')
            {
                if (options.AddressParserComplianceMode == RfcComplianceMode.Strict)
                {
                    if (throwOnError)
                    {
                        throw new ParseException(string.Format("Unexpected end of mailbox at offset {0}", startIndex), startIndex, index);
                    }

                    return(false);
                }
            }
            else
            {
                index++;
            }

            if (route != null)
            {
                address = new MailboxAddress(encoding, name, route, addrspec);
            }
            else
            {
                address = new MailboxAddress(encoding, name, addrspec);
            }

            return(true);
        }
Beispiel #25
0
		void FlushCommandQueue (MailboxAddress sender, IList<MailboxAddress> recipients, CancellationToken cancellationToken)
		{
			if (queued.Count == 0)
				return;

			try {
				var responses = new List<SmtpResponse> ();
				Exception rex = null;
				int rcpt = 0;

				// Note: queued commands are buffered by the stream
				Stream.Flush (cancellationToken);

				// Note: we need to read all responses from the server before we can process
				// them in case any of them have any errors so that we can RSET the state.
				try {
					for (int i = 0; i < queued.Count; i++)
						responses.Add (Stream.ReadResponse (cancellationToken));
				} catch (Exception ex) {
					// Note: save this exception for later (it may be related to
					// an error response for a MAIL FROM or RCPT TO command).
					rex = ex;
				}

				for (int i = 0; i < responses.Count; i++) {
					switch (queued[i]) {
					case SmtpCommand.MailFrom:
						ProcessMailFromResponse (responses[i], sender);
						break;
					case SmtpCommand.RcptTo:
						ProcessRcptToResponse (responses[i], recipients[rcpt++]);
						break;
					}
				}

				if (rex != null)
					throw new SmtpProtocolException ("Error reading a response from the SMTP server.", rex);
			} finally {
				queued.Clear ();
			}
		}
Beispiel #26
0
        internal static bool TryParse(ParserOptions options, byte[] text, ref int index, int endIndex, bool throwOnError, out InternetAddress address)
        {
            address = null;

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

            if (index == endIndex)
            {
                if (throwOnError)
                {
                    throw new ParseException("No address found.", index, index);
                }

                return(false);
            }

            // keep track of the start & length of the phrase
            int startIndex = index;
            int length     = 0;

            while (index < endIndex && ParseUtils.SkipWord(text, ref index, endIndex, throwOnError))
            {
                length = index - startIndex;

                do
                {
                    if (!ParseUtils.SkipCommentsAndWhiteSpace(text, ref index, endIndex, throwOnError))
                    {
                        return(false);
                    }

                    // Note: some clients don't quote dots in the name
                    if (index >= endIndex || text[index] != (byte)'.')
                    {
                        break;
                    }

                    index++;
                } while (true);
            }

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

            // specials    =  "(" / ")" / "<" / ">" / "@"  ; Must be in quoted-
            //             /  "," / ";" / ":" / "\" / <">  ;  string, to use
            //             /  "." / "[" / "]"              ;  within a word.

            if (index >= endIndex || text[index] == (byte)',' || text[index] == ';')
            {
                // we've completely gobbled up an addr-spec w/o a domain
                byte   sentinel = index < endIndex ? text[index] : (byte)',';
                string name, addrspec;

                // rewind back to the beginning of the local-part
                index = startIndex;

                if (!TryParseAddrspec(text, ref index, endIndex, sentinel, throwOnError, out addrspec))
                {
                    return(false);
                }

                ParseUtils.SkipWhiteSpace(text, ref index, endIndex);

                if (index < endIndex && text[index] == '(')
                {
                    int comment = index;

                    if (!ParseUtils.SkipComment(text, ref index, endIndex))
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Incomplete comment token at offset {0}", comment), comment, index);
                        }

                        return(false);
                    }

                    comment++;

                    name = Rfc2047.DecodePhrase(options, text, comment, (index - 1) - comment).Trim();
                }
                else
                {
                    name = string.Empty;
                }

                address = new MailboxAddress(name, addrspec);

                return(true);
            }

            if (text[index] == (byte)':')
            {
                // rfc2822 group address
                int    codepage = -1;
                string name;

                if (length > 0)
                {
                    name = Rfc2047.DecodePhrase(options, text, startIndex, length, out codepage);
                }
                else
                {
                    name = string.Empty;
                }

                if (codepage == -1)
                {
                    codepage = 65001;
                }

                return(TryParseGroup(options, text, startIndex, ref index, endIndex, MimeUtils.Unquote(name), codepage, throwOnError, out address));
            }

            if (text[index] == (byte)'<')
            {
                // rfc2822 angle-addr token
                int    codepage = -1;
                string name;

                if (length > 0)
                {
                    name = Rfc2047.DecodePhrase(options, text, startIndex, length, out codepage);
                }
                else
                {
                    name = string.Empty;
                }

                if (codepage == -1)
                {
                    codepage = 65001;
                }

                return(TryParseMailbox(options, text, startIndex, ref index, endIndex, MimeUtils.Unquote(name), codepage, throwOnError, out address));
            }

            if (text[index] == (byte)'@')
            {
                // we're either in the middle of an addr-spec token or we completely gobbled up an addr-spec w/o a domain
                string name, addrspec;

                // rewind back to the beginning of the local-part
                index = startIndex;

                if (!TryParseAddrspec(text, ref index, endIndex, (byte)',', throwOnError, out addrspec))
                {
                    return(false);
                }

                ParseUtils.SkipWhiteSpace(text, ref index, endIndex);

                if (index < endIndex && text[index] == '(')
                {
                    int comment = index;

                    if (!ParseUtils.SkipComment(text, ref index, endIndex))
                    {
                        if (throwOnError)
                        {
                            throw new ParseException(string.Format("Incomplete comment token at offset {0}", comment), comment, index);
                        }

                        return(false);
                    }

                    comment++;

                    name = Rfc2047.DecodePhrase(options, text, comment, (index - 1) - comment).Trim();
                }
                else
                {
                    name = string.Empty;
                }

                address = new MailboxAddress(name, addrspec);

                return(true);
            }

            if (throwOnError)
            {
                throw new ParseException(string.Format("Invalid address token at offset {0}", startIndex), startIndex, index);
            }

            return(false);
        }
Beispiel #27
0
        internal static bool TryParseMailbox(ParserOptions options, byte[] text, int startIndex, ref int index, int endIndex, string name, int codepage, bool throwOnError, out InternetAddress address)
        {
            Encoding encoding = Encoding.GetEncoding (codepage);
            DomainList route = null;

            address = null;

            // skip over the '<'
            index++;
            if (index >= endIndex) {
                if (throwOnError)
                    throw new ParseException (string.Format ("Incomplete mailbox at offset {0}", startIndex), startIndex, index);

                return false;
            }

            if (text[index] == (byte) '@') {
                if (!DomainList.TryParse (text, ref index, endIndex, throwOnError, out route)) {
                    if (throwOnError)
                        throw new ParseException (string.Format ("Invalid route in mailbox at offset {0}", startIndex), startIndex, index);

                    return false;
                }

                if (index + 1 >= endIndex || text[index] != (byte) ':') {
                    if (throwOnError)
                        throw new ParseException (string.Format ("Incomplete route in mailbox at offset {0}", startIndex), startIndex, index);

                    return false;
                }

                index++;
            }

            string addrspec;
            if (!TryParseAddrspec (text, ref index, endIndex, (byte) '>', throwOnError, out addrspec))
                return false;

            if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
                return false;

            if (index >= endIndex || text[index] != (byte) '>') {
                if (options.AddressParserComplianceMode == RfcComplianceMode.Strict) {
                    if (throwOnError)
                        throw new ParseException (string.Format ("Unexpected end of mailbox at offset {0}", startIndex), startIndex, index);

                    return false;
                }
            } else {
                index++;
            }

            if (route != null)
                address = new MailboxAddress (encoding, name, route, addrspec);
            else
                address = new MailboxAddress (encoding, name, addrspec);

            return true;
        }
Beispiel #28
0
        internal static bool TryParse(ParserOptions options, byte[] text, ref int index, int endIndex, bool throwOnError, out InternetAddress address)
        {
            address = null;

            if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
                return false;

            if (index == endIndex) {
                if (throwOnError)
                    throw new ParseException ("No address found.", index, index);

                return false;
            }

            // keep track of the start & length of the phrase
            int startIndex = index;
            int length = 0;

            while (index < endIndex && ParseUtils.Skip8bitWord (text, ref index, endIndex, throwOnError)) {
                length = index - startIndex;

                do {
                    if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
                        return false;

                    // Note: some clients don't quote dots in the name
                    if (index >= endIndex || text[index] != (byte) '.')
                        break;

                    index++;
                } while (true);
            }

            if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
                return false;

            // specials    =  "(" / ")" / "<" / ">" / "@"  ; Must be in quoted-
            //             /  "," / ";" / ":" / "\" / <">  ;  string, to use
            //             /  "." / "[" / "]"              ;  within a word.

            if (index >= endIndex || text[index] == (byte) ',' || text[index] == ';') {
                // we've completely gobbled up an addr-spec w/o a domain
                byte sentinel = index < endIndex ? text[index] : (byte) ',';
                string name, addrspec;

                // rewind back to the beginning of the local-part
                index = startIndex;

                if (!TryParseAddrspec (text, ref index, endIndex, sentinel, throwOnError, out addrspec))
                    return false;

                ParseUtils.SkipWhiteSpace (text, ref index, endIndex);

                if (index < endIndex && text[index] == '(') {
                    int comment = index;

                    if (!ParseUtils.SkipComment (text, ref index, endIndex)) {
                        if (throwOnError)
                            throw new ParseException (string.Format ("Incomplete comment token at offset {0}", comment), comment, index);

                        return false;
                    }

                    comment++;

                    name = Rfc2047.DecodePhrase (options, text, comment, (index - 1) - comment).Trim ();
                } else {
                    name = string.Empty;
                }

                address = new MailboxAddress (name, addrspec);

                return true;
            }

            if (text[index] == (byte) ':') {
                // rfc2822 group address
                int codepage = -1;
                string name;

                if (length > 0) {
                    name = Rfc2047.DecodePhrase (options, text, startIndex, length, out codepage);
                } else {
                    name = string.Empty;
                }

                if (codepage == -1)
                    codepage = 65001;

                return TryParseGroup (options, text, startIndex, ref index, endIndex, MimeUtils.Unquote (name), codepage, throwOnError, out address);
            }

            if (text[index] == (byte) '<') {
                // rfc2822 angle-addr token
                int codepage = -1;
                string name;

                if (length > 0) {
                    name = Rfc2047.DecodePhrase (options, text, startIndex, length, out codepage);
                } else {
                    name = string.Empty;
                }

                if (codepage == -1)
                    codepage = 65001;

                return TryParseMailbox (options, text, startIndex, ref index, endIndex, MimeUtils.Unquote (name), codepage, throwOnError, out address);
            }

            if (text[index] == (byte) '@') {
                // we're either in the middle of an addr-spec token or we completely gobbled up an addr-spec w/o a domain
                string name, addrspec;

                // rewind back to the beginning of the local-part
                index = startIndex;

                if (!TryParseAddrspec (text, ref index, endIndex, (byte) ',', throwOnError, out addrspec))
                    return false;

                ParseUtils.SkipWhiteSpace (text, ref index, endIndex);

                if (index < endIndex && text[index] == '(') {
                    int comment = index;

                    if (!ParseUtils.SkipComment (text, ref index, endIndex)) {
                        if (throwOnError)
                            throw new ParseException (string.Format ("Incomplete comment token at offset {0}", comment), comment, index);

                        return false;
                    }

                    comment++;

                    name = Rfc2047.DecodePhrase (options, text, comment, (index - 1) - comment).Trim ();
                } else {
                    name = string.Empty;
                }

                address = new MailboxAddress (name, addrspec);

                return true;
            }

            if (throwOnError)
                throw new ParseException (string.Format ("Invalid address token at offset {0}", startIndex), startIndex, index);

            return false;
        }
        /// <summary>
        /// Tries to parse the given input buffer into a new <see cref="MimeKit.MailboxAddress"/> instance.
        /// </summary>
        /// <remarks>
        /// Parses a single <see cref="MailboxAddress"/>. If the the address is not a mailbox address or
        /// there is more than a single mailbox address, then parsing will fail.
        /// </remarks>
        /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
        /// <param name="options">The parser options to use.</param>
        /// <param name="buffer">The input buffer.</param>
        /// <param name="startIndex">The starting index of the input buffer.</param>
        /// <param name="mailbox">The parsed mailbox address.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="options"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="buffer"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <paramref name="startIndex"/> is out of range.
        /// </exception>
        public static bool TryParse(ParserOptions options, byte[] buffer, int startIndex, out MailboxAddress mailbox)
        {
            InternetAddress address;

            if (!InternetAddress.TryParse(options, buffer, startIndex, out address))
            {
                mailbox = null;
                return(false);
            }

            mailbox = address as MailboxAddress;

            return(mailbox != null);
        }
Beispiel #30
0
 static void ProcessRcptToResponse(SmtpResponse response, MailboxAddress mailbox)
 {
     switch (response.StatusCode) {
     case SmtpStatusCode.UserNotLocalWillForward:
     case SmtpStatusCode.Ok:
         break;
     case SmtpStatusCode.UserNotLocalTryAlternatePath:
     case SmtpStatusCode.MailboxNameNotAllowed:
     case SmtpStatusCode.MailboxUnavailable:
     case SmtpStatusCode.MailboxBusy:
         throw new SmtpCommandException (SmtpErrorCode.RecipientNotAccepted, response.StatusCode, mailbox, response.Response);
     case SmtpStatusCode.AuthenticationRequired:
         throw new UnauthorizedAccessException (response.Response);
     default:
         throw new SmtpCommandException (SmtpErrorCode.UnexpectedStatusCode, response.StatusCode, response.Response);
     }
 }
Beispiel #31
0
        void FlushCommandQueue(MailboxAddress sender, IList<MailboxAddress> recipients, CancellationToken cancellationToken)
        {
            if (queued.Count == 0)
                return;

            try {
                var responses = new List<SmtpResponse> ();
                int rcpt = 0;
                int nread;

                queue.Position = 0;
                while ((nread = queue.Read (input, 0, input.Length)) > 0) {
                    cancellationToken.ThrowIfCancellationRequested ();
                    stream.Write (input, 0, nread);
                    logger.LogClient (input, 0, nread);
                }

                // Note: we need to read all responses from the server before we can process
                // them in case any of them have any errors so that we can RSET the state.
                for (int i = 0; i < queued.Count; i++)
                    responses.Add (ReadResponse (cancellationToken));

                for (int i = 0; i < queued.Count; i++) {
                    switch (queued [i]) {
                    case SmtpCommand.MailFrom:
                        ProcessMailFromResponse (responses[i], sender);
                        break;
                    case SmtpCommand.RcptTo:
                        ProcessRcptToResponse (responses[i], recipients[rcpt++]);
                        break;
                    }
                }
            } finally {
                queue.SetLength (0);
                queued.Clear ();
            }
        }
Beispiel #32
0
        static string GetMailFromCommand(MailboxAddress mailbox, SmtpExtension extensions)
        {
            if ((extensions & SmtpExtension.BinaryMime) != 0)
                return string.Format ("MAIL FROM:<{0}> BODY=BINARYMIME", mailbox.Address);

            if ((extensions & SmtpExtension.EightBitMime) != 0)
                return string.Format ("MAIL FROM:<{0}> BODY=8BITMIME", mailbox.Address);

            return string.Format ("MAIL FROM:<{0}>", mailbox.Address);
        }
Beispiel #33
0
 static void ProcessMailFromResponse(SmtpResponse response, MailboxAddress mailbox)
 {
     switch (response.StatusCode) {
     case SmtpStatusCode.Ok:
         break;
     case SmtpStatusCode.MailboxNameNotAllowed:
     case SmtpStatusCode.MailboxUnavailable:
         throw new SmtpCommandException (SmtpErrorCode.SenderNotAccepted, response.StatusCode, mailbox, response.Response);
     case SmtpStatusCode.AuthenticationRequired:
         throw new UnauthorizedAccessException (response.Response);
     default:
         throw new SmtpCommandException (SmtpErrorCode.UnexpectedStatusCode, response.StatusCode, response.Response);
     }
 }
Beispiel #34
0
        void Send(MimeMessage message, MailboxAddress sender, IList<MailboxAddress> recipients, CancellationToken cancellationToken)
        {
            CheckDisposed ();

            if (!IsConnected)
                throw new InvalidOperationException ("The SmtpClient is not connected.");

            var extensions = PrepareMimeEntity (message);

            try {
                // Note: if PIPELINING is supported, MailFrom() and RcptTo() will
                // queue their commands instead of sending them immediately.
                MailFrom (sender, extensions, cancellationToken);
                foreach (var recipient in recipients)
                    RcptTo (recipient, cancellationToken);

                // Note: if PIPELINING is supported, this will flush all outstanding
                // MAIL FROM and RCPT TO commands to the server and then process all
                // of their responses.
                FlushCommandQueue (sender, recipients, cancellationToken);

                Data (message, cancellationToken);
            } catch (UnauthorizedAccessException) {
                // do not disconnect
                throw;
            } catch (SmtpCommandException) {
                Reset (cancellationToken);
                throw;
            } catch {
                Disconnect ();
                throw;
            }
        }
Beispiel #35
0
        /// <summary>
        /// Send the specified message using the supplied sender and recipients.
        /// </summary>
        /// <remarks>
        /// Sends the message by uploading it to an SMTP server using the supplied sender and recipients.
        /// </remarks>
        /// <param name="message">The message.</param>
        /// <param name="sender">The mailbox address to use for sending the message.</param>
        /// <param name="recipients">The mailbox addresses that should receive the message.</param>
        /// <param name="cancellationToken">A cancellation token.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="message"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="sender"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="recipients"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.ObjectDisposedException">
        /// The <see cref="SmtpClient"/> has been disposed.
        /// </exception>
        /// <exception cref="System.InvalidOperationException">
        /// <para>The <see cref="SmtpClient"/> is not connected.</para>
        /// <para>-or-</para>
        /// <para>A sender has not been specified.</para>
        /// <para>-or-</para>
        /// <para>No recipients have been specified.</para>
        /// </exception>
        /// <exception cref="System.OperationCanceledException">
        /// The operation has been canceled.
        /// </exception>
        /// <exception cref="System.UnauthorizedAccessException">
        /// Authentication is required before sending a message.
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An I/O error occurred.
        /// </exception>
        /// <exception cref="SmtpCommandException">
        /// The SMTP command failed.
        /// </exception>
        /// <exception cref="SmtpProtocolException">
        /// An SMTP protocol exception occurred.
        /// </exception>
        public void Send(MimeMessage message, MailboxAddress sender, IEnumerable<MailboxAddress> recipients, CancellationToken cancellationToken = default (CancellationToken))
        {
            if (message == null)
                throw new ArgumentNullException ("message");

            if (sender == null)
                throw new ArgumentNullException ("sender");

            if (recipients == null)
                throw new ArgumentNullException ("recipients");

            var rcpts = recipients.ToList ();

            if (rcpts.Count == 0)
                throw new InvalidOperationException ("No recipients have been specified.");

            Send (message, sender, rcpts, cancellationToken);
        }
Beispiel #36
0
        void MailFrom(MailboxAddress mailbox, SmtpExtension extensions, CancellationToken cancellationToken)
        {
            var command = GetMailFromCommand (mailbox, extensions);

            if ((capabilities & SmtpCapabilities.Pipelining) != 0) {
                QueueCommand (SmtpCommand.MailFrom, command);
                return;
            }

            ProcessMailFromResponse (SendCommand (command, cancellationToken), mailbox);
        }
Beispiel #37
0
        void RcptTo(MailboxAddress mailbox, CancellationToken cancellationToken)
        {
            var command = string.Format ("RCPT TO:<{0}>", mailbox.Address);

            if ((capabilities & SmtpCapabilities.Pipelining) != 0) {
                QueueCommand (SmtpCommand.RcptTo, command);
                return;
            }

            ProcessRcptToResponse (SendCommand (command, cancellationToken), mailbox);
        }
Beispiel #38
0
		void HeadersChanged (object o, HeaderListChangedEventArgs e)
		{
			InternetAddressList list;
			InternetAddress address;
			byte[] rawValue;
			int index = 0;

			switch (e.Action) {
			case HeaderListChangedAction.Added:
				if (addresses.TryGetValue (e.Header.Field, out list)) {
					AddAddresses (e.Header, list);
					break;
				}

				rawValue = e.Header.RawValue;

				switch (e.Header.Id) {
				case HeaderId.MimeVersion:
					MimeUtils.TryParse (rawValue, 0, rawValue.Length, out version);
					break;
				case HeaderId.References:
					references.Changed -= ReferencesChanged;
					foreach (var msgid in MimeUtils.EnumerateReferences (rawValue, 0, rawValue.Length))
						references.Add (msgid);
					references.Changed += ReferencesChanged;
					break;
				case HeaderId.InReplyTo:
					inreplyto = MimeUtils.EnumerateReferences (rawValue, 0, rawValue.Length).FirstOrDefault ();
					break;
				case HeaderId.ResentMessageId:
					resentMessageId = MimeUtils.EnumerateReferences (rawValue, 0, rawValue.Length).FirstOrDefault ();
					break;
				case HeaderId.MessageId:
					messageId = MimeUtils.EnumerateReferences (rawValue, 0, rawValue.Length).FirstOrDefault ();
					break;
				case HeaderId.ResentSender:
					if (InternetAddress.TryParse (Headers.Options, rawValue, ref index, rawValue.Length, false, out address))
						resentSender = address as MailboxAddress;
					break;
				case HeaderId.Sender:
					if (InternetAddress.TryParse (Headers.Options, rawValue, ref index, rawValue.Length, false, out address))
						sender = address as MailboxAddress;
					break;
				case HeaderId.ResentDate:
					DateUtils.TryParse (rawValue, 0, rawValue.Length, out resentDate);
					break;
				case HeaderId.Importance:
					switch (e.Header.Value.ToLowerInvariant ().Trim ()) {
					case "high": importance = MessageImportance.High; break;
					case "low": importance = MessageImportance.Low; break;
					default: importance = MessageImportance.Normal; break;
					}
					break;
				case HeaderId.Priority:
					switch (e.Header.Value.ToLowerInvariant ().Trim ()) {
					case "non-urgent": priority = MessagePriority.NonUrgent; break;
					case "urgent": priority = MessagePriority.Urgent; break;
					default: priority = MessagePriority.Normal; break;
					}
					break;
				case HeaderId.Date:
					DateUtils.TryParse (rawValue, 0, rawValue.Length, out date);
					break;
				}
				break;
			case HeaderListChangedAction.Changed:
			case HeaderListChangedAction.Removed:
				if (addresses.TryGetValue (e.Header.Field, out list)) {
					ReloadAddressList (e.Header.Id, list);
					break;
				}

				ReloadHeader (e.Header.Id);
				break;
			case HeaderListChangedAction.Cleared:
				foreach (var kvp in addresses) {
					kvp.Value.Changed -= InternetAddressListChanged;
					kvp.Value.Clear ();
					kvp.Value.Changed += InternetAddressListChanged;
				}

				references.Changed -= ReferencesChanged;
				references.Clear ();
				references.Changed += ReferencesChanged;

				importance = MessageImportance.Normal;
				priority = MessagePriority.Normal;
				resentMessageId = null;
				resentSender = null;
				inreplyto = null;
				messageId = null;
				version = null;
				sender = null;
				break;
			default:
				throw new ArgumentOutOfRangeException ();
			}
		}
Beispiel #39
0
		void ReloadHeader (HeaderId id)
		{
			if (id == HeaderId.Unknown)
				return;

			switch (id) {
			case HeaderId.ResentMessageId:
				resentMessageId = null;
				break;
			case HeaderId.ResentSender:
				resentSender = null;
				break;
			case HeaderId.ResentDate:
				resentDate = DateTimeOffset.MinValue;
				break;
			case HeaderId.References:
				references.Changed -= ReferencesChanged;
				references.Clear ();
				references.Changed += ReferencesChanged;
				break;
			case HeaderId.InReplyTo:
				inreplyto = null;
				break;
			case HeaderId.MessageId:
				messageId = null;
				break;
			case HeaderId.Sender:
				sender = null;
				break;
			case HeaderId.Importance:
				importance = MessageImportance.Normal;
				break;
			case HeaderId.Priority:
				priority = MessagePriority.Normal;
				break;
			case HeaderId.Date:
				date = DateTimeOffset.MinValue;
				break;
			}

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

				var rawValue = header.RawValue;
				InternetAddress address;
				int index = 0;

				switch (id) {
				case HeaderId.MimeVersion:
					if (MimeUtils.TryParse (rawValue, 0, rawValue.Length, out version))
						return;
					break;
				case HeaderId.References:
					references.Changed -= ReferencesChanged;
					foreach (var msgid in MimeUtils.EnumerateReferences (rawValue, 0, rawValue.Length))
						references.Add (msgid);
					references.Changed += ReferencesChanged;
					break;
				case HeaderId.InReplyTo:
					inreplyto = MimeUtils.EnumerateReferences (rawValue, 0, rawValue.Length).FirstOrDefault ();
					break;
				case HeaderId.ResentMessageId:
					resentMessageId = MimeUtils.EnumerateReferences (rawValue, 0, rawValue.Length).FirstOrDefault ();
					if (resentMessageId != null)
						return;
					break;
				case HeaderId.MessageId:
					messageId = MimeUtils.EnumerateReferences (rawValue, 0, rawValue.Length).FirstOrDefault ();
					if (messageId != null)
						return;
					break;
				case HeaderId.ResentSender:
					if (InternetAddress.TryParse (Headers.Options, rawValue, ref index, rawValue.Length, false, out address))
						resentSender = address as MailboxAddress;
					if (resentSender != null)
						return;
					break;
				case HeaderId.Sender:
					if (InternetAddress.TryParse (Headers.Options, rawValue, ref index, rawValue.Length, false, out address))
						sender = address as MailboxAddress;
					if (sender != null)
						return;
					break;
				case HeaderId.ResentDate:
					if (DateUtils.TryParse (rawValue, 0, rawValue.Length, out resentDate))
						return;
					break;
				case HeaderId.Importance:
					switch (header.Value.ToLowerInvariant ().Trim ()) {
					case "high": importance = MessageImportance.High; break;
					case "low": importance = MessageImportance.Low; break;
					default: importance = MessageImportance.Normal; break;
					}
					break;
				case HeaderId.Priority:
					switch (header.Value.ToLowerInvariant ().Trim ()) {
					case "non-urgent": priority = MessagePriority.NonUrgent; break;
					case "urgent": priority = MessagePriority.Urgent; break;
					default: priority = MessagePriority.Normal; break;
					}
					break;
				case HeaderId.Date:
					if (DateUtils.TryParse (rawValue, 0, rawValue.Length, out date))
						return;
					break;
				}
			}
		}
		/// <summary>
		/// Gets the <see cref="CmsSigner"/> for the specified mailbox.
		/// </summary>
		/// <returns>A <see cref="CmsSigner"/>.</returns>
		/// <param name="mailbox">The mailbox.</param>
		/// <param name="digestAlgo">The preferred digest algorithm.</param>
		/// <exception cref="CertificateNotFoundException">
		/// A certificate for the specified <paramref name="mailbox"/> could not be found.
		/// </exception>
		protected override CmsSigner GetCmsSigner (MailboxAddress mailbox, DigestAlgorithm digestAlgo)
		{
			var now = DateTime.Now;

			foreach (var certificate in certificates) {
				AsymmetricKeyParameter key;

				if (certificate.NotBefore > now || certificate.NotAfter < now)
					continue;

				var keyUsage = certificate.GetKeyUsageFlags ();
				if (keyUsage != 0 && (keyUsage & SecureMimeContext.DigitalSignatureKeyUsageFlags) == 0)
					continue;

				if (!keys.TryGetValue (certificate, out key))
					continue;

				if (certificate.GetSubjectEmailAddress () == mailbox.Address) {
					var signer = new CmsSigner (certificate, key);
					signer.DigestAlgorithm = digestAlgo;
					return signer;
				}
			}

			throw new CertificateNotFoundException (mailbox, "A valid signing certificate could not be found.");
		}
		/// <summary>
		/// Gets the <see cref="CmsRecipient"/> for the specified mailbox.
		/// </summary>
		/// <returns>A <see cref="CmsRecipient"/>.</returns>
		/// <param name="mailbox">The mailbox.</param>
		/// <exception cref="CertificateNotFoundException">
		/// A certificate for the specified <paramref name="mailbox"/> could not be found.
		/// </exception>
		protected override CmsRecipient GetCmsRecipient (MailboxAddress mailbox)
		{
			var now = DateTime.Now;

			foreach (var certificate in certificates) {
				if (certificate.NotBefore > now || certificate.NotAfter < now)
					continue;

				var keyUsage = certificate.GetKeyUsageFlags ();
				if (keyUsage != 0 && (keyUsage & X509KeyUsageFlags.KeyEncipherment) == 0)
					continue;

				if (certificate.GetSubjectEmailAddress () == mailbox.Address) {
					var recipient = new CmsRecipient (certificate);
					EncryptionAlgorithm[] algorithms;

					if (capabilities.TryGetValue (certificate, out algorithms))
						recipient.EncryptionAlgorithms = algorithms;

					return recipient;
				}
			}

			throw new CertificateNotFoundException (mailbox, "A valid certificate could not be found.");
		}
        public IActionResult Submit(ContactForm form)
        {
            if (!ModelState.IsValid)
                return View("Index", form);

            var emailMessage = new MimeMessage();

            var address = new MailboxAddress(Settings.Title, Settings.EmailFromAndTo);
            emailMessage.From.Add(address);
            emailMessage.To.Add(address);
            emailMessage.Subject = Settings.EmailSubject;
            var message = "Name: " + form.Name + Environment.NewLine
                + "Company: " + form.Company + Environment.NewLine
                + form.PreferredMethod + ": " + form.Email + form.Phone + Environment.NewLine
                + "Message:" + Environment.NewLine
                + form.Message;
            emailMessage.Body = new TextPart("plain") { Text = message };

            using (var client = new SmtpClient())
            {
                client.Connect(Settings.EmailServer, 465);
                client.Authenticate(Settings.EmailUser, Cache.Config["EmailPassword"]);
                client.Send(emailMessage);
                client.Disconnect(true);
            }
            return View("Thanks");
        }