Exemplo n.º 1
0
 public static Task SendReplyAsync(
     this ISmtpMessageChannel channel,
     SmtpReplyCode smtpReplyCode,
     CancellationToken cancellationToken)
 {
     return(channel.SendReplyAsync(smtpReplyCode, false, null, cancellationToken));
 }
Exemplo n.º 2
0
        ////////////////////////////////////////////////////////////////////
        // Send command to the server.
        ////////////////////////////////////////////////////////////////////
        private void SendCommand
        (
            string Command,
            SmtpReplyCode ExpectedReply
        )
        {
                #if DEBUG
            Debug.WriteLine(Command);
                #endif

            // send command
            Writer.Write(Command);
            Writer.Write("\r\n");
            Writer.Flush();

            // test reply
            if (ExpectedReply != SmtpReplyCode.IgnoreReply)
            {
                SmtpReplyCode ReplyCode = GetReply();
                if (ReplyCode != ExpectedReply)
                {
                                #if DEBUG
                    Debug.WriteLine(string.Format("Send command {0} failed. Reply code {1}", Command, (int)ReplyCode));
                                #endif
                    throw new ApplicationException("Command error: " + Command);
                }
            }
            return;
        }
Exemplo n.º 3
0
 private SmtpResponse SendData(Socket socket, string message, SmtpReplyCode expectedResponse)
 {
     byte[] msg = Encoding.UTF8.GetBytes(message);
     socket.Send(msg, 0, msg.Length, SocketFlags.None);
     if (!expectedResponse.Equals(SmtpReplyCode.QuitSuccess))
     {
         return(this.WaitForResponse(socket, expectedResponse));
     }
     return(null);
 }
Exemplo n.º 4
0
        public Task SendReplyAsync(
            SmtpReplyCode smtpReplyCode,
            IEnumerable <string> messages,
            CancellationToken cancellationToken)
        {
            List <string> list = messages.ToList();

            for (var index = 0; index < list.Count; index++)
            {
                Entries.Add(new Entry(smtpReplyCode, list[index], index != list.Count - 1));
            }

            return(Task.CompletedTask);
        }
Exemplo n.º 5
0
        async Task ISmtpMessageChannel.SendReplyAsync(
            SmtpReplyCode smtpReplyCode,
            IEnumerable <string> messages,
            CancellationToken cancellationToken)
        {
            string        message;
            StringBuilder builder;

            using (IEnumerator <string> enumerator = messages.GetEnumerator())
            {
                if (!enumerator.MoveNext())
                {
                    throw new ArgumentException("at least one response is required", nameof(messages));
                }

                message = enumerator.Current;
                bool more = enumerator.MoveNext();
                builder = new StringBuilder();
                while (more)
                {
                    builder.Clear();
                    builder.Append(((int)smtpReplyCode).ToString("D3"));
                    builder.Append("-");
                    if (message != null)
                    {
                        builder.Append(message);
                    }

                    await _connection.WriteLineAsync(builder.ToString(), Encoding.ASCII, cancellationToken);

                    message = enumerator.Current;
                    more    = enumerator.MoveNext();
                }
            }

            builder.Clear();
            builder.Append(((int)smtpReplyCode).ToString("D3"));
            builder.Append(" ");
            if (message != null)
            {
                builder.Append(message);
            }

            var output = builder.ToString();

            _log.Verbose($"SMTP -> {output}");
            await _connection.WriteLineAsync(output, Encoding.ASCII, cancellationToken);
        }
Exemplo n.º 6
0
        private SmtpResponse WaitForResponse(Socket socket, SmtpReplyCode expectedResponse)
        {
            DateTime timeStamp = DateTime.Now.AddSeconds(this.timeout);

            while (socket.Available == 0)
            {
                if (DateTime.Now > timeStamp)
                {
                    throw new SmtpTimeoutException(string.Format("Connection timeout while sending data to the server '{0}'", this.host));
                }
                Thread.Sleep(10);
            }

            byte[] bytes = new byte[1024];

            socket.Receive(bytes, 0, socket.Available, SocketFlags.None);

            string response  = Encoding.UTF8.GetString(bytes);
            int    replyCode = int.Parse(response.Substring(0, 3), NumberFormatInfo.InvariantInfo);
            string message   = response.Substring(4, response.Length - 4);

            if (replyCode != (int)expectedResponse)
            {
                switch (expectedResponse)
                {
                case SmtpReplyCode.ConnectSuccess:
                    throw new SmtpConnectionException(string.Format("Failed to connect to SMTP-server '{0}'. Code: {1} Message: {2}", this.host, replyCode, message));

                case SmtpReplyCode.AuthSuccess:
                case SmtpReplyCode.AuthRequest:
                    throw new SmtpAuthenticationException(string.Format("Authentication to SMTP-server failed '{0}'. Code: {1} Message: {2}", this.host, replyCode, message));

                case SmtpReplyCode.DataSuccess:
                    throw new SmtpDataTransferException(string.Format("Failed to send data to SMTP-server '{0}'. Code: {1} Message: {2}", this.host, replyCode, message));

                default:
                    throw new SmtpException(string.Format("Failed to send mail through SMTP-server '{0}'. Code: {1} Message: {2}", this.host, replyCode, message));
                }
            }

            return(new SmtpResponse(replyCode, message));
        }
Exemplo n.º 7
0
        // Open connection to host on port.
        private void OpenConnection()
        {
            ReplyStrings = new List <string>();
            Socket       = new TcpClient();

            // connect to mail server
            Socket.SendTimeout    = TimeoutMS;
            Socket.ReceiveTimeout = TimeoutMS;
            Socket.Connect(Host, Port);

            if (ConnMethod == ConnectMethod.Secure)
            {
                // create SSL stream
                SslStream sslStream = new SslStream(Socket.GetStream(), true, ServerValidationCallback, ClientCertificateSelectionCallback, EncryptionPolicy.AllowNoEncryption);

                // autheticate client
                sslStream.AuthenticateAsClient(Host);

                // create read and write streams
                Writer = new StreamWriter(sslStream, Encoding.ASCII);
                Reader = new StreamReader(sslStream, Encoding.ASCII);
            }
            else
            {
                NetworkStream NetStream = Socket.GetStream();
                Writer = new StreamWriter(NetStream, Encoding.ASCII);
                Reader = new StreamReader(NetStream, Encoding.ASCII);
            }

            // Code 220 means that service is up and working
            SmtpReplyCode ReplyCode = GetReply();

            if (ReplyCode != SmtpReplyCode.Ready)
            {
                        #if DEBUG
                Debug.WriteLine(string.Format("Open connection to {0} failed. Reply code {1}", Host, (int)ReplyCode));
                        #endif

                throw new ApplicationException("Connect to mail server failed");
            }
            return;
        }
Exemplo n.º 8
0
        Task ISmtpMessageChannel.SendReplyAsync(
            SmtpReplyCode smtpReplyCode,
            bool more,
            string message,
            CancellationToken cancellationToken)
        {
            var builder = new StringBuilder();

            builder.Append(((int)smtpReplyCode).ToString("D3"));
            builder.Append(more ? "-" : " ");
            if (message != null)
            {
                builder.Append(message);
            }

            string output = builder.ToString();

            _log.Verbose($"SMTP -> {output}");
            return(_connection.WriteLineAsync(output, Encoding.ASCII, cancellationToken));
        }
Exemplo n.º 9
0
        ////////////////////////////////////////////////////////////////////
        // Send command to the server.
        ////////////////////////////////////////////////////////////////////
        private void SendCommand(string command, SmtpReplyCode expectedReply)
        {
            // send command
            var bytes = Encoding.UTF8.GetBytes(command + "\r\n");

            _writer.Write(bytes, 0, bytes.Length);
            _writer.Flush();

            // test reply
            if (expectedReply == SmtpReplyCode.IgnoreReply)
            {
                return;
            }
            var replyCode = GetReply();

            if (replyCode == expectedReply)
            {
                return;
            }

            throw new ApplicationException("Command error: " + command);
        }
Exemplo n.º 10
0
 public Entry(SmtpReplyCode code, string message, bool more)
 {
     Code    = code;
     Message = message;
     More    = more;
 }
Exemplo n.º 11
0
 public Task SendReplyAsync(SmtpReplyCode smtpReplyCode, bool more, string message, CancellationToken token)
 {
     Entries.Add(new Entry(smtpReplyCode, message, more));
     return(Task.CompletedTask);
 }
Exemplo n.º 12
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="replyCode">Reply error code</param>
 public SmtpException(SmtpReplyCode replyCode)
 {
     this.replyCode = replyCode;
 }
Exemplo n.º 13
0
 internal SmtpResponse(SmtpReplyCode replyCode, string message = null)
 {
     ReplyCode = replyCode;
     Message   = message;
 }
Exemplo n.º 14
0
 public SmtpResponse(SmtpReplyCode code, List <string> lines)
 {
     Code  = code;
     Lines = lines;
 }
Exemplo n.º 15
0
 internal SmtpCommand MakeInvalid(SmtpReplyCode code, string response = "")
 {
     return(new InvalidCommand(new SmtpResponse(code, response)));
 }
Exemplo n.º 16
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="replyCode">Reply error code</param>
 public SmtpException(SmtpReplyCode replyCode)
 {
     this.replyCode = replyCode;
 }
Exemplo n.º 17
0
 public static void AssertResponse(MockSmtpChannel channel, SmtpReplyCode reply)
 {
     Assert.Equal(1, channel.Entries.Count);
     AssertResponse(channel.Entries[0], reply);
 }
Exemplo n.º 18
0
 public static void AssertResponse(MockSmtpChannel.Entry entry, SmtpReplyCode reply)
 {
     Assert.False(entry.More);
     Assert.Equal(reply, entry.Code);
 }
Exemplo n.º 19
0
 public SmtpServerReply(SmtpReplyCode code, string raw, string message)
 {
     this.Code       = code;
     this.RawMessage = raw;
     this.Message    = message;
 }
Exemplo n.º 20
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="replyCode">The reply code.</param>
 /// <param name="message">The reply message.</param>
 public SmtpResponse(SmtpReplyCode replyCode, string message = null)
 {
     ReplyCode = replyCode;
     Message = message;
 }