Git Product home page Git Product logo

aenetmail's People

Contributors

andyedinborough avatar b2berry avatar deaquino avatar filpen avatar geograph-us avatar gymbrall avatar ignacionr avatar ilivewithian avatar jorgef avatar joshilewis avatar jvdvleuten avatar kivikakk avatar kuttkatrea avatar miguelerm avatar moonpyk avatar mungojam avatar nicolas01 avatar nikolausm avatar nwoolls avatar paolosanchi avatar petersondrew avatar philipspigelmire avatar piher avatar rflipper avatar rix0rrr avatar robitar avatar summercat avatar technicallyfeasible avatar thefra985 avatar warrenfalk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aenetmail's Issues

IDLE Not working

I've attempted to use your current cs files and also swapped them out with NadavK 's files without luck. NadavK's files worked very intermittently. Initial connection, I would send 2 or 3 messages to the specific server that the software is looking for and 1 or 2 would actually trigger the NewMessage event. I was also getting errors when trying to Disconnect. Is this an issue that I am only seeing, or am I missing something. Here's my implementation in Vb.Net. I have the C# project referenced with my VB.Net application.. I've also tried this with SSL on port 993. Connects ok either way. Is NadavK's code integrated with the latest ImapClient.cs and other files?

Public WithEvents AENetIMAPClient As Global.AE.Net.Mail.ImapClient
Public Host As String = "XXXX"
Public User As String = "XXXX"
Public Pass As String = "XXX"
Public Sub Start()
Try

        AENetIMAPClient = New Global.AE.Net.Mail.ImapClient(Host, User, Pass, Global.AE.Net.Mail.ImapClient.AuthMethods.Login, 143, False)


        AddHandler AENetIMAPClient.NewMessage, AddressOf AEIMAPClient_New

Catch ex As Exception
MsgBox(ex.Message.ToString(), MsgBoxStyle.Critical, "Start Error")
End Try
End Sub

IDLE code receiving responses for other operations

After the changes to the IDLE code, the IdleResumeCommand function in ImapClient is throwing exceptions on some operations (like MoveMessage). This seems to be because that code is catching the responses for the other commands (EXPUNGE for MoveMessage, I've also seen OK SUCCESS).

Is it really necessary to throw and exception if we don't get the response we were expecting? It seems like since we don't do anything with the response, it's pointless to throw an exception.

Body not parsed from text/plain messages sent by Gmail

The library fails to parse the message body in text/plain messages send by Gmail. I've attached an example, I'm really not sure how to fix the parsing logic to account for this except maybe checking the headers for content-type: text/plain?
What's happening is that the one line of body text is being treated as if it's part of the headers.

Delivered-To: [email protected]
Received: by 10.142.174.3 with SMTP id w3cs50740wfe;
        Mon, 14 Nov 2011 18:10:08 -0800 (PST)
Return-Path: <[email protected]>
Received-SPF: pass (google.com: domain of [email protected] designates 10.227.208.71 as permitted sender) client-ip=10.227.208.71;
Authentication-Results: mr.google.com; spf=pass (google.com: domain of [email protected] designates 10.227.208.71 as permitted sender) [email protected]; dkim=pass [email protected]
Received: from mr.google.com ([10.227.208.71])
        by 10.227.208.71 with SMTP id gb7mr16473303wbb.7.1321323006082 (num_hops = 1);
        Mon, 14 Nov 2011 18:10:06 -0800 (PST)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
        d=gmail.com; s=gamma;
        h=mime-version:from:date:message-id:subject:to:content-type;
        bh=3ajdGhBv88zJknw0EVGu6lJhm0zz+4eRVot/EGmYTOs=;
        b=nxqtHAr0o4/76BCnJVbxXCL0NWiABD9o1ijDXpJaNIJ19+ParWNzEtbTf9xiFMtoDI
        kufMoypwCxokbNJRXxmiuXnWSBvQ2UhNqwnIYvr2YxXpj+nOIEZOXmoj2S3DF0PM7Qif
        MuSMSi3f4Jmcscmi6KNeP4wCcmqF564fccGhw=
Received: by 10.227.208.71 with SMTP id gb7mr16473303wbb.7.1321323006076; Mon,
14 Nov 2011 18:10:06 -0800 (PST)
MIME-Version: 1.0
Received: by 10.227.200.65 with HTTP; Mon, 14 Nov 2011 18:09:45 -0800 (PST)
From: Drew Peterson <[email protected]>
Date: Mon, 14 Nov 2011 20:09:45 -0600
Message-ID: <redacted>
Subject: test2
To: [email protected]
Content-Type: text/plain; charset=UTF-8

Test message body

InvalidOperationException on ImapClient.Dispose

After upgrading to version 1.5 from Nuget, I receive the following error when calling Dispose on an ImapClient:

System.InvalidOperationException was unhandled
  Message=The collection has been marked as complete with regards to additions.
  Source=System
  StackTrace:
       at System.Collections.Concurrent.BlockingCollection`1.TryAddWithNoTimeValidation(T item, Int32 millisecondsTimeout, CancellationToken cancellationToken)
       at System.Collections.Concurrent.BlockingCollection`1.Add(T item)
       at AE.Net.Mail.TextClient.ReceiveData() in C:\repos\AE.Net.Mail\TextClient.cs:line 87
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

The exception is thrown from ReceiveData in TextClient after ReadThread.Join is called from Disconnect. When attempting to set a breakpoint the debugger refuses to break in the ReceiveData function before the exception is thrown, so I can't give you much more info than that.

Simple correction in attachment filename parsing

Hi,
When sending files with attachments through the .Net default smtp class, attachments headers look like that :

----boundary_0_7faa88fa-e993-4b32-9b03-606e3bd87a18
Content-Type: application/octet-stream; name=Angry_baby.jpg
Content-Transfer-Encoding: base64
Content-Disposition: attachment

And thus the name is not parsed.
So I suggest this simple fix :

public string Filename {
        get { return Headers["Content-Disposition"]["filename"] ?? Headers["Content-Disposition"]["name"]; }
    }

Body character coding problem

Hi!

I'm working on a program in VS2010 (C#) and using your component to receive unseen messages. It's working nice but today I received a mail that is not shown correctly and containing '?' characters (Unicode characters).
Here is the code I use:

System.Lazy<AE.Net.Mail.MailMessage>[] myMessages = _client2.SearchMessages(AE.Net.Mail.SearchCondition.Unseen());
foreach (System.Lazy<AE.Net.Mail.MailMessage> message in myMessages)
{
AE.Net.Mail.MailMessage msg = message.Value;
}

I have added a watch on "msg" variable and can see the following:
msg.AlternativeViews[0].Content -> A h�ten virtu�lis
msg.AlternativeViews[0].ContentEncoding -> 8bit
msg.BodyHtml -> the same as above, but with html tags

msg.AlternativeViews[0].Content should be look like this -> A héten virtuális...

As you can see the message body contains accute (Unicode) characters (they are Hungarian characters, and might be in ISO-8859-1, or ISO-8859-2).

Raising events during getmessages

Hi,

Not really an issue, just a very quick question : why not raising an event in getmessages every time a message has been fetched ?

Charset in imap doesn't work correctly

i think something should be done in the internal void SetBody(string value) method..
because in the value that is assigned to Body has wrong characters:
latin characters like 'à' and 'ò' are converted to '?'

GetMessages returns only one message

Hi. I downloaded today fresh copy of project, compiled id and I have following problem with this code:

        using (var imap = new ImapClient("imap.gmail.com", "user", "pass", ImapClient.AuthMethods.Login, 993, true))
        {
            imap.SelectMailbox(@"INBOX");
            textBox1.AppendText(imap.GetMessageCount() + Environment.NewLine);
            // Get the first *11* messages. 0 is the first message;
            // and it also includes the 10th message, which is really the eleventh ;)
            // MailMessage represents, well, a message in your mailbox
            MailMessage[] mm = imap.GetMessages(0, 10);
            foreach (MailMessage m in mm)
            {
                textBox1.AppendText(m.ContentType + Environment.NewLine);
                textBox1.AppendText(m.Charset + Environment.NewLine);
                textBox1.AppendText(m.ContentTransferEncoding + Environment.NewLine);
                textBox1.AppendText(m.Subject + Environment.NewLine);
            }
        }

Problem is it returns only one message, when GetMessageCount() returns 67 messages.

Working with a proxy

Hello,

I am exceptionally on a network that requires a proxy configuration.
I thought I would try out my email software on this network, and as it turns out the TcpClient object doesn't work on proxies and doesn't seem to allow any proxy configuration.

Have you used your library through a proxy ?

If not, i have found a quite simple open-source C# library creating TcpClient objects through proxies :
http://www.starksoft.com/prod_proxy.html

As an example, the connect method in Imap client could become something like :

public void Connect(string hostname, int port, bool ssl, string proxyHost = null, int proxyPort = -1, ProxyType proxyType = ProxyType.None)
{
try
{
Host = hostname;
Port = port;
Ssl = ssl;

            if (proxyHost != null && proxyType != ProxyType.None && proxyPort > -1)
            {
                // create an instance of the client proxy factory 
                ProxyClientFactory factory = new ProxyClientFactory();

                // use the proxy client factory to generically specify the type of proxy to create 
                // the proxy factory method CreateProxyClient returns an IProxyClient object 
                IProxyClient proxy = factory.CreateProxyClient(proxyType, proxyHost, proxyPort);

                // create a connection through the proxy to hostname over the port 
                _Connection = proxy.CreateConnection(hostname, port);
            }
            else { _Connection = new TcpClient(hostname, port); }


            _Stream = _Connection.GetStream();
            if (ssl)
            {
                var sslSream = new System.Net.Security.SslStream(_Stream);
                _Stream = sslSream;
                sslSream.AuthenticateAsClient(hostname);
            }

            _Reader = new StreamReader(_Stream, System.Text.Encoding.Default);
            string info = _Reader.ReadLine();
            OnConnected(info);

            IsConnected = true;
            Host = hostname;
        }
        catch (Exception)
        {
            IsConnected = false;
            throw;
        }
    }

and the imap constructor :

public ImapClient(string host, string username, string password, AuthMethods method = AuthMethods.Login, int port = 143, bool secure = false, string proxyHost = null, int proxyPort = -1, ProxyType proxyType = ProxyType.None) {
Connect(host, port, secure, proxyHost, proxyPort, proxyType);
AuthMethod = method;
Login(username, password);
}

AppendMail Null Exeption

I am trying to append mails from a MailBox to another MailBox using imap.AppendMail(MailBox,MailMessage). But it gives "Object reference not set to an instance of an object." exeption.

imap GetMessage returns null message

If there are 3 messages in my gmail account imap GetMessageCount() returns 3 but if I iterate over the messages (starting from index zero) I get two non-null messages and one null message. If the account only has one message in it GetMessageCount() returns 1 and GetMessage(0) returns NULL. GetMessages(0, count - 1, false) appears to work properly. I'm using the latest release as of this posting.

[Regression]Problem parsing Headers after upgrade to version 1.6.0

Hello,

After upgrading to 1.6.0 nuget, I saw a regression in From and To Headers parsing. This is blocking, please try to have a look quickly. Thank you.

Expected
Property From : [email protected]
Property To : [email protected]

Got
Property From : null
Property To : empty list

Email:

Return-path: <[email protected]>
Envelope-to: [email protected]
Delivery-date: Sat, 24 Mar 2012 12:07:36 -0600
Received: from [209.85.216.45] (helo=mail-qa0-f45.google.com)
    by box508.bluehost.com with esmtps (TLSv1:RC4-SHA:128)
    (Exim 4.76)
    (envelope-from <[email protected]>)
    id 1SBVNH-0001UX-OP
    for [email protected]; Sat, 24 Mar 2012 12:07:35 -0600
Received: by qafi31 with SMTP id i31so1689831qaf.11
        for <[email protected]>; Sat, 24 Mar 2012 11:07:34 -0700 (PDT)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
        d=gmail.com; s=20120113;
        h=mime-version:in-reply-to:references:date:message-id:subject:from:to
         :content-type;
        bh=XI5g3cp9Z4KDh86UX/bKWDXAEMXCGvauQZgtBx5bOZw=;
        b=h0/g6CgWLivOn/kFbNUMaEGxrvs4b1+tOnLHkYi541HnxLELB9QVAuldcp1Da7ousY
         bKxsSV6cirJ9HHXjTneH+vZXhKiher96G8C6o6P9YDRLwcwJc8EcMib/hiyZI4ttfIZQ
         uW7gmv5m6dN6JWY7My7T4OL8khX4x69F3epQJlCmrGvOuGebUVM9fKOGp/gyCFXbnHqc
         y1R1KUScTO0pzYbOhfGj8F8CStgg8Cfr2L1LSbQaL9RgvmWDTkBgRENhY/+rhtyyOBoG
         qxnZ3hwydFkxQZVLD0URAZ5cqVKj32wyfWccZQyL9FQwRAMJf+ECbejZyuZS+4fKQAZ0
         mBzg==
MIME-Version: 1.0
Received: by 10.224.205.130 with SMTP id fq2mr21049735qab.53.1332612454419;
 Sat, 24 Mar 2012 11:07:34 -0700 (PDT)
Received: by 10.229.102.138 with HTTP; Sat, 24 Mar 2012 11:07:34 -0700 (PDT)
Received: by 10.229.102.138 with HTTP; Sat, 24 Mar 2012 11:07:34 -0700 (PDT)
In-Reply-To: <CAME9Ad+QaZ0ZWvpcW4KiZ1O4XwZ11G=cHsBJC9j_LOd1-AkYBA@mail.gmail.com>
References: <[email protected]>
    <CAME9AdJHjsfkhVebotnr9PyXCzfqmEL0x1h+K7=sPNWnavDYiA@mail.gmail.com>
    <CAME9Ad+E5B1rSXC1kNFtZ8DOnWwWXa8d1v1BHqTOnhNbidNiGw@mail.gmail.com>
    <CAME9Ad+QaZ0ZWvpcW4KiZ1O4XwZ11G=cHsBJC9j_LOd1-AkYBA@mail.gmail.com>
Date: Sat, 24 Mar 2012 19:07:34 +0100
Message-ID: <CAME9AdJO2sqMpXcwmwZqLwaoKmR+4deXu3b14+Q0tOtFLds=8g@mail.gmail.com>
Subject: =?ISO-8859-1?B?RndkOiBSZSA6IOBfbCdhaWRlX3Rlc3RAamF2YWdlbg==?=
From: "Jhon & Kate Doe" <[email protected]>
To: "[email protected]" <[email protected]>
Content-Type: multipart/mixed; boundary=20cf300fab43f80d9304bc0103ed

--20cf300fab43f80d9304bc0103ed
Content-Type: multipart/alternative; boundary=20cf300fab43f80d8e04bc0103eb

--20cf300fab43f80d8e04bc0103eb
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable

Hello, test forward
---------- Forwarded message ----------
From: "Jhon & Kate Doe" <[email protected]>
Date: Mar 22, 2012 10:19 PM
Subject: Fwd: Re : =E0_l&apos;aide_test@example
To: "[email protected]" <[email protected]>

=C0 lo
---------- Forwarded message ----------
From: "Jhon & Kate Doe" <[email protected]>
Date: Mar 22, 2012 9:23 PM
Subject: Fwd: Re : =E0_l&apos;aide_test@example
To: <[email protected]>



---------- Forwarded message ----------
From: Jhon & Kate Doe <[email protected]>
Date: 2012/3/22
Subject: Re: Re : =E0_l'aide_test@example
To: [email protected]


=E0 looo


2012/3/22 Mike Doe <[email protected]>

> Reply
>
>
> Envoy=E9 =E0 partir de Yahoo! Mail (sur Android)
>
>  ------------------------------
> * From: * Jhon & Kate Doe <[email protected]>;
> * To: *
> * Subject: * =E0_l'aide_test@example
> * Sent: * Thu, Mar 22, 2012 7:17:25 PM
>
>   =E0 l'aide
>

--20cf300fab43f80d8e04bc0103eb
Content-Type: text/html; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable


<p>Hello, test forward</p>
<div class=3D"gmail_quote">---------- Forwarded message ----------<br>From:=
 &quot;Jhon &amp; Kate Doe&quot; &lt;<a href=3D"mailto:jhon.doe@=
gmail.com">[email protected]</a>&gt;<br>Date: Mar 22, 2012 10:19 PM<b=
r>
Subject: Fwd: Re : =E0_l&amp;apos;aide_test@example<br>To: &quot;<a href=3D=
"mailto:[email protected]">[email protected]</a>&quot; &lt;<a h=
ref=3D"mailto:[email protected]">[email protected]</a>&gt;<br><=
br type=3D"attribution">

<p>=C0 lo</p>
<div class=3D"gmail_quote"><div class=3D"quoted-text">---------- Forwarded =
message ----------<br>From: &quot;Jhon &amp; Kate Doe&quot; &lt;<a hr=
ef=3D"mailto:[email protected]" target=3D"_blank">jhon.doe@gmail=
.com</a>&gt;<br>
</div><div class=3D"elided-text">Date: Mar 22, 2012 9:23 PM<br>
Subject: Fwd: Re : =E0_l&amp;apos;aide_test@example<br>To:  &lt;<a href=3D"=
mailto:[email protected]" target=3D"_blank">[email protected]</=
a>&gt;<br><br type=3D"attribution"><br><br><div class=3D"gmail_quote"><div>=
---------- Forwarded message ----------<br>

From: <b class=3D"gmail_sendername">Jhon &amp; Kate Doe</b> <span dir=
=3D"ltr">&lt;<a href=3D"mailto:[email protected]" target=3D"_blank">c=
[email protected]</a>&gt;</span><br></div><div>
Date: 2012/3/22<br>Subject: Re: Re : =E0_l&#39;aide_test@example<br>To: <a =
href=3D"mailto:[email protected]" target=3D"_blank">test@exampleerati=
on.com</a><br><br><br>=E0 looo<div><div><br><br><div class=3D"gmail_quote">
2012/3/22 Mike Doe <span dir=3D"ltr">&lt;<a href=3D"mailto:horia.toma@yah=
oo.com" target=3D"_blank">[email protected]</a>&gt;</span><br><blockquot=
e class=3D"gmail_quote" style=3D"margin:0 0 0 .8ex;border-left:1px #ccc sol=
id;padding-left:1ex">



<table cellspacing=3D"0" cellpadding=3D"0" border=3D"0"><tbody><tr><td vali=
gn=3D"top" style=3D"font:inherit"><p>Reply<br><br><br></p>
<p>Envoy=E9 =E0 partir de Yahoo! Mail (sur Android)</p>
</td></tr></tbody></table>            <div>
                <div>
                    <br>
                    <div style=3D"font-family:times new roman,new york,time=
s,serif;font-size:12pt">
                        <font face=3D"Tahoma">
                            <hr size=3D"1">
                            <b>
                                <span style=3D"font-weight:bold">From:</spa=
n>
                            </b>
                            Jhon &amp; Kate Doe &lt;<a href=3D"mailto=
:[email protected]" target=3D"_blank">[email protected]</a>&gt;=
;                            <br>
                            <b>
                                <span>To:</span>
                            </b>
                                                                           =
                                                     <br>
                            <b>
                                <span>Subject:</span>
                            </b>
                            =E0_l&#39;aide_test@example                    =
        <br>
                            <b>
                                <span style=3D"font-weight:bold">Sent:</spa=
n>
                            </b>
                            Thu, Mar 22, 2012 7:17:25 PM                   =
         <br>
                            </font>
                            <br>
                            <table cellspacing=3D"0" cellpadding=3D"0" bord=
er=3D"0">
                                <tbody>
                                    <tr>
                                        <td valign=3D"top" style=3D"font:in=
herit">=E0 l&#39;aide


</td>
                                    </tr>
                                </tbody>
                            </table>
                    </div>
                </div>
            </div>
</blockquote></div><br>
</div></div></div></div><br>
</div></div>

</div>

--20cf300fab43f80d8e04bc0103eb--
--20cf300fab43f80d9304bc0103ed
Content-Type: image/png; name="color_wheel.png"
Content-Disposition: attachment; filename="color_wheel.png"
Content-Transfer-Encoding: base64
X-Attachment-Id: f_h047kla30

iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJ
bWFnZVJlYWR5ccllPAAAAvRJREFUeNpkk09sFAUUxn8zuzOz2y3b7cKudFtKMZCgaUIRCKjBmGhq
Go16knCVm9ZEYwIHT3DCIwkNnEwIJwgHCAIS/BMjGo2EcLG7aZtIS7pbut0u7D92Znbn+bq1cSMv
+Q4z89733vvmewb/i+NZplzh4xZEDrUMDvhCG5qGyTcv7+XT7lwR6XrKHhnnr6NyY2VKpN2S7giC
QIr5MzJ9JSTZa+Hx5wly748buaOSdZdlWdryp3wll2VCHrQOirgfKuEpRVXc6pzkvk1I7qY1vkFg
dgiC1u3fR07i2j4TnOEOeRyi9LAbjB6keh/mj2A7LiOHfyAIzNsbU5hkL0x9ljyB5UR0wYuksZnh
LXoZUZJtmrIdo7YTQkkoHMeJ2CT7PiF7mql1AvGPvdP/EudpEeMVBomT0t7L7CEaSoM3BFZKMQDL
YXhwjv5tbxPAsXUCSxzHNrXrEy3LKF5VgmEqvNjpTpBRkhjyWAXzLP0fM9gxByOkA2qEe38borHJ
JlxIs8WxSDo2fU6GzZpbbldIVe/RrkVVB12h2tSXLuYLHt5iuqNBOH53kNrOHrbmNhHp0Ul7oWI8
pWx77PG3Qj2KKT6uaROUY1Abwsg38Oa3rBO0Q21vrvzMjid6KS4VKC0+Ip6Isk/XcNVNBXmTgdUf
iZS1KN4kGIzTePw3gRF4HYLg2crVX+/z0Uh/i9lcgf6k7msKfUt9PI10OhB195EoXcLO1mFslIXa
HxT91tU1AkMxzOiX84ffGCORGtCPDSZWD7KjmWY4ChlftXNhv/8uJJOUihVWvvue3V5juxppYc1I
C1RnJn+5N8PswkMyQZzMXJonS6rZI3DzilX1EZ+z+nCa4t2fuOU3Jzt1ayt0lJi/fhErTG62eXa0
MMZiqE4oZlG3hJpvqPg+05UDvNbIc6denfxC1HH/htF1TnHFrvf4+YRF6gMs7B1Kv0vH9wO8EuVr
J3n9a82ZVVQ2bsHg+RhWbO6Y7L9Q41HaGLv7Gv8RYAA5OVH0igpFJAAAAABJRU5ErkJggg==
--20cf300fab43f80d9304bc0103ed
Content-Type: image/png; name="resize.png"
Content-Disposition: attachment; filename="resize.png"
Content-Transfer-Encoding: base64
X-Attachment-Id: f_h047klaa1

iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJ
bWFnZVJlYWR5ccllPAAAAddJREFUeNpi/P//PwMlgImBQsACYzjOfzUTSBkjSwJdlw6kzqJrunPx
IsO/f/8Ynk32QBjw588f41hvKePbD35+UVVg59l2+M2td59/Y9j4/P597C74/fMnw+XrX75IiHDy
bFhxguEdq9ia379+nf314wfDz+/fGX79+A6kfzAws7BgDwOQAZqq3DxHdp9iMLIyYOBmZwoBeqGA
6EAE2bRs/c1bT39xtR04+eCWgaqIGhcrYyYhQ+Du+fvnT/q7D19ATjz7+s2H14dO/si01JdVO3Hx
UeZPSFRPIBSNZ2EhDrR1wpu376cfOnnrlrGGuBo3qkuMkWMLIx18vX8GFoUTXr35MH3/iZu39HTl
1DjYWUCGtHJzsy8Dunbmf2A0ggAjLCUyMjLCDeGUN2TgM49lYBRRZ/j940cBNz9vpratvtqlo5dv
BYeYqy2ZtRPkUpO384IZWLD56/vD82DMJqXLwKodMOHHd3XRU/vPhci52qitu/Dmyy9gjBGVlH89
u8zw48lF4z9CQiFmka5qN59//KKrL8sDivJvu5sxvADyAzMQs0IxGxCzA71hyGhZ2IBi8tvbN/8d
660A6n2MbgDMECYozYLGZ4KqAYFvQL0fGSnNzgABBgBbsuMDQbb6rAAAAABJRU5ErkJggg==
--20cf300fab43f80d9304bc0103ed--

Attachment.IsAttachment should use string.StartsWith instead of ==

current impl:

public bool IsAttachment
{
  get
  {
    return this.ContentDisposition == "attachment" || this.ContentDisposition == "inline";
  }
}

should be:

public bool IsAttachment
{
  get
  {
    return this.ContentDisposition.StartsWith("attachment") || this.ContentDisposition.StartsWith("inline");
  }
}

\r\n\r\n in Body property

I recived a message containing a \r\n\r\n body..
The deprecated BodyHtml shown the correct message.. i suppose that a trim() i the Load methos should fix the problem:
so change the
Line 117 in MailMessage.cs from
if (string.IsNullOrEmpty(Body) && Attachments != null && Attachments.Count > 0) {
to
if (string.IsNullOrEmpty(Body.Trim()) && Attachments != null && Attachments.Count > 0) {

Timeout connect enhacement timeout

Hi,
I've succesfully tested an enhancement in Connect method.
I had an issue with slow responding IMAP server during auth process so I added timeout parameters in connect method before invocation of AuthenticateAsClient method.
Please consider include some solution in a code. Best regards!

example:

sslStream.ReadTimeout = sslStream.WriteTimeout=connectionTimout;
sslStream.AuthenticateAsClient(hostname);

Wrong body length ruins getResponse();

Hi,

There is a mail in my mailbox that causes the getMessage(i,true); method to just stop.
After digging into it, it appears that the last lines of the stream are :

)
then

`````` xm0and finally76 OK Success```

whereas the last two lines expected are :
)
and then
xm076 OK Success

Since the code just tests if the last line contains
xm076 OK Success
by doing

          break; ```
when the last line is ```76 OK Success``` the code just rolls back to GetResponse() wich causes the readLine() method to just sit there waiting for an imaginary end of the stream. (Eventually it will return null after a very long timeout)

I'm guessing that the the body length answered by the server is too much by one charachter.
Here's the size response :
     ```* 73 FETCH (UID 106 RFC822.SIZE 1765 FLAGS (\Seen) BODY[HEADER] {1372}```

If that is, I would suggest something like this :

public MailMessage[] GetMessages(string start, string end, bool uid, bool headersonly, bool setseen)
{
CheckMailboxSelected();
IdlePause();

        string UID, HEADERS, SETSEEN;
        UID = HEADERS = SETSEEN = String.Empty;
        if (uid)
            UID = "UID ";
        if (headersonly)
            HEADERS = "HEADER";
        if (!setseen)
            SETSEEN = ".PEEK";
        string tag = GetTag();
        string command = tag + UID + "FETCH " + start + ":" + end + " (UID RFC822.SIZE FLAGS BODY" + SETSEEN + "[" + HEADERS + "])";
        string response;


        string endOfStreamTmp = String.Empty;
        string endOfStreamTag = tag + "OK Success";

        var x = new List<MailMessage>();
        SendCommand(command);
        while (true)
        {
            response = GetResponse();
            // 3) We apend the latest response to the potential beginning
            // if no potential beginning was found in 2) or if this is the first time the code gets here
            // then endOfStreamTmp is empty which means we are just testing the latest response
            endOfStreamTmp += response;
            if (endOfStreamTmp.Contains(endOfStreamTag))
            {
                break;
            }
            endOfStreamTmp = String.Empty;
            var m = rxGetBodyLength.Match(response);
            if (!m.Success)
                continue;
            int length = m.Groups[1].Value.ToInt();
            var mail = new MailMessage();
            var body = new StringBuilder();
            var buffer = new char[8192];
            int read;

            string bodyStr = string.Empty;

            while (length > 0)
            {
                read = _Reader.Read(buffer, 0, Math.Min(length, buffer.Length));
                body.Append(buffer, 0, read);
                length -= read;
            }
            bodyStr = body.ToString();

            // 1) We are going to check if the body doesn't end with the beginning of the endOfStreamTag
            bool tagSubStrNotFound = true;
            for (int i = 1; i <= endOfStreamTag.Length && tagSubStrNotFound; i++)
            {
                if (bodyStr.EndsWith(endOfStreamTag.Substring(0, i)))
                {
                    // 2) if it does, we store the matching end wich is potentially the beginning of the endOfStreamTag
                    endOfStreamTmp = bodyStr.Substring(bodyStr.Length - 1 - i);
                    tagSubStrNotFound = false;
                }
            }
            mail.Load(bodyStr, headersonly);
            var m2 = rxUID.Match(response);
            if (m2.Groups[1] != null)
                mail.Uid = m2.Groups[1].ToString();
            m2 = rxFlags.Match(response);
            if (m2.Groups[1] != null)
                mail.SetFlags(m2.Groups[1].ToString());
            m2 = rxSize.Match(response);
            if (m2.Groups[1] != null)
                mail.Size = Convert.ToInt32(m2.Groups[1].ToString());

            x.Add(mail);
        }

        IdleResume();
        return x.ToArray();
    }

What solves the problem but does not remove the extra chars from the body ( ```xm0```)

Race condition in TextClient.Disconnect

I've discovered a race condition in TextClient.Disconnect and TextClient.SendCommand that is happening about once a day (program runs 24/7). Turns out the idle code (or something) must be calling the SendCommand function while disconnect is disposing of the SSL stream, resulting in a ThreadException being raised when it attempts to write to the stream.
I'm not really sure of the best way to handle this so I've just attempted to hack around it for now by catching an ObjectDisposedException and carrying on like nothing happened. Here are the exception details

Cannot access a disposed object.
Object name: 'SslStream'.
   at System.Net.Security.SslState.CheckThrow(Boolean authSucessCheck)
   at System.Net.Security.SslState.get_SecureStream()
   at System.Net.Security.SslStream.Write(Byte[] buffer, Int32 offset, Int32 count)
   at AE.Net.Mail.TextClient.SendCommand(String command) in D:\Documents\CODE\aenetmail\TextClient.cs:line 98
   at AE.Net.Mail.ImapClient.OnLogout() in D:\Documents\CODE\aenetmail\ImapClient.cs:line 481
   at AE.Net.Mail.TextClient.Logout() in D:\Documents\CODE\aenetmail\TextClient.cs:line 43
   at AE.Net.Mail.TextClient.Disconnect() in D:\Documents\CODE\aenetmail\TextClient.cs:line 119
   at AE.Net.Mail.TextClient.Dispose() in D:\Documents\CODE\aenetmail\TextClient.cs:line 134

Messages aren't getting returned in PowerShell

I'm trying to use this library in PowerShell, and I'm having a really hard time getting any messages returned. Here's the code I'm using:

        $SearchConditionClass = [AE.Net.Mail.SearchCondition];
        $SearchCondition = $SearchConditionClass::Undeleted();
        $ImapClient = New-Object -TypeName AE.Net.Mail.ImapClient -ArgumentList $ImapServer, $UserName, $Password;
        $Messages = $ImapClient.SearchMessages($SearchCondition);

In the $Messages variable, I'm getting the Lazy objects returned, but the "Value" property is null. Therefore, I can't view any of the message details.

Cheers,
Trevor Sullivan
http://trevorsullivan.net

Regexp in LIST command does not work properly

Hi,

first I would like to say a big thank you for this implementation of IMAP client.
I've encountered a problem using "ImapClient.ListMailboxes(reference, pattern)"

I had no returning mailboxes from iCloud but Gmail does the job.
The difference of LIST response of them was the missing double-quotation marks
at iCloud.

Gmail-Response:

  • LIST (\HasNoChildren) "/" "Drafts"

iCloud-Respone:

  • LIST (\NoInferiors) "/" INBOX

The problem was at the regular expression in the ListMailboxes() method. If I changed it from:

  • LIST (([^)]*)) "([^\"]+)" "([^\"]+)"

to:

  • LIST (([^)]*)) "([^\"]+)" "?([^\"]+)"?

I also get the list of mailbox from iCloud.

best regards

_Responses.Take(); gets stuck when using a backgroundworker

Hi,

I was downloading emails from a backgroundWorker to keep the UI responsive and it was working fine when the textclient class was using a streamreader but ever since it is a thread that is reading the response nothing is received from the server.

I have checked that the exact same code works fine outside from the worker so I'm guessing that it's a thread-related issue but since I am no expert I ask your help...

A quick test shows that the Connect method in TextClient gets stuck on the line
string info = _Responses.Take();

Any ideas and/or solutions ?

DecodeQuotedPrintable throws StackOverFlow

Hi,

There's a msg in my mailbox that causes the line
int ascii = int.Parse(match.Value.Replace("=",string.Empty), System.Globalization.NumberStyles.HexNumber);
in the decodeQuotedPrintable method to throw a StackOverFlow Exception claiming that the value was to big or to small to be an integer.

The previous
int ascii = int.Parse(match.Value.Substring(1), System.Globalization.NumberStyles.HexNumber);
works fine on the same message.

I don't know what would help you to find out what's wrong so just tell me...

Issue deleting Gmail messages

When I use

imap.DeleteMessage(message);

the message gets labeled as "Trash" but is still also labelled "Inbox" as well, so is not really deleted.

When I use

imap.MoveMessage(message.Uid, "[Gmail]/Trash");

I get an exception of "1 EXPUNGE" thrown by method CheckResultOK

I am using commit d2062b5 (2011/11/28)

AOL imap mail check throw error message

In ImapClient.cs the following line throw a long error message but I only noticed this when downloading messages from imap.aol.com:

System.Diagnostics.Debug.Assert(next == ')');

If the line above is commented out, then error message disappears :).

Unable to validate Login/Connection independently

When a ImapClient or Pop3Client client instance is created, it connects and logs in in the constructor. There is no alternate constructor that allows only creating the instance first and then use the public methods Login and Connect later.

What is the rational behind imposing connection and login in constructor when we can switch both server and user later on?

One of the incurred issue is that the connection to server and the user login/pwd cannot be tested independently.

Saving UTF16 text/xml attachments with BOM has encoding issues

The ObjectWHeaders.SetBody method re-encodes any attachment content type that starts with "text/" into UTF8. When I receive a base64 UTF16 test/xml document that contains an initial UTF16 byte order mark (BOM), the re-encoding to UTF8 places garbage at the begining of the data when I save the attachment to a file.

Underscores in encoded Subject header

Hi,

Encoded Subject header uses _ in some clients to encode spaces. This case is not handled properly. Examples:

Case1

Subject: =?iso-8859-1?Q?testing_encoding_h=E9?=
Got: testing_encoding_hé
Expected: testing encoding hé

Case2

Subject: coucou =?ISO-8859-1?Q?=E0_tous?=
Got: coucou à_tous
Expected: coucou à tous

Thanks

Secure sockets implementation

Hi Andy, just curious... did you consider using System.Net.Security.SslStream instead of the Mentalis lib? (It was added in .NET 2.0 - I think the Mentalis library was authored around .NET 1.0 or 1.1...)

Thanks,

Omri.

From is null or has character set issues

Hi

First of all, thanks for sharing this.

I have found two issues with the From object as follows:

If from header ahs no display name (is in the form [email protected], the messages From object is NULL. I get around this with the following piece of code:

name = "";
addr = "";
if (msg.Value.From != null)
{
name = msg.Value.From.DisplayName;
addr = msg.Value.From.Address;
}
else
{
string[] tok = msg.Value.Headers["From"].RawValue.Split(new string[] { "<", ">" }, StringSplitOptions.RemoveEmptyEntries);
addr = tok[0];
if (tok.Length == 2)
name = tok[1];
}
if (name.CompareTo(string.Empty) == 0)
{
string[] tokens = addr.Split('@');
name = tokens[0].Replace('.', ' ').Replace('-', ' ').Replace('_', ' ');
}

this workd well so far

Another issue i have found is the character set. I didn't even know the was possible but apparently some mail boxes do allow accented characters in mail addresses - wich causes issues on your library since the address Taduçõ[email protected] comes back as Tradu??[email protected].

You library doesn't handle well special characters in the address.

regards
Luís Rodrigues

Encoding problem

I found another problem with encoding. Gmail webclient displays message correctly, but your dll has problem with polish characters. Email is encoded (says so in header) in utf8. Here is example:

Poinformujemy Ci� e-mailem, kiedy Kupuj�cy wybierze

should be:
Poinformujemy Cię e-mailem, kiedy Kupują�cy wybierze

The remote certificate is invalid according to the validation procedure.

Hey andy,
I'm trying to use your library with a imap and pop server to get mail.
I'm getting this exception "Authentication Exception was unhandled by user code: The remote certificate is invalid according to the validation procedure."
What can I do to skip this validation procedure?

Thanks much for your work,
Florian

Downloading messages is very ineffecient

The current code for downloading IMAP messages is very inefficient: it leads to a lot of string copying, which is hurting me for large messages (with attachments).

I've refactored the code to use the StringBuilder and it's quite a lot faster now for me:

New code:

    var body = new StringBuilder();
    while (bodyremaininglen > 0) {
      var line = GetResponse();

      if (bodyremaininglen < line.Length) {
        body.Append(line, 0, bodyremaininglen);
        bodyremaininglen = 0;
      } else {
        body.Append(line).Append(Environment.NewLine);
        bodyremaininglen -= line.Length + 2;  //extra 2 for CRLF
      }
    }

Original code:

    string body = String.Empty;
    while (bodyremaininglen > 0) {
      bodies += GetResponse();
      if (bodyremaininglen < bodies.Length) {
        body += bodies.Substring(0, bodyremaininglen);
        bodyremaininglen = 0;
        bodies = bodies.Remove(0);
      } else {
        body += bodies + Environment.NewLine;
        bodyremaininglen -= bodies.Length + 2;  //extra 2 for CRLF
        bodies = "";
      }
    }

When network was reconnected imap.NewMessage += not works

Some time we may go out of network and reconnected, while that time

imap.NewMessage += (sender, e) => {
var msg = imap.GetMessage(e.MessageCount - 1);
}

this function will not work,
Connection is not providing any exception to the user.
If their is any event to rise while exception and reconnect function. it will be more useful to all.

Best Regards
Balaji Manoharan

Truncated attachments?

I have a very simple bit of code that reads mail from Gmail via the Imap client.

Both text and binary attachments are being truncated, I have tried a ton of different ways of prodding the api, all my attachments come through with correct mime types and file names but are truncated at about ~300 Bytes?

I Stepped ImapClient.GetMessages()

Seems that attachments are truncated coming out of there? so without totally tearing everything down. Does anyone have any ideas? Is there something special I need to do to ensure attachments get fully downloaded?

Regards,
Stonie.

NewMessage event being raised when no new messages are present

Since the 1.5.3 update, I'm now receiving a NewMessage event from the ImapClient while idling, even though there are no new messages. I'm receiving this almost exactly 5 minutes after being connected, could this have anything to do with the new automatic idle support?

Error: Cannot read when another read is pending

Andy,

I am trying to use IDLE, but I receive an error in two scenarios: in the NewMessage delegate, and when calling .noop().
Can you help?

Error:
"The Read method cannot be called when another read operation is pending."

Call-stack:
at System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.StreamReader.ReadBuffer()
at System.IO.StreamReader.ReadLine()
at AE.Net.Mail.TextClient.GetResponse() in C:...\AE.Net.Mail\TextClient.cs:line 87
at AE.Net.Mail.TextClient.SendCommandGetResponse(String command) in C:...\AE.Net.Mail\TextClient.cs:line 83
at AE.Net.Mail.ImapClient.IdlePause() in C:...\AE.Net.Mail\ImapClient.cs:line 84
at AE.Net.Mail.ImapClient.GetMessages(String start, String end, Boolean uid, Boolean headersonly, Boolean setseen) in C:...\AE.Net.Mail\ImapClient.cs:line 324
at AE.Net.Mail.ImapClient.GetMessages(Int32 startIndex, Int32 endIndex, Boolean headersonly, Boolean setseen) in C:...\AE.Net.Mail\ImapClient.cs:line 319
at AE.Net.Mail.ImapClient.GetMessage(Int32 index, Boolean headersonly, Boolean setseen) in C:...\AE.Net.Mail\ImapClient.cs:line 307
at AE.Net.Mail.ImapClient.GetMessage(Int32 index, Boolean headersonly) in C:...\AE.Net.Mail\ImapClient.cs:line 303
at MailTester.Program.<>c__DisplayClass2.

b__0(Object sender, MessageEventArgs e) in C:...\MailTester\Program.cs:line 35

Here is the code:

using (var imap = new ImapClient("imap.gmail.com", un, pw, ImapClient.AuthMethods.Login, 993, true))    {
var msgs = imap.SearchMessages(
  SearchCondition.Undeleted().And(
    SearchCondition.SentSince(new DateTime(2011, 10, 10))));
System.Diagnostics.Debug.WriteLine("msgs: " + msgs.Length.ToString());

imap.NewMessage += (sender, e) =>             {
    var msg = imap.GetMessage(e.MessageCount - 1);        //throws exception
    System.Diagnostics.Debug.WriteLine(DateTime.Now.ToShortTimeString() + ": " + msg.Subject);
};

System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent(false);
while (!mre.WaitOne(TimeSpan.FromMinutes(20)))             {
    imap.Noop();        //throws exception
}

}

ImapClient.GetMessage(uid) returning "out of bounds"

When calling the ImapClient.GetMessage() method, and passing it a valid UID, such as [int] or [string] "5", I constantly get a "Index was outside the bounds of the array" message. I haven't been able to find any call to GetMessage() that works to get a specific UID.

I am not sure if this is related to my other issue, where I'm getting null messages when calling SearchMessages() ...

Cheers,
Trevor Sullivan
http://trevorsullivan.net

Flags add vs replace

The store method of the ImapClient looks like it will replace flags when it is supposed to add and add when it is supposed to replace.

There is a ternary expression in the code as follows: replace ? "+" : ""

Yet the plus sign is intended for adding flags, whereas no sign is intended for replacing flags.

From the RFC:

FLAGS
Replace the flags for the message (other than \Recent) with the
argument. The new value of the flags is returned as if a FETCH
of those flags was done.

  FLAGS.SILENT <flag list>
     Equivalent to FLAGS, but without returning a new value.

  +FLAGS <flag list>
     Add the argument to the flags for the message.  The new value
     of the flags is returned as if a FETCH of those flags was done.

  +FLAGS.SILENT <flag list>
     Equivalent to +FLAGS, but without returning a new value.

  -FLAGS <flag list>
     Remove the argument from the flags for the message.  The new
     value of the flags is returned as if a FETCH of those flags was
     done.

  -FLAGS.SILENT <flag list>
     Equivalent to -FLAGS, but without returning a new value.

UTF-8 decoding in message body

Hi Andy,

I'm using your lib to parse messages written in French. I noticed that some emails encoded with UTF-8 are not correctly decoded.

During debugging, I found the problem to be in the Utilities class.

If you look at DecodeQuotedPrintable method, it gathers the regex matches for each group of two characters following the equals sign. In case of a UTF-8 encoding, this will produce a series of two unknown characters.

For example, the character "é" is encoded as =C3=A9 and both groups should be used during decoding a single character.

I think this should be easy fixable by accumulating the groups of characters with a slightly modified regex that looks like this:
var matches = Regex.Matches(value, @"(=[0-9A-F]{2})+");

And then you need to replace the equals inside with an empty string and the job's done.

I hope my example was clear enough.

Thanks,
Horia

Load method not loading uid ?

Hello,

When i save the raw text of a downloaded email and then later try to load it, everything's fine except that the uid is nothing.
After giving a quick look at the source code I believe that the load method of a MailMessage forgets to load its uid.

References field in the MailMessage class

Actually this is not an issue, but more of a nice to have feature since it will help chaining the replies.

It may look like this:

public MailAddress[] References { get; private set; }

and be populated in the Load method:

References = Headers.GetAddresses("References");

Thanks

In-Reply-To and References headers.

Hi,

Do you plan to add InReplyTo and References properties to ease access to In-Reply-To and References headers?

The In-Reply-To header was originally defined by RFC 822, the 1982 standard for mail messages. In 2001, its definition was tightened up by RFC 2822. The References header was defined by RFC 822 in 1982.
source

spaces and double quotes in password

If password contains a space, the login command sends too many arguments.

The answer is to put quotes around the password, and to handle quotes in the password use backslash to escape, and to handle backslash use double backslash. Per RFC 3501 section 9 Formal Syntax.

I recommend altering the login command found in internal override void OnLogin using the following line of code:

command = string.Format("{0}LOGIN {1} "{2}"", tag, login.Replace("", "\").Replace(""", "\""), password);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.