Ejemplo n.º 1
0
        public virtual void Save(System.IO.TextWriter txt)
        {
            txt.WriteLine("Date: {0}", (Date == DateTime.MinValue ? DateTime.Now : Date).GetRFC2060Date());
            txt.WriteLine("To: {0}", string.Join("; ", To.Select(x => x.ToString())));
            txt.WriteLine("Cc: {0}", string.Join("; ", Cc.Select(x => x.ToString())));
            txt.WriteLine("Reply-To: {0}", string.Join("; ", ReplyTo.Select(x => x.ToString())));
            txt.WriteLine("Bcc: {0}", string.Join("; ", Bcc.Select(x => x.ToString())));
            if (Sender != null)
            {
                txt.WriteLine("Sender: {0}", Sender);
            }
            if (From != null)
            {
                txt.WriteLine("From: {0}", From);
            }
            if (!string.IsNullOrEmpty(MessageID))
            {
                txt.WriteLine("Message-ID: {0}", MessageID);
            }

            var otherHeaders = Headers.Where(x => !SpecialHeaders.Contains(x.Key, StringComparer.InvariantCultureIgnoreCase));

            foreach (var header in otherHeaders)
            {
                txt.WriteLine("{0}: {1}", header.Key, header.Value);
            }
            if (Importance != MailPriority.Normal)
            {
                txt.WriteLine("Importance: {0}", (int)Importance);
            }
            txt.WriteLine("Subject: {0}", Subject);

            string boundary = null;

            if (Attachments.Any() || AlternateViews.Any())
            {
                boundary = string.Format("--boundary_{0}", Guid.NewGuid());
                txt.WriteLine("Content-Type: multipart/mixed; boundary={0}", boundary);
            }

            // signal end of headers
            txt.WriteLine();

            if (boundary != null)
            {
                txt.WriteLine("--" + boundary);
                txt.WriteLine();
            }

            txt.WriteLine(Body);

            AlternateViews.Union(Attachments).ToList().ForEach(att => {
                txt.WriteLine("--" + boundary);
                txt.WriteLine(string.Join("\n", att.Headers.Select(h => string.Format("{0}: {1}", h.Key, h.Value))));
                txt.WriteLine();
                txt.WriteLine(att.Body);
            });

            if (boundary != null)
            {
                txt.WriteLine("--" + boundary + "--");
            }
        }
Ejemplo n.º 2
0
        /// <summary>Returns the MailMessage as a RFC 822 formatted message</summary>
        public override string ToString()
        {
            StringBuilder         sb = new StringBuilder(60000);
            MimeHeaderLineBuilder lb = new MimeHeaderLineBuilder( );

            lb.Traits.SetEncoderCharSet(charset);

            // reply to email address
            sb.Append(
                MimeCommon.ConcatMessageLine(
                    lb.Traits,
                    "Reply-To:",
                    ReplyTo.ToMimeString(lb.Traits.EncoderCharSet),
                    MimeConstants.CrLf));

            // BgnTemp debug.  an already encoded from email address.
            if (mEncodedFromAddress != null)
            {
                sb.Append(mEncodedFromAddress + MimeConstants.CrLf);
            }
            else
            {
                // EndTemp debug.

                // send from email address
                sb.Append(
                    MimeCommon.ConcatMessageLine(
                        lb.Traits,
                        "From:",
                        From.ToMimeString(lb.Traits.EncoderCharSet),
                        MimeConstants.CrLf));
            }

            // send to email address
            sb.Append(
                MimeCommon.ConcatMessageLine(
                    lb.Traits,
                    "To:",
                    ToRecipients.ToMessageHeaderString(lb.Traits.EncoderCharSet),
                    MimeConstants.CrLf));

//			sb.Append( "Reply-To: " ) ;
//			sb.Append( ReplyTo.ToMimeString( charset )) ;
//			sb.Append( SmtpConstants.CrLf ) ;

//			sb.Append( "From: " + From.ToMimeStringToMessageHeaderString( charset )) ;
//			sb.Append( SmtpConstants.CrLf ) ;
//			sb.Append( "To: " + ToRecipients.ToMessageHeaderString( charset )) ;
//			sb.Append( SmtpConstants.CrLf ) ;

            if (CCRecipients.Count > 0)
            {
                sb.Append("CC: " + CCRecipients.ToMessageHeaderString(charset));
                sb.Append(SmtpConstants.CrLf);
            }

            if (BCCRecipients.Count > 0)
            {
                sb.Append("BCC: " + BCCRecipients.ToMessageHeaderString(charset));
                sb.Append(SmtpConstants.CrLf);
            }

            // message subject line.
            if (Stringer.IsNotEmpty(Subject))
            {
                lb.Clear( );
                lb.Append("Subject: ");
                lb.Append(Subject);
                sb.Append(lb.ToEncodedString( ) + MimeConstants.CrLf);
            }

            // BgnTemp debug.  an already encoded subject line.
            if (mEncodedSubject != null)
            {
                sb.Append(mEncodedSubject + MimeConstants.CrLf);
            }
            // EndTemp debug.

            // send timestamp
            lb
            .Clear( )
            .Append("Date: " + DateTime.Now.ToUniversalTime().ToString("R"));
            sb.Append(lb.ToEncodedString( ) + MimeConstants.CrLf);

            sb.Append(SmtpConfig.X_MAILER_HEADER + "\r\n");

            if (notification)
            {
                if (ReplyTo.FriendlyName != null && ReplyTo.FriendlyName.Length != 0)
                {
                    sb.Append("Disposition-Notification-To: " + MailEncoder.ConvertHeaderToQP(ReplyTo.FriendlyName, charset) + " <" + ReplyTo.Address + ">\r\n");
                }
                else
                {
                    sb.Append("Disposition-Notification-To: <" + ReplyTo.Address + ">\r\n");
                }
            }

            if (priority != null)
            {
                sb.Append("X-Priority: " + priority + "\r\n");
            }

            if (customHeaders != null)
            {
                for (IEnumerator i = customHeaders.GetEnumerator(); i.MoveNext();)
                {
                    MailHeader m = (MailHeader)i.Current;

                    if (m.name.Length >= 0 && m.body.Length >= 0)
                    {
                        sb.Append(m.name + ":" + MailEncoder.ConvertHeaderToQP(m.body, charset) + "\r\n");
                    }
                    else
                    {
                        // TODO: Check if below is within RFC spec.
                        sb.Append(m.name + ":\r\n");
                    }
                }
            }

            sb.Append("MIME-Version: 1.0\r\n");
            sb.Append(GetMessageBody());

            return(sb.ToString());
        }
Ejemplo n.º 3
0
        protected override void OnCommand(object message)
        {
            switch (message)
            {
            case Cmd c when c.Mode == "p":
                Persist(c, d =>
                {
                    _counter += 1;
                    if (d.Payload != _counter)
                    {
                        throw new ArgumentException($"Expected to receive [{_counter}] yet got: [{d.Payload}]");
                    }
                    if (_counter == ReplyAfter)
                    {
                        ReplyTo.Tell(d.Payload);
                    }
                });
                break;

            case Cmd c when c.Mode == "pb":
                _batch.Add(c);

                if (_batch.Count % BatchSize == 0)
                {
                    PersistAll(_batch, d =>
                    {
                        _counter += 1;
                        if (d.Payload != _counter)
                        {
                            throw new ArgumentException($"Expected to receive [{_counter}] yet got: [{d.Payload}]");
                        }
                        if (_counter == ReplyAfter)
                        {
                            ReplyTo.Tell(d.Payload);
                        }
                    });
                    _batch = new List <Cmd>(BatchSize);
                }
                break;

            case Cmd c when c.Mode == "pa":
                PersistAsync(c, d =>
                {
                    _counter += 1;
                    if (d.Payload != _counter)
                    {
                        throw new ArgumentException($"Expected to receive [{_counter}] yet got: [{d.Payload}]");
                    }
                    if (_counter == ReplyAfter)
                    {
                        ReplyTo.Tell(d.Payload);
                    }
                });
                break;

            case Cmd c when c.Mode == "pba":
                _batch.Add(c);

                if (_batch.Count % BatchSize == 0)
                {
                    PersistAllAsync(_batch, d =>
                    {
                        _counter += 1;
                        if (d.Payload != _counter)
                        {
                            throw new ArgumentException($"Expected to receive [{_counter}] yet got: [{d.Payload}]");
                        }
                        if (_counter == ReplyAfter)
                        {
                            ReplyTo.Tell(d.Payload);
                        }
                    });
                    _batch = new List <Cmd>(BatchSize);
                }
                break;

            case ResetCounter _:
                _counter = 0;
                break;
            }
        }
Ejemplo n.º 4
0
 public UserMessage SetSystem(SystemName sys) =>
 new UserMessage(Content, Sender.SetSystem(sys), ReplyTo.SetSystem(sys));
Ejemplo n.º 5
0
 protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
 {
     ReplyTo.WriteContentsTo(Version, writer);
 }
Ejemplo n.º 6
0
        internal void PrepareHeaders(bool sendEnvelope, bool allowUnicode)
        {
            string headerName;

            if (_headersEncoding == null)
            {
                _headersEncoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
            }

            //ContentType is written directly to the stream so remove potential user duplicate
            Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.ContentType) !);

            Headers[MailHeaderInfo.GetString(MailHeaderID.MimeVersion)] = "1.0";

            // add sender to headers first so that it is written first to allow the IIS smtp svc to
            // send MAIL FROM with the sender if both sender and from are present
            headerName = MailHeaderInfo.GetString(MailHeaderID.Sender) !;
            if (Sender != null)
            {
                Headers.InternalAdd(headerName, Sender.Encode(headerName.Length, allowUnicode));
            }
            else
            {
                Headers.Remove(headerName);
            }

            headerName = MailHeaderInfo.GetString(MailHeaderID.From) !;
            Headers.InternalAdd(headerName, From !.Encode(headerName.Length, allowUnicode));

            headerName = MailHeaderInfo.GetString(MailHeaderID.To) !;
            if (To.Count > 0)
            {
                Headers.InternalAdd(headerName, To.Encode(headerName.Length, allowUnicode));
            }
            else
            {
                Headers.Remove(headerName);
            }

            headerName = MailHeaderInfo.GetString(MailHeaderID.Cc) !;
            if (CC.Count > 0)
            {
                Headers.InternalAdd(headerName, CC.Encode(headerName.Length, allowUnicode));
            }
            else
            {
                Headers.Remove(headerName);
            }

            headerName = MailHeaderInfo.GetString(MailHeaderID.ReplyTo) !;
            if (ReplyTo != null)
            {
                Headers.InternalAdd(headerName, ReplyTo.Encode(headerName.Length, allowUnicode));
            }
            else if (ReplyToList.Count > 0)
            {
                Headers.InternalAdd(headerName, ReplyToList.Encode(headerName.Length, allowUnicode));
            }
            else
            {
                Headers.Remove(headerName);
            }

            Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Bcc) !);

            if (_priority == MailPriority.High)
            {
                Headers[MailHeaderInfo.GetString(MailHeaderID.XPriority)]  = "1";
                Headers[MailHeaderInfo.GetString(MailHeaderID.Priority)]   = "urgent";
                Headers[MailHeaderInfo.GetString(MailHeaderID.Importance)] = "high";
            }
            else if (_priority == MailPriority.Low)
            {
                Headers[MailHeaderInfo.GetString(MailHeaderID.XPriority)]  = "5";
                Headers[MailHeaderInfo.GetString(MailHeaderID.Priority)]   = "non-urgent";
                Headers[MailHeaderInfo.GetString(MailHeaderID.Importance)] = "low";
            }
            //if the priority was never set, allow the app to set the headers directly.
            else if (((int)_priority) != -1)
            {
                Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.XPriority) !);
                Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Priority) !);
                Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Importance) !);
            }

            Headers.InternalAdd(MailHeaderInfo.GetString(MailHeaderID.Date) !,
                                MailBnfHelper.GetDateTimeString(DateTime.Now, null) !);

            headerName = MailHeaderInfo.GetString(MailHeaderID.Subject) !;
            if (!string.IsNullOrEmpty(_subject))
            {
                if (allowUnicode)
                {
                    Headers.InternalAdd(headerName, _subject);
                }
                else
                {
                    Headers.InternalAdd(headerName,
                                        MimeBasePart.EncodeHeaderValue(_subject, _subjectEncoding,
                                                                       MimeBasePart.ShouldUseBase64Encoding(_subjectEncoding),
                                                                       headerName.Length));
                }
            }
            else
            {
                Headers.Remove(headerName);
            }

            EncodeHeaders(_headers !, allowUnicode);
        }
Ejemplo n.º 7
0
        /// <summary>Returns the MailMessage as a RFC 822 formatted message</summary>
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder(60000);

            sb.Append("Reply-To: " + ReplyTo.ToMessageHeaderString(charset));
            sb.Append(SmtpConstants.CrLf);
            sb.Append("From: " + From.ToMessageHeaderString(charset));
            sb.Append(SmtpConstants.CrLf);

            if (1 == 2)
            {
                if (Stringer.IsNotEmpty(ReplyTo.FriendlyName))
                {
                    string rt = MessageHeaderString.EncodeAsRequired(
                        Stringer.Enquote(ReplyTo.FriendlyName, '"', QuoteEncapsulation.Escape),
                        new QuotedPrintableTraits( ));
                    sb.Append("Reply-To: ");
                    sb.Append(rt);
                    sb.Append(" <" + ReplyTo.Address + ">" + SmtpConstants.CrLf);
                    string debug = sb.ToString( );
                }
                else
                {
                    sb.Append("Reply-To: <" + ReplyTo.Address + ">" + SmtpConstants.CrLf);
                }

                // from email address.
                if (Stringer.IsNotEmpty(From.FriendlyName))
                {
                    string rt = MessageHeaderString.EncodeAsRequired(
                        Stringer.Enquote(From.FriendlyName, '"', QuoteEncapsulation.Escape),
                        new QuotedPrintableTraits( ));
                    sb.Append("From: ");
                    sb.Append(rt);
                    sb.Append(" <" + From.Address + ">" + SmtpConstants.CrLf);
                }
                else
                {
                    sb.Append("From: <" + From.Address + ">" + SmtpConstants.CrLf);
                }
            }

            sb.Append("To: " + CreateAddressList(mToRecipients) + "\r\n");

            if (CCRecipients.Count != 0)
            {
                sb.Append("CC: " + CreateAddressList(CCRecipients) + "\r\n");
            }

            if (subject != null && subject.Length > 0)
            {
                StringBuilder cleanSubject = new StringBuilder(subject);
                cleanSubject.Replace("\r\n", null);
                cleanSubject.Replace("\n", null);

                sb.Append("Subject: " + MailEncoder.ConvertHeaderToQP(cleanSubject.ToString(), charset) + "\r\n");
            }

            sb.Append("Date: " + DateTime.Now.ToUniversalTime().ToString("R") + "\r\n");
            sb.Append(SmtpConfig.X_MAILER_HEADER + "\r\n");

            if (notification)
            {
                if (ReplyTo.FriendlyName != null && ReplyTo.FriendlyName.Length != 0)
                {
                    sb.Append("Disposition-Notification-To: " + MailEncoder.ConvertHeaderToQP(ReplyTo.FriendlyName, charset) + " <" + ReplyTo.Address + ">\r\n");
                }
                else
                {
                    sb.Append("Disposition-Notification-To: <" + ReplyTo.Address + ">\r\n");
                }
            }

            if (priority != null)
            {
                sb.Append("X-Priority: " + priority + "\r\n");
            }

            if (customHeaders != null)
            {
                for (IEnumerator i = customHeaders.GetEnumerator(); i.MoveNext();)
                {
                    MailHeader m = (MailHeader)i.Current;

                    if (m.name.Length >= 0 && m.body.Length >= 0)
                    {
                        sb.Append(m.name + ":" + MailEncoder.ConvertHeaderToQP(m.body, charset) + "\r\n");
                    }
                    else
                    {
                        // TODO: Check if below is within RFC spec.
                        sb.Append(m.name + ":\r\n");
                    }
                }
            }

            sb.Append("MIME-Version: 1.0\r\n");
            sb.Append(GetMessageBody());

            return(sb.ToString());
        }
Ejemplo n.º 8
0
        public override string GetStreamAPIURL()
        {
            string url = "https://stream.gnip.com:443/accounts/{0}/publishers/twitter/streams/sample1track/{1}.json";

            url = string.Format(url, Account, IsLive ? "prod" : "reply");

            if (!IsLive)
            {
                url = string.Format("{0}?fromDate={1}&toDate={2}", url, ReplyFrom.ToString("yyyyMMddHHmm"), ReplyTo.ToString("yyyyMMddHHmm"));
            }

            return(url);
        }
Ejemplo n.º 9
0
 public virtual void ReplyTo(C context, ReplyTo mystruct)
 {
 }
Ejemplo n.º 10
0
        public override bool Equals(object obj)
        {
            if (this == obj)
            {
                return(true);
            }

            if (obj == null)
            {
                return(false);
            }

            if (GetType() != obj.GetType())
            {
                return(false);
            }

            var other = (MessageProperties)obj;

            if (AppId == null)
            {
                if (other.AppId != null)
                {
                    return(false);
                }
            }
            else if (!AppId.Equals(other.AppId))
            {
                return(false);
            }

            if (ClusterId == null)
            {
                if (other.ClusterId != null)
                {
                    return(false);
                }
            }
            else if (!ClusterId.Equals(other.ClusterId))
            {
                return(false);
            }

            if (ContentEncoding == null)
            {
                if (other.ContentEncoding != null)
                {
                    return(false);
                }
            }
            else if (!ContentEncoding.Equals(other.ContentEncoding))
            {
                return(false);
            }

            if (ContentLength != other.ContentLength)
            {
                return(false);
            }

            if (ContentType == null)
            {
                if (other.ContentType != null)
                {
                    return(false);
                }
            }
            else if (!ContentType.Equals(other.ContentType))
            {
                return(false);
            }

            if (CorrelationId == null)
            {
                if (other.CorrelationId != null)
                {
                    return(false);
                }
            }
            else if (!CorrelationId.Equals(other.CorrelationId))
            {
                return(false);
            }

            if (DeliveryMode != other.DeliveryMode)
            {
                return(false);
            }

            if (DeliveryTag != other.DeliveryTag)
            {
                return(false);
            }

            if (Expiration == null)
            {
                if (other.Expiration != null)
                {
                    return(false);
                }
            }
            else if (!Expiration.Equals(other.Expiration))
            {
                return(false);
            }

            if (!Headers.Equals(other.Headers))
            {
                return(false);
            }

            if (MessageCount == null)
            {
                if (other.MessageCount != null)
                {
                    return(false);
                }
            }
            else if (!MessageCount.Equals(other.MessageCount))
            {
                return(false);
            }

            if (MessageId == null)
            {
                if (other.MessageId != null)
                {
                    return(false);
                }
            }
            else if (!MessageId.Equals(other.MessageId))
            {
                return(false);
            }

            if (Priority == null)
            {
                if (other.Priority != null)
                {
                    return(false);
                }
            }
            else if (!Priority.Equals(other.Priority))
            {
                return(false);
            }

            if (ReceivedExchange == null)
            {
                if (other.ReceivedExchange != null)
                {
                    return(false);
                }
            }
            else if (!ReceivedExchange.Equals(other.ReceivedExchange))
            {
                return(false);
            }

            if (ReceivedRoutingKey == null)
            {
                if (other.ReceivedRoutingKey != null)
                {
                    return(false);
                }
            }
            else if (!ReceivedRoutingKey.Equals(other.ReceivedRoutingKey))
            {
                return(false);
            }

            if (Redelivered == null)
            {
                if (other.Redelivered != null)
                {
                    return(false);
                }
            }
            else if (!Redelivered.Equals(other.Redelivered))
            {
                return(false);
            }

            if (ReplyTo == null)
            {
                if (other.ReplyTo != null)
                {
                    return(false);
                }
            }
            else if (!ReplyTo.Equals(other.ReplyTo))
            {
                return(false);
            }

            if (Timestamp == null)
            {
                if (other.Timestamp != null)
                {
                    return(false);
                }
            }
            else if (!Timestamp.Equals(other.Timestamp))
            {
                return(false);
            }

            if (Type == null)
            {
                if (other.Type != null)
                {
                    return(false);
                }
            }
            else if (!Type.Equals(other.Type))
            {
                return(false);
            }

            if (UserId == null)
            {
                if (other.UserId != null)
                {
                    return(false);
                }
            }
            else if (!UserId.Equals(other.UserId))
            {
                return(false);
            }

            return(true);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Send the message.
        /// </summary>
        /// <returns>
        /// True if it succeeds.
        /// </returns>
        public bool SendMail()
        {
            // Create a mail message.
            MimeMessage message = new MimeMessage();

            // Handle addresses.
            message.From.Add(new MailboxAddress(SenderName, SenderEmail));
            foreach (string address in Recipients.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
            {
                message.To.Add(new MailboxAddress(address.Trim()));
            }
            foreach (string address in CCRecipients.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
            {
                message.Cc.Add(new MailboxAddress(address.Trim()));
            }
            foreach (string address in BCCRecipients.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
            {
                message.Bcc.Add(new MailboxAddress(address.Trim()));
            }
            if (!String.IsNullOrEmpty(ReplyTo))
            {
                foreach (string address in ReplyTo.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    message.ReplyTo.Add(new MailboxAddress(address.Trim()));
                }
            }

            // Set up the subject, body, and attachments.
            message.Subject = Subject;
            var builder = new BodyBuilder();

            if (UseHtml)
            {
                builder.HtmlBody = Message;
            }
            else
            {
                builder.TextBody = Message;
            }
            foreach (string path in _attachments)
            {
                builder.Attachments.Add(path);
            }
            message.Body = builder.ToMessageBody();

            // Send the message.
            SmtpClient client;

            if (String.IsNullOrWhiteSpace(LogFile))
            {
                client = new SmtpClient();
            }
            else
            {
                client = new SmtpClient(new ProtocolLogger(LogFile));
            }
            using (client)
            {
                // Accept all SSL certificates (in case the server supports STARTTLS).
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                client.Timeout = Timeout * 1000;
                // See https://unop.uk/sending-email-in-.net-core-with-office-365-and-mailkit/ for Office 365 or
                // https://unop.uk/advanced-email-sending-with-.net-core-and-mailkit/ for a more advanced guide
                SecureSocketOptions value = (SecureSocketOptions)SecurityOptions;
                client.Connect(MailServer, ServerPort, value);
                if (OAuthenticate != null)
                {
                    client.Authenticate(OAuthenticate);
                }
                else if (!String.IsNullOrWhiteSpace(UserName))
                {
                    // TODO: may have to use System.Text.Encoding.UTF8 as first parameter; see https://github.com/jstedfast/MailKit/issues/686
                    // See https://dotnetcoretutorials.com/2018/03/18/common-errors-sending-email-mailkit/ for common errors
                    client.Authenticate(UserName, Password);
                }
                client.Send(message);
                client.Disconnect(true);
            }
            client.Dispose();
            return(true);
        }