Example #1
0
 Task UploadAsyncInternal(IAbsoluteFilePath localFile, Uri uri,
                          ITransferProgress progress = null)
 {
     ConfirmStrategySupported(uri);
     return
         (GetStrategy(uri).UploadAsync(GetSpec(localFile, uri, progress)));
 }
Example #2
0
 public byte[] Download(Uri uri, ITransferProgress progress)
 {
     using (var tmpFile = new TmpFileCreated()) {
         _downloader.Download(uri, tmpFile.FilePath, progress);
         return(File.ReadAllBytes(tmpFile.FilePath.ToString()));
     }
 }
Example #3
0
        public IDisposable SetupUploadTransferProgress(ITransferProgress transferProgress, TimeSpan timeout) {
            var lastTime = Tools.Generic.GetCurrentUtcDateTime;
            long lastBytes = 0;

            UploadProgressChanged +=
                (sender, args) => {
                    var bytes = args.BytesReceived;
                    var now = Tools.Generic.GetCurrentUtcDateTime;

                    transferProgress.FileSizeTransfered = bytes;
                    long? speed = null;
                    if (lastBytes != 0) {
                        var timeSpan = now - lastTime;
                        var bytesChange = bytes - lastBytes;

                        if (timeSpan.TotalMilliseconds > 0)
                            speed = (long) (bytesChange/(timeSpan.TotalMilliseconds/1000.0));
                    }
                    transferProgress.Update(speed, args.ProgressPercentage);
                    lastTime = now;
                    lastBytes = bytes;
                };

            UploadFileCompleted += (sender, args) => { transferProgress.Completed = true; };

            var timer = new TimerWithElapsedCancellation(500, () => {
                if (!transferProgress.Completed
                    && Tools.Generic.LongerAgoThan(lastTime, timeout)) {
                    CancelAsync();
                    return false;
                }
                return !transferProgress.Completed;
            });
            return timer;
        }
 public override Task SendAsync(MimeMessage message,
                                CancellationToken cancellationToken = default,
                                ITransferProgress progress          = null)
 {
     MessageIsSent = true;
     return(Task.CompletedTask);
 }
        public bool CheckZsyncLoop(Process process, string data, ITransferProgress progress)
        {
            // By not resetting the loopdata/counts we set ourselves up for a situation where it's possible to detect loops that span multiple lines..
            if (!ZsyncLoop.IsMatch(data))
            {
                return(false);
            }

            if (progress.ZsyncLoopData == null)
            {
                progress.ZsyncLoopData  = data;
                progress.ZsyncLoopCount = 0;
                return(false);
            }

            if (progress.ZsyncLoopData.Equals(data, StringComparison.OrdinalIgnoreCase))
            {
                var loopCount = ++progress.ZsyncLoopCount;
                if (loopCount < 2)
                {
                    return(false);
                }
                if (!process.SafeHasExited())
                {
                    process.TryKill();
                }
                return(true);
            }

            progress.ZsyncLoopData  = data;
            progress.ZsyncLoopCount = 0;

            return(false);
        }
        public bool CheckZsyncLoop(Process process, string data, ITransferProgress progress) {
            // By not resetting the loopdata/counts we set ourselves up for a situation where it's possible to detect loops that span multiple lines..
            if (!ZsyncLoop.IsMatch(data))
                return false;

            if (progress.ZsyncLoopData == null) {
                progress.ZsyncLoopData = data;
                progress.ZsyncLoopCount = 0;
                return false;
            }

            if (progress.ZsyncLoopData.Equals(data, StringComparison.OrdinalIgnoreCase)) {
                var loopCount = ++progress.ZsyncLoopCount;
                if (loopCount < 2)
                    return false;
                if (!process.SafeHasExited())
                    process.TryKill();
                return true;
            }

            progress.ZsyncLoopData = data;
            progress.ZsyncLoopCount = 0;

            return false;
        }
 public void Pull(ITransferProgress status, string remoteSub = null, string localSub = null) {
     CreateSshFolder();
     HandleRsyncResponse(_rsyncLauncher.RunAndProcess(
         status,
         JoinPathsIfNeeded(Remote, remoteSub),
         JoinPathsIfNeeded(Local, localSub),
         BuildOptions()));
 }
Example #8
0
        public async Task <byte[]> DownloadAsync(Uri uri, ITransferProgress progress)
        {
            using (var tmpFile = new TmpFileCreated()) {
                await _downloader.DownloadAsync(uri, tmpFile.FilePath, progress).ConfigureAwait(false);

                return(File.ReadAllBytes(tmpFile.FilePath.ToString()));
            }
        }
Example #9
0
 public override void Send(FormatOptions options, MimeMessage message, CancellationToken cancellationToken = new CancellationToken(),
                           ITransferProgress progress = null)
 {
     if (SendException != null)
     {
         throw SendException;
     }
 }
Example #10
0
        /*
         * public override object SyncRoot { get; }
         * protected override string Protocol { get; }
         * public override HashSet<string> AuthenticationMechanisms { get; }
         * public override int Timeout { get; set; }
         * public override bool IsConnected { get; }
         * public override bool IsSecure { get; }
         * public override bool IsAuthenticated { get; }
         */

        public override void Send(MimeMessage message, CancellationToken cancellationToken = new CancellationToken(),
                                  ITransferProgress progress = null)
        {
            if (SendException != null)
            {
                throw SendException;                         // in use
            }
        }
        protected TransferSpec(Uri uri, IAbsoluteFilePath localFile, ITransferProgress progress) {
            Contract.Requires<ArgumentNullException>(uri != null);
            Contract.Requires<ArgumentNullException>(localFile != null);

            Uri = uri;
            LocalFile = localFile;
            Progress = progress ?? new TransferProgress();
        }
Example #12
0
        public ProcessExitResultWithOutput RunAndProcess(ITransferProgress progress, string source, string destination,
                                                         RsyncOptions options = null)
        {
            var processInfo = BuildProcessInfo(progress, source, destination, options);

            return(ProcessExitResultWithOutput.FromProcessExitResult(_processManager.LaunchAndProcess(processInfo),
                                                                     progress.Output));
        }
Example #13
0
 LaunchAndProcessInfo BuildProcessInfo(ITransferProgress progress, string source, string destination,
                                       RsyncOptions options) => new LaunchAndProcessInfo(GetProcessStartInfo(source, destination, options))
 {
     StandardOutputAction = (process, data) => _parser.ParseOutput(process, data, progress),
     StandardErrorAction  = (process, data) => _parser.ParseOutput(process, data, progress),
     MonitorOutput        = _processManager.DefaultMonitorOutputTimeOut,
     MonitorResponding    = _processManager.DefaultMonitorRespondingTimeOut
 };
 public ProcessExitResultWithOutput RunAndProcess(ITransferProgress progress, string source, string destination,
     CancellationToken token,
     RsyncOptions options = null) {
     var processInfo = BuildProcessInfo(progress, source, destination, options);
     processInfo.CancellationToken = token;
     return ProcessExitResultWithOutput.FromProcessExitResult(_processManager.LaunchAndProcess(processInfo),
         progress.Output);
 }
 public async Task<ProcessExitResultWithOutput> RunAndProcessAsync(ITransferProgress progress, string source,
     string destination,
     RsyncOptions options = null) {
     var processInfo = BuildProcessInfo(progress, source, destination, options);
     return
         ProcessExitResultWithOutput.FromProcessExitResult(
             await _processManager.LaunchAndProcessAsync(processInfo).ConfigureAwait(false), progress.Output);
 }
Example #16
0
 public void Pull(ITransferProgress status, string remoteSub = null, string localSub = null)
 {
     CreateSshFolder();
     HandleRsyncResponse(_rsyncLauncher.RunAndProcess(
                             status,
                             JoinPathsIfNeeded(Remote, remoteSub),
                             JoinPathsIfNeeded(Local, localSub),
                             BuildOptions()));
 }
Example #17
0
 public ProcessExitResultWithOutput RunAndProcess(ITransferProgress progress, Uri url, string file) {
     TryHandleOldFiles(file);
     var processInfo = BuildProcessInfo(progress, url, file);
     var r =
         ProcessExitResultWithOutput.FromProcessExitResult(_processManager.LaunchAndProcess(processInfo),
             progress.Output);
     TryRemoveOldFiles(file);
     return r;
 }
        public override void ParseOutput(Process sender, string data, ITransferProgress progress)
        {
            // ###################- 97.3% 141.5 kBps 0:00 ETA
            // used 0 local, fetched 894
            if (data == null)
            {
                return;
            }
            progress.UpdateOutput(data);

            if (!VerifyZsyncCompatible(data))
            {
                progress.ZsyncIncompatible = true;
            }

            if (CheckZsyncLoop(sender, data, progress))
            {
                return;
            }

            var matches = ZSYNC_START.Matches(data);

            if (matches.Count > 0)
            {
                var match = matches[0];

                var speed     = match.Groups[2].Value.TryDouble();
                var speedUnit = match.Groups[3].Value;
                progress.Update(GetByteSize(speed, speedUnit), match.Groups[1].Value.TryDouble());

                var eta = match.Groups[4].Value;
                if (tspan.IsMatch(eta))
                {
                    eta = "0:" + eta;
                }
                TimeSpan ts;
                if (TimeSpan.TryParse(eta, out ts))
                {
                    progress.Eta = ts;
                }

                return;
            }

            matches = ZSYNC_END.Matches(data);
            if (matches.Count > 0)
            {
                var match = matches[0];
                progress.FileSizeTransfered = match.Groups[2].Value.TryInt();
                progress.Completed          = true;
                return;
            }

            progress.Eta = null;
            progress.Update(null, 0);
        }
Example #19
0
        public async Task <ProcessExitResultWithOutput> RunAndProcessAsync(ITransferProgress progress, string source,
                                                                           string destination,
                                                                           RsyncOptions options = null)
        {
            var processInfo = BuildProcessInfo(progress, source, destination, options);

            return
                (ProcessExitResultWithOutput.FromProcessExitResult(
                     await _processManager.LaunchAndProcessAsync(processInfo).ConfigureAwait(false), progress.Output));
        }
Example #20
0
        public override Task SendAsync(MimeMessage message, CancellationToken cancellationToken = new CancellationToken(),
                                       ITransferProgress progress = null)
        {
            if (SendException != null)
            {
                throw SendException;
            }

            return(Task.CompletedTask);
        }
Example #21
0
        public override void ParseOutput(Process sender, string data, ITransferProgress progress)
        {
            //        3.51M  43%  177.98kB/s    0:00:25
            // sent 1.39K bytes  received 1.01K bytes  1.60K bytes/sec
            // total size is 114.55K  speedup is 47.57
            if (data == null)
            {
                return;
            }
            progress.UpdateOutput(data);

            var matches = RSYNC_START.Matches(data);

            if (matches.Count > 0)
            {
                var match = matches[0];


                var speed     = match.Groups[2].Value.TryDouble();
                var speedUnit = match.Groups[3].Value;
                progress.Update(GetByteSize(speed, speedUnit), match.Groups[1].Value.TryDouble());

                TimeSpan ts;
                if (TimeSpan.TryParse(match.Groups[4].Value, out ts))
                {
                    progress.Eta = ts;
                }

                return;
            }

            matches = RSYNC_END.Matches(data);
            if (matches.Count > 0)
            {
                var match    = matches[0];
                var sent     = match.Groups[1].Value.TryDouble();
                var sentUnit = match.Groups[2].Value;

                var received     = match.Groups[3].Value.TryDouble();
                var receivedUnit = match.Groups[4].Value;

                // Rsync final message omits B(yte) indication
                progress.FileSizeTransfered = GetByteSize(sent, sentUnit + "b") +
                                              GetByteSize(received, receivedUnit + "b");
                progress.Completed = true;
                return;
            }

            progress.Eta = null;
            progress.Update(null, 0);
        }
Example #22
0
        protected TransferSpec(Uri uri, IAbsoluteFilePath localFile, ITransferProgress progress)
        {
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }
            if (localFile == null)
            {
                throw new ArgumentNullException(nameof(localFile));
            }

            Uri       = uri;
            LocalFile = localFile;
            Progress  = progress ?? new TransferProgress();
        }
Example #23
0
        public IDisposable SetupDownloadTransferProgress(ITransferProgress transferProgress, TimeSpan timeout)
        {
            var  lastTime  = Tools.Generic.GetCurrentUtcDateTime;
            long lastBytes = 0;

            transferProgress.Update(null, 0);
            transferProgress.FileSizeTransfered = 0;
            DownloadProgressChanged            +=
                (sender, args) => {
                var bytes = args.BytesReceived;
                var now   = Tools.Generic.GetCurrentUtcDateTime;

                transferProgress.FileSizeTransfered = bytes;

                long?speed = null;

                if (lastBytes != 0)
                {
                    var timeSpan    = now - lastTime;
                    var bytesChange = bytes - lastBytes;

                    if (timeSpan.TotalMilliseconds > 0)
                    {
                        speed = (long)(bytesChange / (timeSpan.TotalMilliseconds / 1000.0));
                    }
                }
                transferProgress.Update(speed, args.ProgressPercentage);

                lastBytes = bytes;
                lastTime  = now;
            };

            DownloadFileCompleted += (sender, args) => { transferProgress.Completed = true; };

            var timer = new TimerWithElapsedCancellation(500, () => {
                if (!transferProgress.Completed &&
                    Tools.Generic.LongerAgoThan(lastTime, timeout))
                {
                    CancelAsync();
                    return(false);
                }
                return(!transferProgress.Completed);
            });

            return(timer);
        }
        public override void ParseOutput(Process sender, string data, ITransferProgress progress) {
            //        3.51M  43%  177.98kB/s    0:00:25
            // sent 1.39K bytes  received 1.01K bytes  1.60K bytes/sec
            // total size is 114.55K  speedup is 47.57
            if (data == null)
                return;
            progress.UpdateOutput(data);

            var matches = RSYNC_START.Matches(data);
            if (matches.Count > 0) {
                var match = matches[0];


                var speed = match.Groups[2].Value.TryDouble();
                var speedUnit = match.Groups[3].Value;
                progress.Update(GetByteSize(speed, speedUnit), match.Groups[1].Value.TryDouble());

                TimeSpan ts;
                if (TimeSpan.TryParse(match.Groups[4].Value, out ts))
                    progress.Eta = ts;

                return;
            }

            matches = RSYNC_END.Matches(data);
            if (matches.Count > 0) {
                var match = matches[0];
                var sent = match.Groups[1].Value.TryDouble();
                var sentUnit = match.Groups[2].Value;

                var received = match.Groups[3].Value.TryDouble();
                var receivedUnit = match.Groups[4].Value;

                // Rsync final message omits B(yte) indication
                progress.FileSizeTransfered = GetByteSize(sent, sentUnit + "b") +
                                              GetByteSize(received, receivedUnit + "b");
                progress.Completed = true;
                return;
            }

            progress.Eta = null;
            progress.Update(null, 0);
        }
        public override void ParseOutput(Process sender, string data, ITransferProgress progress) {
            // ###################- 97.3% 141.5 kBps 0:00 ETA  
            // used 0 local, fetched 894
            if (data == null)
                return;
            progress.UpdateOutput(data);

            if (!VerifyZsyncCompatible(data))
                progress.ZsyncIncompatible = true;

            if (CheckZsyncLoop(sender, data, progress))
                return;

            var matches = ZSYNC_START.Matches(data);
            if (matches.Count > 0) {
                var match = matches[0];

                var speed = match.Groups[2].Value.TryDouble();
                var speedUnit = match.Groups[3].Value;
                progress.Update(GetByteSize(speed, speedUnit), match.Groups[1].Value.TryDouble());

                var eta = match.Groups[4].Value;
                if (tspan.IsMatch(eta))
                    eta = "0:" + eta;
                TimeSpan ts;
                if (TimeSpan.TryParse(eta, out ts))
                    progress.Eta = ts;

                return;
            }

            matches = ZSYNC_END.Matches(data);
            if (matches.Count > 0) {
                var match = matches[0];
                progress.FileSizeTransfered = match.Groups[2].Value.TryInt();
                progress.Completed = true;
                return;
            }

            progress.Eta = null;
            progress.Update(null, 0);
        }
Example #26
0
        public async Task SendMailAsync(MimeMessage message, ITransferProgress progressHandler = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            using (var client = await GetAuthenticatedClientAsync(cancellationToken))
            {
                // TODO wziąć to skądś (może dodatkowe opcje ustawień dla usera?)
                var formatOptions = new FormatOptions
                {
                    NewLineFormat = NewLineFormat.Dos
                };

                try
                {
                    await client.SendAsync(formatOptions, message, cancellationToken, progressHandler);
                }
                catch (Exception e)
                {
                    var errorMessage = "Exception occured while sending email!";
                    logger.Warn(e, errorMessage);
                    throw new Exception(errorMessage, e);
                }
            }
        }
Example #27
0
        // public bool SendSMS()
        // {
        //     string URL = "https://smsapi.engineeringtgr.com/send/?Mobile=xxxxxxxxxx&Password=xxxxxx&Message=text&To=xxxxxxxxxx&Key=xxxxxxxxxxxxxx";

        //     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
        //     request.Method = "GET";
        //     request.ContentType = "application/json";
        //     request.ContentLength = 0;// DATA.Length;

        //      try {
        //         WebResponse webResponse = request.GetResponse();
        //         Stream webStream = webResponse.GetResponseStream();
        //         StreamReader responseReader = new StreamReader(webStream);
        //         string response = responseReader.ReadToEnd();
        //         Console.Out.WriteLine(response);
        //         responseReader.Close();
        //     } catch (Exception xe) {
        //         Console.Out.WriteLine("-----------------");
        //         Console.Out.WriteLine(xe.Message);
        //     }
        // }

        public static bool SendMail(string userName, string email, string body)
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress("SiyasMatrimony", "*****@*****.**"));
            message.To.Add(new MailboxAddress(userName, email));
            message.Subject = "Credential Information";
            message.Body    = new TextPart("plain")
            {
                Text = body
            };
            using (var client = new SmtpClient())
            {
                client.Connect("smtp.gmail.com", 587, false);
                client.Authenticate("*****@*****.**", "Kailas@12345");
                ITransferProgress progress = null;
                client.Send(message, default(CancellationToken), progress);
                client.Disconnect(true);
            }

            //if(progress)

            return(true);
        }
Example #28
0
			public SendContext (ITransferProgress progress, long? size)
			{
				this.progress = progress;
				this.size = size;
			}
Example #29
0
		ImapCommand QueueMultiAppend (FormatOptions options, IList<MimeMessage> messages, IList<MessageFlags> flags, IList<DateTimeOffset> dates, CancellationToken cancellationToken, ITransferProgress progress)
		{
			var args = new List<object> ();
			string format = "APPEND %F";

			args.Add (this);

			for (int i = 0; i < messages.Count; i++) {
				if ((flags[i] & SettableFlags) != 0)
					format += " " + ImapUtils.FormatFlagsList (flags[i], 0);

				if (dates != null)
					format += " \"" + ImapUtils.FormatInternalDate (dates[i]) + "\"";

				format += " %L";

				args.Add (messages[i]);
			}

			format += "\r\n";

			var ic = new ImapCommand (Engine, cancellationToken, null, options, format, args.ToArray ());
			ic.Progress = progress;

			Engine.QueueCommand (ic);

			return ic;
		}
Example #30
0
		/// <summary>
		/// Gets a substream of the specified message.
		/// </summary>
		/// <remarks>
		/// Fetches a substream of the message. If the starting offset is beyond
		/// the end of the message, an empty stream is returned. If the number of
		/// bytes desired extends beyond the end of the message, a truncated stream
		/// will be returned.
		/// </remarks>
		/// <returns>The stream.</returns>
		/// <param name="uid">The UID of the message.</param>
		/// <param name="offset">The starting offset of the first desired byte.</param>
		/// <param name="count">The number of bytes desired.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentException">
		/// <paramref name="uid"/> is invalid.
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <para><paramref name="offset"/> is negative.</para>
		/// <para>-or-</para>
		/// <para><paramref name="count"/> is negative.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="MessageNotFoundException">
		/// The IMAP server did not return the requested message stream.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		public override Stream GetStream (UniqueId uid, int offset, int count, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null)
		{
			if (uid.Id == 0)
				throw new ArgumentException ("The uid is invalid.", "uid");

			if (offset < 0)
				throw new ArgumentOutOfRangeException ("offset");

			if (count < 0)
				throw new ArgumentOutOfRangeException ("count");

			CheckState (true, false);

			if (count == 0)
				return new MemoryStream ();

			var ic = new ImapCommand (Engine, cancellationToken, this, "UID FETCH %u (BODY.PEEK[]<%d.%d>)\r\n", uid.Id, offset, count);
			var ctx = new FetchStreamContext (progress);
			Stream stream;

			ic.RegisterUntaggedHandler ("FETCH", FetchStream);
			ic.UserData = ctx;

			Engine.QueueCommand (ic);

			try {
				Engine.Wait (ic);

				ProcessResponseCodes (ic, null);

				if (ic.Response != ImapCommandResponse.Ok)
					throw ImapCommandException.Create ("FETCH", ic);

				if (!ctx.Sections.TryGetValue (string.Empty, out stream))
					throw new MessageNotFoundException ("The IMAP server did not return the requested stream.");

				ctx.Sections.Remove (string.Empty);
			} finally {
				ctx.Dispose ();
			}

			return stream;
		}
Example #31
0
		/// <summary>
		/// Gets a substream of the specified message.
		/// </summary>
		/// <remarks>
		/// <para>Gets a substream of the specified message. If the starting offset is beyond
		/// the end of the specified section of the message, an empty stream is returned. If
		/// the number of bytes desired extends beyond the end of the section, a truncated
		/// stream will be returned.</para>
		/// <para>For more information about how to construct the <paramref name="section"/>,
		/// see Section 6.4.5 of RFC3501.</para>
		/// </remarks>
		/// <returns>The stream.</returns>
		/// <param name="index">The index of the message.</param>
		/// <param name="section">The desired section of the message.</param>
		/// <param name="offset">The starting offset of the first desired byte.</param>
		/// <param name="count">The number of bytes desired.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="section"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <para><paramref name="index"/> is out of range.</para>
		/// <para>-or-</para>
		/// <para><paramref name="offset"/> is negative.</para>
		/// <para>-or-</para>
		/// <para><paramref name="count"/> is negative.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="MessageNotFoundException">
		/// The IMAP server did not return the requested message stream.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		public override Stream GetStream (int index, string section, int offset, int count, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null)
		{
			if (index < 0 || index >= Count)
				throw new ArgumentOutOfRangeException ("index");

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

			if (offset < 0)
				throw new ArgumentOutOfRangeException ("offset");

			if (count < 0)
				throw new ArgumentOutOfRangeException ("count");

			CheckState (true, false);

			if (count == 0)
				return new MemoryStream ();

			var command = string.Format ("FETCH {0} (BODY.PEEK[{1}]<{2}.{3}>)\r\n", index + 1, section, offset, count);
			var ic = new ImapCommand (Engine, cancellationToken, this, command);
			var ctx = new FetchStreamContext (progress);
			Stream stream;

			ic.RegisterUntaggedHandler ("FETCH", FetchStream);
			ic.UserData = ctx;

			Engine.QueueCommand (ic);

			try {
				Engine.Wait (ic);

				ProcessResponseCodes (ic, null);

				if (ic.Response != ImapCommandResponse.Ok)
					throw ImapCommandException.Create ("FETCH", ic);

				if (!ctx.Sections.TryGetValue (section, out stream))
					throw new MessageNotFoundException ("The IMAP server did not return the requested stream.");

				ctx.Sections.Remove (section);
			} finally {
				ctx.Dispose ();
			}

			return stream;
		}
Example #32
0
		/// <summary>
		/// Gets the specified body part.
		/// </summary>
		/// <remarks>
		/// Gets the specified body part.
		/// </remarks>
		/// <returns>The body part.</returns>
		/// <param name="index">The index of the message.</param>
		/// <param name="part">The body part.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="part"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="index"/> is out of range.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="MessageNotFoundException">
		/// The IMAP server did not return the requested message.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		public override MimeEntity GetBodyPart (int index, BodyPart part, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null)
		{
			return GetBodyPart (index, part, false, cancellationToken, progress);
		}
Example #33
0
		/// <summary>
		/// Gets the specified body part.
		/// </summary>
		/// <remarks>
		/// Gets the specified body part.
		/// </remarks>
		/// <returns>The body part.</returns>
		/// <param name="index">The index of the message.</param>
		/// <param name="partSpecifier">The body part specifier.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="partSpecifier"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="index"/> is out of range.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="MessageNotFoundException">
		/// The IMAP server did not return the requested message.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		public MimeEntity GetBodyPart (int index, string partSpecifier, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null)
		{
			return GetBodyPart (index, partSpecifier, false, cancellationToken, progress);
		}
Example #34
0
        /// <summary>
        /// Asynchronously send the specified message.
        /// </summary>
        /// <remarks>
        /// <para>Sends the specified message.</para>
        /// <para>The sender address is determined by checking the following
        /// message headers (in order of precedence): Resent-Sender,
        /// Resent-From, Sender, and From.</para>
        /// <para>If either the Resent-Sender or Resent-From addresses are present,
        /// the recipients are collected from the Resent-To, Resent-Cc, and
        /// Resent-Bcc headers, otherwise the To, Cc, and Bcc headers are used.</para>
        /// </remarks>
        /// <example>
        /// <code language="c#" source="Examples\SmtpExamples.cs" region="SendMessageWithOptions"/>
        /// </example>
        /// <returns>An asynchronous task context.</returns>
        /// <param name="options">The formatting options.</param>
        /// <param name="message">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>
        /// </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 Task SendAsync(FormatOptions options, MimeMessage message, CancellationToken cancellationToken = default(CancellationToken), ITransferProgress progress = null)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            var recipients = GetMessageRecipients(message);
            var sender     = GetMessageSender(message);

            if (sender == null)
            {
                throw new InvalidOperationException("No sender has been specified.");
            }

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

            return(SendAsync(options, message, sender, recipients, true, cancellationToken, progress));
        }
Example #35
0
		/// <summary>
		/// Gets the specified message.
		/// </summary>
		/// <remarks>
		/// Gets the specified message.
		/// </remarks>
		/// <returns>The message.</returns>
		/// <param name="index">The index of the message.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="index"/> is out of range.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="MessageNotFoundException">
		/// The IMAP server did not return the requested message.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		public override MimeMessage GetMessage (int index, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null)
		{
			if (index < 0 || index >= Count)
				throw new ArgumentOutOfRangeException ("index");

			CheckState (true, false);

			var ic = new ImapCommand (Engine, cancellationToken, this, "FETCH %d (BODY.PEEK[])\r\n", index + 1);
			var ctx = new FetchStreamContext (progress);
			Stream stream;

			ic.RegisterUntaggedHandler ("FETCH", FetchStream);
			ic.UserData = ctx;

			Engine.QueueCommand (ic);

			try {
				Engine.Wait (ic);

				ProcessResponseCodes (ic, null);

				if (ic.Response != ImapCommandResponse.Ok)
					throw ImapCommandException.Create ("FETCH", ic);

				if (!ctx.Sections.TryGetValue (string.Empty, out stream))
					throw new MessageNotFoundException ("The IMAP server did not return the requested message.");

				ctx.Sections.Remove (string.Empty);
			} finally {
				ctx.Dispose ();
			}

			return ParseMessage (stream, cancellationToken);
		}
Example #36
0
		/// <summary>
		/// Send the specified message.
		/// </summary>
		/// <remarks>
		/// <para>Sends the specified message.</para>
		/// <para>The sender address is determined by checking the following
		/// message headers (in order of precedence): Resent-Sender,
		/// Resent-From, Sender, and From.</para>
		/// <para>If either the Resent-Sender or Resent-From addresses are present,
		/// the recipients are collected from the Resent-To, Resent-Cc, and
		/// Resent-Bcc headers, otherwise the To, Cc, and Bcc headers are used.</para>
		/// </remarks>
		/// <example>
		/// <code language="c#" source="Examples\SmtpExamples.cs" region="SendMessageWithOptions"/>
		/// </example>
		/// <param name="options">The formatting options.</param>
		/// <param name="message">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>
		/// </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, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null)
		{
			if (message == null)
				throw new ArgumentNullException ("message");

			var recipients = GetMessageRecipients (message);
			var sender = GetMessageSender (message);

			if (sender == null)
				throw new InvalidOperationException ("No sender has been specified.");

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

			Send (options, message, sender, recipients, cancellationToken, progress);
		}
Example #37
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);
		}
Example #38
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;
			}
		}
Example #39
0
 /// <summary>
 /// Sends the specified message using the supplied sender and recipients.
 /// </summary>
 /// <remarks>
 /// Sends the specified message 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="MailTransport"/> has been disposed.
 /// </exception>
 /// <exception cref="ServiceNotConnectedException">
 /// The <see cref="MailTransport"/> 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.OperationCanceledException">
 /// The operation has been canceled.
 /// </exception>
 /// <exception cref="System.NotSupportedException">
 /// <para>Internationalized formatting was requested but is not supported by the transport.</para>
 /// </exception>
 /// <exception cref="System.IO.IOException">
 /// An I/O error occurred.
 /// </exception>
 /// <exception cref="CommandException">
 /// The send command failed.
 /// </exception>
 /// <exception cref="ProtocolException">
 /// A protocol exception occurred.
 /// </exception>
 public abstract void Send(FormatOptions options, MimeMessage message, MailboxAddress sender, IEnumerable <MailboxAddress> recipients, CancellationToken cancellationToken = default(CancellationToken), ITransferProgress progress = null);
Example #40
0
 public override void Send(MimeMessage message, MailboxAddress sender, IEnumerable <MailboxAddress> recipients,
                           CancellationToken cancellationToken = new CancellationToken(), ITransferProgress progress = null)
 {
     if (SendException != null)
     {
         throw SendException;
     }
 }
Example #41
0
		/// <summary>
		/// Appends the specified messages to the folder.
		/// </summary>
		/// <remarks>
		/// Appends the specified messages to the folder and returns the UniqueIds assigned to the messages.
		/// </remarks>
		/// <returns>The UIDs of the appended messages, if available; otherwise an empty array.</returns>
		/// <param name="options">The formatting options.</param>
		/// <param name="messages">The list of messages to append to the folder.</param>
		/// <param name="flags">The message flags to use for each of the messages.</param>
		/// <param name="dates">The received dates to use for each of the messages.</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="messages"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="flags"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="dates"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para>One or more of the <paramref name="messages"/> is null.</para>
		/// <para>-or-</para>
		/// <para>The number of messages, flags, and dates do not match.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="System.InvalidOperationException">
		/// Internationalized formatting was requested but has not been enabled.
		/// </exception>
		/// <exception cref="FolderNotFoundException">
		/// The <see cref="ImapFolder"/> does not exist.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// Internationalized formatting was requested but is not supported by the server.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		public override IList<UniqueId> Append (FormatOptions options, IList<MimeMessage> messages, IList<MessageFlags> flags, IList<DateTimeOffset> dates, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null)
		{
			if (options == null)
				throw new ArgumentNullException ("options");

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

			for (int i = 0; i < messages.Count; i++) {
				if (messages[i] == null)
					throw new ArgumentException ("One or more of the messages is null.");
			}

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

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

			if (messages.Count != flags.Count || messages.Count != dates.Count)
				throw new ArgumentException ("The number of messages, the number of flags, and the number of dates must be equal.");

			CheckState (false, false);

			if (options.International && (Engine.Capabilities & ImapCapabilities.UTF8Accept) == 0)
				throw new NotSupportedException ("The IMAP server does not support the UTF8 extension.");

			var format = options.Clone ();
			format.NewLineFormat = NewLineFormat.Dos;

			if ((Engine.Capabilities & ImapCapabilities.UTF8Only) == ImapCapabilities.UTF8Only)
				format.International = true;

			if (format.International && !Engine.UTF8Enabled)
				throw new InvalidOperationException ("The UTF8 extension has not been enabled.");

			if (messages.Count == 0)
				return new UniqueId[0];

			if ((Engine.Capabilities & ImapCapabilities.MultiAppend) != 0) {
				var ic = QueueMultiAppend (format, messages, flags, dates, cancellationToken, progress);

				Engine.Wait (ic);

				ProcessResponseCodes (ic, null);

				if (ic.Response != ImapCommandResponse.Ok)
					throw ImapCommandException.Create ("APPEND", ic);

				var append = ic.RespCodes.OfType<AppendUidResponseCode> ().FirstOrDefault ();

				if (append != null)
					return append.UidSet;

				return new UniqueId[0];
			}

			// FIXME: use an aggregate progress reporter
			var uids = new List<UniqueId> ();

			for (int i = 0; i < messages.Count; i++) {
				var uid = Append (format, messages[i], flags[i], dates[i], cancellationToken);
				if (uids != null && uid.HasValue)
					uids.Add (uid.Value);
				else
					uids = null;
			}

			if (uids == null)
				return new UniqueId[0];

			return uids;
		}
Example #42
0
        /// <summary>
        /// Asynchronously 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>
        /// <returns>An asynchronous task context.</returns>
        /// <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 Task SendAsync(FormatOptions options, MimeMessage message, MailboxAddress sender, IEnumerable <MailboxAddress> recipients, CancellationToken cancellationToken = default(CancellationToken), ITransferProgress progress = null)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            if (sender == null)
            {
                throw new ArgumentNullException(nameof(sender));
            }

            if (recipients == null)
            {
                throw new ArgumentNullException(nameof(recipients));
            }

            var unique = new HashSet <string> (StringComparer.OrdinalIgnoreCase);
            var rcpts  = new List <MailboxAddress> ();

            AddUnique(rcpts, unique, recipients);

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

            return(SendAsync(options, message, sender, rcpts, true, cancellationToken, progress));
        }
Example #43
0
			public FetchStreamContext (ITransferProgress progress)
			{
				Progress = progress;
			}
Example #44
0
 /// <summary>
 /// Sends the specified message.
 /// </summary>
 /// <remarks>
 /// <para>Sends the specified message.</para>
 /// <para>The sender address is determined by checking the following
 /// message headers (in order of precedence): Resent-Sender,
 /// Resent-From, Sender, and From.</para>
 /// <para>If either the Resent-Sender or Resent-From addresses are present,
 /// the recipients are collected from the Resent-To, Resent-Cc, and
 /// Resent-Bcc headers, otherwise the To, Cc, and Bcc headers are used.</para>
 /// </remarks>
 /// <example>
 /// <code language="c#" source="Examples\SmtpExamples.cs" region="SendMessageWithOptions"/>
 /// </example>
 /// <param name="options">The formatting options.</param>
 /// <param name="message">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>
 /// </exception>
 /// <exception cref="System.ObjectDisposedException">
 /// The <see cref="MailTransport"/> has been disposed.
 /// </exception>
 /// <exception cref="ServiceNotConnectedException">
 /// The <see cref="MailTransport"/> 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.OperationCanceledException">
 /// The operation has been canceled.
 /// </exception>
 /// <exception cref="System.NotSupportedException">
 /// <para>Internationalized formatting was requested but is not supported by the transport.</para>
 /// </exception>
 /// <exception cref="System.IO.IOException">
 /// An I/O error occurred.
 /// </exception>
 /// <exception cref="CommandException">
 /// The send command failed.
 /// </exception>
 /// <exception cref="ProtocolException">
 /// A protocol exception occurred.
 /// </exception>
 public abstract void Send(FormatOptions options, MimeMessage message, CancellationToken cancellationToken = default(CancellationToken), ITransferProgress progress = null);
Example #45
0
		/// <summary>
		/// Gets the specified body part.
		/// </summary>
		/// <remarks>
		/// Gets the specified body part.
		/// </remarks>
		/// <returns>The body part.</returns>
		/// <param name="uid">The UID of the message.</param>
		/// <param name="part">The body part.</param>
		/// <param name="headersOnly"><c>true</c> if only the headers should be downloaded; otherwise, <c>false</c>></param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="part"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <paramref name="uid"/> is invalid.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="MessageNotFoundException">
		/// The IMAP server did not return the requested message body.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		public override MimeEntity GetBodyPart (UniqueId uid, BodyPart part, bool headersOnly, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null)
		{
			if (uid.Id == 0)
				throw new ArgumentException ("The uid is invalid.", "uid");

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

			return GetBodyPart (uid, part.PartSpecifier, headersOnly, cancellationToken, progress);
		}
        /// <summary>
        /// Sends the asynchronous.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="traceProps">The trace props.</param>
        /// <param name="progress">The progress.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task SendAsync(MimeMessage message, Dictionary <string, string> traceProps, ITransferProgress progress = null, CancellationToken cancellationToken = default)
        {
            TimeSpan span = DateTime.Now - this.lastSend;

            if (this.smtpClient == null || span.TotalMinutes > this.timeout)
            {
                this.Refresh(traceProps);
            }

            await this.smtpClient.SendAsync(message).ConfigureAwait(false);

            this.lastSend = DateTime.Now;
        }
Example #47
0
		/// <summary>
		/// Gets the specified body part.
		/// </summary>
		/// <remarks>
		/// Gets the specified body part.
		/// </remarks>
		/// <returns>The body part.</returns>
		/// <param name="index">The index of the message.</param>
		/// <param name="part">The body part.</param>
		/// <param name="headersOnly"><c>true</c> if only the headers should be downloaded; otherwise, <c>false</c>></param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="part"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="index"/> is out of range.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="MessageNotFoundException">
		/// The IMAP server did not return the requested message.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		public override MimeEntity GetBodyPart (int index, BodyPart part, bool headersOnly, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null)
		{
			if (index < 0 || index >= Count)
				throw new ArgumentOutOfRangeException ("index");

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

			return GetBodyPart (index, part.PartSpecifier, headersOnly, cancellationToken, progress);
		}
Example #48
0
 /// <summary>
 /// Sends the specified message using the supplied sender and recipients.
 /// </summary>
 /// <remarks>
 /// Sends the specified message 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">The cancellation token.</param>
 /// <param name="progress">The progress reporting mechanism.</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="MailTransport"/> has been disposed.
 /// </exception>
 /// <exception cref="ServiceNotConnectedException">
 /// The <see cref="MailTransport"/> 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.OperationCanceledException">
 /// The operation has been canceled.
 /// </exception>
 /// <exception cref="System.IO.IOException">
 /// An I/O error occurred.
 /// </exception>
 /// <exception cref="CommandException">
 /// The send command failed.
 /// </exception>
 /// <exception cref="ProtocolException">
 /// A protocol exception occurred.
 /// </exception>
 public virtual void Send(MimeMessage message, MailboxAddress sender, IEnumerable <MailboxAddress> recipients, CancellationToken cancellationToken = default(CancellationToken), ITransferProgress progress = null)
 {
     Send(FormatOptions.Default, message, sender, recipients, cancellationToken, progress);
 }
Example #49
0
		/// <summary>
		/// Gets the specified body part.
		/// </summary>
		/// <remarks>
		/// Gets the specified body part.
		/// </remarks>
		/// <returns>The body part.</returns>
		/// <param name="index">The index of the message.</param>
		/// <param name="partSpecifier">The body part specifier.</param>
		/// <param name="headersOnly"><c>true</c> if only the headers should be downloaded; otherwise, <c>false</c>></param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="partSpecifier"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="index"/> is out of range.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="MessageNotFoundException">
		/// The IMAP server did not return the requested message.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		public MimeEntity GetBodyPart (int index, string partSpecifier, bool headersOnly, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null)
		{
			if (index < 0 || index >= Count)
				throw new ArgumentOutOfRangeException ("index");

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

			CheckState (true, false);

			string[] tags;

			var command = string.Format ("FETCH {0} ({1})\r\n", index + 1, GetBodyPartQuery (partSpecifier, headersOnly, out tags));
			var ic = new ImapCommand (Engine, cancellationToken, this, command);
			var ctx = new FetchStreamContext (progress);
			ChainedStream chained;
			bool dispose = false;
			Stream stream;

			ic.RegisterUntaggedHandler ("FETCH", FetchStream);
			ic.UserData = ctx;

			Engine.QueueCommand (ic);

			try {
				Engine.Wait (ic);

				ProcessResponseCodes (ic, null);

				if (ic.Response != ImapCommandResponse.Ok)
					throw ImapCommandException.Create ("FETCH", ic);

				chained = new ChainedStream ();

				foreach (var tag in tags) {
					if (!ctx.Sections.TryGetValue (tag, out stream))
						throw new MessageNotFoundException ("The IMAP server did not return the requested body part.");

					if (!(stream is MemoryStream || stream is MemoryBlockStream))
						dispose = true;

					chained.Add (stream);
				}

				foreach (var tag in tags)
					ctx.Sections.Remove (tag);
			} finally {
				ctx.Dispose ();
			}

			var entity = ParseEntity (chained, dispose, cancellationToken);

			if (partSpecifier.Length == 0) {
				for (int i = entity.Headers.Count; i > 0; i--) {
					var header = entity.Headers[i - 1];

					if (!header.Field.StartsWith ("Content-", StringComparison.OrdinalIgnoreCase))
						entity.Headers.RemoveAt (i - 1);
				}
			}

			return entity;
		}
Example #50
0
 public override Task SendAsync(FormatOptions options, MimeMessage message, MailboxAddress sender, IEnumerable <MailboxAddress> recipients,
                                CancellationToken cancellationToken = new CancellationToken(), ITransferProgress progress = null)
 {
     throw new NotImplementedException();
 }
Example #51
0
		/// <summary>
		/// Gets a substream of the specified body part.
		/// </summary>
		/// <remarks>
		/// <para>Gets a substream of the specified message.</para>
		/// <para>For more information about how to construct the <paramref name="section"/>,
		/// see Section 6.4.5 of RFC3501.</para>
		/// </remarks>
		/// <returns>The stream.</returns>
		/// <param name="uid">The UID of the message.</param>
		/// <param name="section">The desired section of the message.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentException">
		/// <paramref name="uid"/> is invalid.
		/// </exception>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="section"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="MessageNotFoundException">
		/// The IMAP server did not return the requested message stream.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		public override Stream GetStream (UniqueId uid, string section, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null)
		{
			if (uid.Id == 0)
				throw new ArgumentException ("The uid is invalid.", "uid");

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

			CheckState (true, false);

			var command = string.Format ("UID FETCH {0} (BODY.PEEK[{1}])\r\n", uid.Id, section);
			var ic = new ImapCommand (Engine, cancellationToken, this, command);
			var ctx = new FetchStreamContext (progress);
			Stream stream;

			ic.RegisterUntaggedHandler ("FETCH", FetchStream);
			ic.UserData = ctx;

			Engine.QueueCommand (ic);

			try {
				Engine.Wait (ic);

				ProcessResponseCodes (ic, null);

				if (ic.Response != ImapCommandResponse.Ok)
					throw ImapCommandException.Create ("FETCH", ic);

				if (!ctx.Sections.TryGetValue (section, out stream))
					throw new MessageNotFoundException ("The IMAP server did not return the requested stream.");

				ctx.Sections.Remove (section);
			} finally {
				ctx.Dispose ();
			}

			return stream;
		}
Example #52
0
		/// <summary>
		/// Asynchronously get a substream of the specified body part.
		/// </summary>
		/// <remarks>
		/// <para>Asynchronously gets a substream of the specified message. If the starting
		/// offset is beyond the end of the specified section of the message, an empty stream
		/// is returned. If the number of bytes desired extends beyond the end of the section,
		/// a truncated stream will be returned.</para>
		/// <para>For more information about how to construct the <paramref name="section"/>,
		/// see Section 6.4.5 of RFC3501.</para>
		/// </remarks>
		/// <returns>The stream.</returns>
		/// <param name="index">The index of the message.</param>
		/// <param name="section">The desired section of the message.</param>
		/// <param name="offset">The starting offset of the first desired byte.</param>
		/// <param name="count">The number of bytes desired.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <param name="progress">The progress reporting mechanism.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="section"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <para><paramref name="index"/> is out of range.</para>
		/// <para>-or-</para>
		/// <para><paramref name="offset"/> is negative.</para>
		/// <para>-or-</para>
		/// <para><paramref name="count"/> is negative.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="IMailStore"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="IMailStore"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="IMailStore"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The folder is not currently open.
		/// </exception>
		/// <exception cref="MessageNotFoundException">
		/// The <see cref="IMailStore"/> did not return the requested message stream.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="CommandException">
		/// The command failed.
		/// </exception>
		public virtual Task<Stream> GetStreamAsync (int index, string section, int offset, int count, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null)
		{
			if (index < 0 || index >= Count)
				throw new ArgumentOutOfRangeException ("index");

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

			if (offset < 0)
				throw new ArgumentOutOfRangeException ("offset");

			if (count < 0)
				throw new ArgumentOutOfRangeException ("count");

			return Task.Factory.StartNew (() => {
				lock (SyncRoot) {
					return GetStream (index, section, offset, count, cancellationToken, progress);
				}
			}, cancellationToken, TaskCreationOptions.None, TaskScheduler.Default);
		}
Example #53
0
 public override Task SendAsync(FormatOptions options, MimeMessage message,
                                CancellationToken cancellationToken = new CancellationToken(), ITransferProgress progress = null)
 {
     throw new NotImplementedException();
 }
 static bool AllowZsyncFallback(ITransferProgress progress)
 => progress.ZsyncHttpFallback || (progress.Tries > progress.ZsyncHttpFallbackAfter);
Example #55
0
		/// <summary>
		/// Appends the specified message to the folder.
		/// </summary>
		/// <remarks>
		/// Appends the specified message to the folder and returns the UniqueId assigned to the message.
		/// </remarks>
		/// <returns>The UID of the appended message, if available; otherwise, <c>null</c>.</returns>
		/// <param name="options">The formatting options.</param>
		/// <param name="message">The message.</param>
		/// <param name="flags">The message flags.</param>
		/// <param name="date">The received date of 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>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="System.InvalidOperationException">
		/// Internationalized formatting was requested but has not been enabled.
		/// </exception>
		/// <exception cref="FolderNotFoundException">
		/// The <see cref="ImapFolder"/> does not exist.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// Internationalized formatting was requested but is not supported by the server.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		public override UniqueId? Append (FormatOptions options, MimeMessage message, MessageFlags flags, DateTimeOffset date, CancellationToken cancellationToken = default (CancellationToken), ITransferProgress progress = null)
		{
			if (options == null)
				throw new ArgumentNullException ("options");

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

			CheckState (false, false);

			if (options.International && (Engine.Capabilities & ImapCapabilities.UTF8Accept) == 0)
				throw new NotSupportedException ("The IMAP server does not support the UTF8 extension.");

			var format = options.Clone ();
			format.NewLineFormat = NewLineFormat.Dos;

			if ((Engine.Capabilities & ImapCapabilities.UTF8Only) == ImapCapabilities.UTF8Only)
				format.International = true;

			if (format.International && !Engine.UTF8Enabled)
				throw new InvalidOperationException ("The UTF8 extension has not been enabled.");

			var ic = QueueAppend (format, message, flags, date, cancellationToken, progress);

			Engine.Wait (ic);

			ProcessResponseCodes (ic, this);

			if (ic.Response != ImapCommandResponse.Ok)
				throw ImapCommandException.Create ("APPEND", ic);

			var append = ic.RespCodes.OfType<AppendUidResponseCode> ().FirstOrDefault ();

			if (append != null)
				return append.UidSet[0];

			return null;
		}
Example #56
0
        /// <summary>
        /// Asynchronously sends the specified message using the supplied sender and recipients.
        /// </summary>
        /// <remarks>
        /// Asynchronously sends the specified message using the supplied sender and recipients.
        /// </remarks>
        /// <returns>An asynchronous task context.</returns>
        /// <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="MailTransport"/> has been disposed.
        /// </exception>
        /// <exception cref="ServiceNotConnectedException">
        /// The <see cref="MailTransport"/> 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.OperationCanceledException">
        /// The operation has been canceled.
        /// </exception>
        /// <exception cref="System.NotSupportedException">
        /// <para>Internationalized formatting was requested but is not supported by the transport.</para>
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An I/O error occurred.
        /// </exception>
        /// <exception cref="CommandException">
        /// The send command failed.
        /// </exception>
        /// <exception cref="ProtocolException">
        /// A protocol exception occurred.
        /// </exception>
        public virtual Task SendAsync(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");
            }

            return(Task.Factory.StartNew(() => {
                lock (SyncRoot) {
                    Send(options, message, sender, recipients, cancellationToken, progress);
                }
            }, cancellationToken, TaskCreationOptions.None, TaskScheduler.Default));
        }
Example #57
0
		void Bdat (FormatOptions options, MimeMessage message, CancellationToken cancellationToken, ITransferProgress progress)
		{
			long size;

			using (var measure = new MeasuringStream ()) {
				message.WriteTo (options, measure, cancellationToken);
				size = measure.Length;
			}

			var bytes = Encoding.UTF8.GetBytes (string.Format ("BDAT {0} LAST\r\n", size));

			Stream.Write (bytes, 0, bytes.Length, cancellationToken);

			if (progress != null) {
				var ctx = new SendContext (progress, size);

				using (var stream = new ProgressStream (Stream, ctx.Update)) {
					message.WriteTo (options, stream, cancellationToken);
					stream.Flush (cancellationToken);
				}
			} else {
				message.WriteTo (options, Stream, cancellationToken);
				Stream.Flush (cancellationToken);
			}

			var response = Stream.ReadResponse (cancellationToken);

			switch (response.StatusCode) {
			default:
				throw new SmtpCommandException (SmtpErrorCode.MessageNotAccepted, response.StatusCode, response.Response);
			case SmtpStatusCode.AuthenticationRequired:
				throw new ServiceNotAuthenticatedException (response.Response);
			case SmtpStatusCode.Ok:
				OnMessageSent (new MessageSentEventArgs (message, response.Response));
				break;
			}
		}
Example #58
0
		ImapCommand QueueAppend (FormatOptions options, MimeMessage message, MessageFlags flags, DateTimeOffset? date, CancellationToken cancellationToken, ITransferProgress progress)
		{
			string format = "APPEND %F";

			if ((flags & SettableFlags) != 0)
				format += " " + ImapUtils.FormatFlagsList (flags, 0);

			if (date.HasValue)
				format += " \"" + ImapUtils.FormatInternalDate (date.Value) + "\"";

			format += " %L\r\n";

			var ic = new ImapCommand (Engine, cancellationToken, null, options, format, this, message);
			ic.Progress = progress;

			Engine.QueueCommand (ic);

			return ic;
		}
Example #59
0
        public override Task SendAsync(MimeMessage message, MailboxAddress sender, IEnumerable <MailboxAddress> recipients,
                                       CancellationToken cancellationToken = new CancellationToken(), ITransferProgress progress = null)
        {
            if (SendException != null)
            {
                throw SendException;
            }

            return(Task.CompletedTask);
        }
Example #60
0
		void Data (FormatOptions options, MimeMessage message, CancellationToken cancellationToken, ITransferProgress progress)
		{
			var response = SendCommand ("DATA", cancellationToken);

			if (response.StatusCode != SmtpStatusCode.StartMailInput)
				throw new SmtpCommandException (SmtpErrorCode.UnexpectedStatusCode, response.StatusCode, response.Response);

			if (progress != null) {
				var ctx = new SendContext (progress, null);

				using (var stream = new ProgressStream (Stream, ctx.Update)) {
					using (var filtered = new FilteredStream (stream)) {
						filtered.Add (new SmtpDataFilter ());

						message.WriteTo (options, filtered, cancellationToken);
						filtered.Flush ();
					}
				}
			} else {
				using (var filtered = new FilteredStream (Stream)) {
					filtered.Add (new SmtpDataFilter ());

					message.WriteTo (options, filtered, cancellationToken);
					filtered.Flush ();
				}
			}

			Stream.Write (EndData, 0, EndData.Length, cancellationToken);
			Stream.Flush (cancellationToken);

			response = Stream.ReadResponse (cancellationToken);

			switch (response.StatusCode) {
			default:
				throw new SmtpCommandException (SmtpErrorCode.MessageNotAccepted, response.StatusCode, response.Response);
			case SmtpStatusCode.AuthenticationRequired:
				throw new ServiceNotAuthenticatedException (response.Response);
			case SmtpStatusCode.Ok:
				OnMessageSent (new MessageSentEventArgs (message, response.Response));
				break;
			}
		}