Programming | Blog | Limilabs https://www.limilabs.com/blog Using Limilabs .net components Mon, 16 Sep 2024 15:21:08 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 How to log System.Net https://www.limilabs.com/blog/how-to-log-system-net Mon, 02 Jan 2017 22:21:39 +0000 https://www.limilabs.com/blog/?p=5248 In your App.config add the following code: That’s it! The log looks like this: System.Net Information: 0 : [8548] SecureChannel#238379 System.Net Information: 0 : [8548] Enumerating security System.Net Information: 0 : [8548] Negotiate System.Net Information: 0 : [8548] NegoExtender System.Net Information: 0 : [8548] pku2u System.Net Information: 0 : [8548] WDigest System.Net Information: 0 : […]

The post How to log System.Net first appeared on Blog | Limilabs.

]]>
In your App.config add the following code:

<?xml version="1.0"?>
<configuration>
  <system.diagnostics>

    <trace autoflush="true"/>

    <switches>
      <add name="System.Net" value="Verbose" />
    </switches>

    <sources>
      
      <source name="System.Net">
        <listeners>
          <add name="SystemNetLogFile"/>
        </listeners>
      </source>
      
    </sources>

    <sharedListeners>
      <add name="SystemNetLogFile" type="System.Diagnostics.TextWriterTraceListener" initializeData="d:\system.net.log"/>
    </sharedListeners>

  </system.diagnostics>
</configuration>

That’s it!

The log looks like this:

System.Net Information: 0 : [8548] SecureChannel#238379
System.Net Information: 0 : [8548] Enumerating security
System.Net Information: 0 : [8548] Negotiate
System.Net Information: 0 : [8548] NegoExtender
System.Net Information: 0 : [8548] pku2u
System.Net Information: 0 : [8548] WDigest
System.Net Information: 0 : [8548] Kerberos
System.Net Information: 0 : [8548] NTLM
System.Net Information: 0 : [8548] Schannel
System.Net Information: 0 : [8548] Microsoft Unifie
System.Net Information: 0 : [8548] TSSSP
System.Net Information: 0 : [8548] CREDSSP
System.Net Information: 0 : [8548] SecureChannel#238379
System.Net Information: 0 : [8548] Current OS installat
System.Net Information: 0 : [8548] AcquireCredentialsHa
System.Net Error: 0 : [8548] AcquireCredentialsHandle()
System.Net Information: 0 : [8548] AcquireCredentialsHa
System.Net Error: 0 : [8548] AcquireCredentialsHandle()
System.Net Information: 0 : [8548] SecureChannel#214541
System.Net Information: 0 : [8548] SecureChannel#214541
System.Net Information: 0 : [8548] AcquireCredentialsHa
System.Net Information: 0 : [8548] InitializeSecurityCo
System.Net Information: 0 : [8548] InitializeSecurityCo
System.Net Information: 0 : [8548] InitializeSecurityCo
System.Net Information: 0 : [8548] InitializeSecurityCo
System.Net Information: 0 : [8548] InitializeSecurityCo
System.Net Information: 0 : [8548] InitializeSecurityCo
System.Net Information: 0 : [8548] InitializeSecurityCo
System.Net Information: 0 : [8548] InitializeSecurityCo
System.Net Information: 0 : [8548] InitializeSecurityCo
System.Net Information: 0 : [8548] InitializeSecurityCo
System.Net Information: 0 : [8548] InitializeSecurityCo
System.Net Information: 0 : [8548] InitializeSecurityCo
System.Net Information: 0 : [8548] Remote certificate:
V3

[Subject]
CN=mail.postecert.it, O=Postecom S.p.A., L=Roma, S=Ro
Simple Name: mail.postecert.it
DNS Name: mail.postecert.it

[Issuer]
CN=GlobalSign Organization Validation CA - SHA256 - G
Simple Name: GlobalSign Organization Validation CA -
DNS Name: GlobalSign Organization Validation CA - SHA

[Serial Number]
0A9141CFE287B47FF4273C12

[Not Before]
2016-11-02 08:01:04

[Not After]
2017-11-03 08:01:04

[Thumbprint]
F12F74096659D9CCAA4ACD3432C896AF39CA8B9E

[Signature Algorithm]
sha256RSA(1.2.840.113549.1.1.11)

[Public Key]
Algorithm: RSA
Length: 2048
Key Blob: 30 82 01 0a 02 82 01 01 00 bf a1 62 b7 64 1
System.Net Information: 0 : [8548] SecureChannel#214541
System.Net Information: 0 : [8548] ProcessAuthenticatio

The post How to log System.Net first appeared on Blog | Limilabs.

]]>
Enable IMAP in Gmail https://www.limilabs.com/blog/enable-imap-in-gmail Tue, 02 Jun 2015 10:26:31 +0000 http://www.limilabs.com/blog/?p=2224 When it comes to managing emails efficiently, having the right tools can make all the difference. Mail.dll is a helpful email library that can simplify email tasks for developers and businesses. To make the most of Mail.dll’s capabilities, it’s essential to enable IMAP (Internet Message Access Protocol) in Gmail. Don’t worry; it’s not as complicated […]

The post Enable IMAP in Gmail first appeared on Blog | Limilabs.

]]>
When it comes to managing emails efficiently, having the right tools can make all the difference.

Mail.dll is a helpful email library that can simplify email tasks for developers and businesses.

To make the most of Mail.dll’s capabilities, it’s essential to enable IMAP (Internet Message Access Protocol) in Gmail. Don’t worry; it’s not as complicated as it sounds!

In this article, we’ll guide you through the simple steps of enabling IMAP in Gmail, allowing you to seamlessly connect Mail.dll to your Gmail account. By doing so, you’ll unlock a world of convenient email management and boost your productivity.

Let’s explore how you can enable IMAP in Gmail and unleash the full potential of Mail.dll!

5 easy steps to enable IMAP

  • Sign in to Gmail.
  • Click the gear icon in the upper-right and select Settings.
  • Click Forwarding and POP/IMAP.
  • Select Enable IMAP.
  • Remember that Gmail only allows secure TLS/SSL connections so you need to use ConnectSSL method.

Application specific passwords

An application specific password is a 16-digit password that gives an application permission to access your Google Account. Application passwords are the easiest way to log-in to your Gmail account using POP3 or IMAP.

2-Step-Verification must be enabled on your account to access this feature (you’ll get the ‘setting you are looking for is not available for your account’ error otherwise):

Once you have the password use it as a regular password for POP3, SMTP or IMAP clients: using app passwords with Gmail

OAuth 2.0

Another approach would be to use one of the OAuth 2.0 flows:

  1. OAuth 2.0 for installed applications
  2. OAuth 2.0 for web applications
  3. OAuth 2.0 for service accounts

Less secure apps (deprecated)

On May 30, 2022, this setting will no longer be available.

Less secure apps (those that use primary password to access) are no longer supported by Gmail, except for some corporate accounts. You can find this setting here: enable access for ‘less’ secure apps 

Please note that contrary to what the label says those applications are secure – they use TLS to secure the communication. The term ‘less secure apps’ is used only because such applications need to be provided with account’s primary password to be able to access IMAP.

2-step verification

If you use 2-Step-Verification and are seeing a “password incorrect” error when trying to access IMAP, POP3, SMTP, an app password (or OAuth 2.0 access) will solve the problem. 

Simple .NET IMAP access sample

Discover the power of simple .NET IMAP access with Mail.dll’s user-friendly and efficient. This comprehensive and straightforward sample allows developers to effortlessly interact with IMAP servers in their .NET applications.

With Mail.dll’s intuitive API design, handling email tasks, such as parsing, composing, and managing folders, becomes a breeze. Whether you’re a seasoned developer or a newcomer to email integration, Mail.dll provides an excellent starting point for leveraging IMAP capabilities in your .NET projects. Say goodbye to complex implementations and embrace the ease and effectiveness of Mail.dll’s Simple .NET IMAP access sample.

// C# code:
 
using(Imap imap = new Imap())
{
    imap.ConnectSSL("imap.gmail.com");
    imap.UseBestLogin("pat@gmail.com", "app-password");
 
    imap.SelectInbox();
 
    List<long> uids = imap.Search(Flag.Unseen);
    foreach (long uid in uids)
    {
        var eml = imap.GetMessageByUID(uid);
        IMail mail = new MailBuilder().CreateFromEml(eml);
 
        string subject = mail.Subject;
        string plainText = mail.Text;
    }
    imap.Close();
}
' VB.NET code:
 
Using imap As New Imap()
    imap.ConnectSSL("imap.gmail.com")
    imap.UseBestLogin("pat@gmail.com", "app-password")
 
    imap.SelectInbox()
 
    Dim uids As List(Of Long) = imap.Search(Flag.Unseen)
    For Each uid As Long In uids
        Dim eml = imap.GetMessageByUID(uid)
        Dim mail As IMail = New MailBuilder().CreateFromEml(eml)
 
        Dim subject As String = mail.Subject
        Dim plainText As String = mail.Text
    Next
    imap.Close()
End Using

You can find more .NET IMAP samples.

You can download Mail.dll IMAP library for .NET here.

The post Enable IMAP in Gmail first appeared on Blog | Limilabs.

]]>
Enable POP3 in Gmail https://www.limilabs.com/blog/enable-pop3-in-gmail https://www.limilabs.com/blog/enable-pop3-in-gmail#comments Tue, 02 Jun 2015 10:00:17 +0000 http://www.limilabs.com/blog/?p=2231 Sign in to Gmail. Click the gear icon in the upper-right and select Settings. Click Forwarding and POP/IMAP. Select Enable POP for all mail or Enable POP for mail that arrives from now on. Here you can learn more about Gmail’s POP3 behavior Remember that Gmail only allows secure TLS/SSL connections so you need to […]

The post Enable POP3 in Gmail first appeared on Blog | Limilabs.

]]>
  • Sign in to Gmail.
  • Click the gear icon in the upper-right and select Settings.
  • Click Forwarding and POP/IMAP.
  • Select Enable POP for all mail or Enable POP for mail that arrives from now on. Here you can learn more about Gmail’s POP3 behavior
  • Remember that Gmail only allows secure TLS/SSL connections so you need to use ConnectSSL method.
  • Application specific password

    An application specific password is a 16-digit password that gives an application permission to access your Google Account. Application passwords are the easiest way to log-in to your Gmail account using POP3 or IMAP.

    2-Step-Verification must be enabled on your account to access this feature (you’ll get the ‘setting you are looking for is not available for your account’ error otherwise):

    Once you have the password use it as a regular password for POP3, SMTP or IMAP clients.

    OAuth 2.0

    Another approach would be to use one of the OAuth 2.0 flows:

    1. OAuth 2.0 for installed applications
    2. OAuth 2.0 for web applications
    3. OAuth 2.0 for service accounts

    Less secure apps (deprecated)

    Less secure apps (those that use primary password to access) are no longer supported by Gmail, except some corporate accounts. You can find this here: enable access for ‘less’ secure apps 

    Please note that contrary to what the label says those applications are secure – they use TLS to secure the communication. The term ‘less secure apps’ is used only because such applications need to be provided with account’s primary password to be able to access IMAP.

    2-step verification

    If you use 2-Step-Verification and are seeing a “password incorrect” error when trying to access POP3, IMAP, SMTP, an app password (or OAuth 2.0 access) will solve the problem. 

    Simple .NET POP3 access sample

    // C# code:
     
    using(Pop3 pop3 = new Pop3())
    {
        pop3.ConnectSSL("pop.gmail.com");
        pop3.Login("your_email@gmail.com", "app-password");
     
        foreach (string uid in pop3.GetAll())
        {
            var eml = pop3.GetMessageByUID(uid);
            IMail mail= new MailBuilder()
                .CreateFromEml(eml);
     
            Console.WriteLine(mail.Subject);
            Console.WriteLine(mail.Text);
        }
        pop3.Close();
    }
    
    ' VB.NET code:
     
    Using pop3 As New Pop3()
        pop3.ConnectSSL("pop.gmail.com")
        pop3.Login("your_email@gmail.com", "app-password")
     
        For Each uid As String In pop3.GetAll()
            Dim email As IMail = New MailBuilder() _
                .CreateFromEml(pop3.GetMessageByUID(uid))
            Console.WriteLine(email.Subject)
        Console.WriteLine(mail.Text)
        Next
        pop3.Close()
    End Using
    
    

    More .NET POP3 client samples. You can download Mail.dll IMAP library for .NET here.

    The post Enable POP3 in Gmail first appeared on Blog | Limilabs.

    ]]>
    https://www.limilabs.com/blog/enable-pop3-in-gmail/feed 2
    IMAP search requires parentheses https://www.limilabs.com/blog/imap-search-requires-parentheses Fri, 06 Jun 2014 06:58:42 +0000 http://www.limilabs.com/blog/?p=4621 IMAP protocol uses Polish notation (also known as prefix notation) for client queries. In general it means, that operator (in case of IMAP search it’s always a logical operator) is placed left of its operands. Polish notation Expression that would be written in conventional infix notation as: (5 − 6) * 7 can be written […]

    The post IMAP search requires parentheses first appeared on Blog | Limilabs.

    ]]>
    IMAP protocol uses Polish notation (also known as prefix notation) for client queries. In general it means, that operator (in case of IMAP search it’s always a logical operator) is placed left of its operands.

    Polish notation

    Expression that would be written in conventional infix notation as:
    (5 − 6) * 7
    can be written in prefix/Polish notation as:
    * (− 5 6) 7
    As all mathematical operands are binary (or have defined number of operands) we don’t need parentheses to correctly evaluate this expression:
    * − 5 6 7

    Polish notation doesn’t require parentheses.

    IMAP search needs parentheses

    Although IMAP search syntax uses Polish notation it actually requires parentheses to be evaluated unambiguously.

    This is because there is no explicitly defined AND operator, that takes exactly 2 operands.

    RFC 3501:

    When multiple keys are specified, the result is the intersection (AND function) of all the messages that match those keys.

    So although it is true that Polish and reverse Polish notations don’t require parentheses, it is not true that IMAP search doesn’t require them.

    ‘OR/AND’ example

    Expression 1a:

    Regular notation:
    (SUBJECT subject OR BODY body) AND FROM from

    Polish notation:
    AND OR SUBJECT subject BODY body FROM from

    IMAP’s Polish notation (note there is no AND operator):
    OR SUBJECT subject BODY body FROM from

    Expression 1b:

    Regular notation:
    SUBJECT subject OR (BODY body AND FROM from)

    Polish notation:
    OR SUBJECT subject AND BODY body FROM from

    IMAP’s Polish notation (note there is no AND operator):
    OR SUBJECT subject BODY body FROM from

    1a != 1b

    Expression 1a is not equal to Expression 1b:
    ((a or b) and c) != (a or (b and c))

    For:
    a = true
    b = true
    c = false

    We have:
    ((true or true) and false) != (true or (true and false))
    false != true

    Parentheses are needed

    But when there is no AND operator, IMAP’s Polish notations look exactly the same, thus we need parentheses!

    Expression 1a (IMAP’s Polish notation with parentheses):
    (OR SUBJECT subject BODY body) FROM from

    Expression 1b (IMAP’s Polish notation with parentheses):
    OR SUBJECT subject (BODY body FROM from)

    OR SUBJECT subject BODY body FROM from
    is treated like
    (OR SUBJECT subject BODY body) FROM from

    ‘NOT’ example

    Expression 2a:

    Regular notation:
    NOT (SUBJECT subject AND BODY body)

    Polish notation:
    NOT AND SUBJECT subject BODY body

    IMAP’s Polish notation (note there is no AND operator):
    NOT SUBJECT subject BODY body

    Expression 2b:

    Regular notation:
    (NOT SUBJECT subject) AND BODY body

    Polish notation:
    AND NOT SUBJECT subject BODY body

    IMAP’s Polish notation (note there is no AND operator):
    NOT SUBJECT subject BODY body

    2a != 2b

    Expression 2a is obviously not equal to Expression 2b.

    Parentheses are needed

    Again IMAP’s Polish notations look the same. We need parentheses!

    Expression 2a (IMAP’s Polish notation with parentheses):
    NOT (SUBJECT subject BODY body)

    Expression 2b (IMAP’s Polish notation with parentheses):
    (NOT SUBJECT subject) BODY body

    NOT SUBJECT subject BODY body
    is treated like
    (NOT SUBJECT subject) BODY body

    The post IMAP search requires parentheses first appeared on Blog | Limilabs.

    ]]>
    EnvelopedCms decrypt problem https://www.limilabs.com/blog/envelopedcms-decrypt-problem Mon, 03 Feb 2014 09:39:29 +0000 http://www.limilabs.com/blog/?p=4423 .NET’s EnvelopedCms class represents a CMS/PKCS #7 structure for enveloped data. Such data are for example used in S/MIME encrypted messages. EnvelopedCms class contains several Decrypt method overloads: Decrypt() Decrypt(RecipientInfo) Decrypt(X509Certificate2Collection) Decrypt(RecipientInfo, X509Certificate2Collection) Each Decrypt method decrypts the contents of the decoded enveloped CMS/PKCS #7 data. Each searches the current user and local machine My […]

    The post EnvelopedCms decrypt problem first appeared on Blog | Limilabs.

    ]]>
    .NET’s EnvelopedCms class represents a CMS/PKCS #7 structure for enveloped data. Such data are for example used in S/MIME encrypted messages.

    EnvelopedCms class contains several Decrypt method overloads:

    • Decrypt()
    • Decrypt(RecipientInfo)
    • Decrypt(X509Certificate2Collection)
    • Decrypt(RecipientInfo, X509Certificate2Collection)

    Each Decrypt method decrypts the contents of the decoded enveloped CMS/PKCS #7 data. Each searches the current user and local machine My stores for the appropriate certificate and private key.

    Last two overloads allow passing additional collection of X509 certificates, that should be searched to find matching certificate for decryption.

    There are 2 most common errors that can occur while decrypting:

    • “The enveloped-data message does not contain the specified recipient.” – Which means that no matching certificate was found in My stores and in the additional certificate collection.
    • “Cannot find object or property.” – Certificate was found, but there is no private key in it, so it can not be used to decryped the enveloped data.

    There are 3 ways of adding certificates to My store, 2 of those don’t import private key:

    • “Personal” tab in CertMgr (does not import private key).
    • MMC “Certificates” snap-in (“My user account”) (does not import private key).
    • Double clicking the pfx file (imports private key).

    In many cases data are encrypted using 2 or more certificates (so both sender and receiver are able to decrypt the message)

    The problem with all Decrypt methods is that they try to use only the first certificate they find. The matching is based on certificate SN. First, both My stores are search, then extra store (passed certificate collection).

    This leads to a problem when, both certificates are in My store, but only one contains a private key.

    .NET is going to use the first certificate it finds – if it’s the one without the private key, “Cannot find object or property” exception is going to be thrown.

    The only workaround for this problem is to try to decrypt the message for each ReceipientInfo separately. This way we are sure that all certificates will be tried.

    Mail.dll .NET secure email component does this automatically, so no additional code is required.

    The post EnvelopedCms decrypt problem first appeared on Blog | Limilabs.

    ]]>
    SSL vs TLS vs STARTTLS – What are those? https://www.limilabs.com/blog/ssl-vs-tls-vs-starttls-stls Wed, 09 Oct 2013 18:34:55 +0000 http://www.limilabs.com/blog/?p=4320 There’s often quite a confusion about the different terms: SSL, TLS, STARTTLS and STLS. SSL and TLS SSL and TLS are cryptographic protocols, both provide a way to encrypt communication channel between two machines over the Internet (e.g. client computer and a server). SSL stands for Secure Sockets Layer and current version is 3.0. TLS […]

    The post SSL vs TLS vs STARTTLS – What are those? first appeared on Blog | Limilabs.

    ]]>
    There’s often quite a confusion about the different terms: SSL, TLS, STARTTLS and STLS.

    SSL and TLS

    SSL and TLS are cryptographic protocols, both provide a way to encrypt communication channel between two machines over the Internet (e.g. client computer and a server). SSL stands for Secure Sockets Layer and current version is 3.0. TLS stands for Transport Layer Security and the current version is 1.2. TLS is the successor to SSL. The terms SSL and TLS can be used interchangeably, unless you’re referring to a specific protocol version.

    Version numbering is inconsistent between SSL and TLSs. When TLS took over SSL as the preferred protocol name, it began with a new version number. The ordering of protocols in terms of oldest to newest is: SSLv2, SSLv3, TLSv1.0, TLSv1.1, TLSv1.2.

    STARTTLS and STLS

    STARTTLS is a protocol command, that is issued by an email client. It indicates, that the client wants to upgrade existing, insecure connection to a secure connection using SSL/TLS cryptographic protocol. STARTTLS command name is used by SMTP and IMAP protocols, whereas POP3 protocol uses STLS as the command name.

    Despite having TLS in the name, STARTTLS doesn’t mean TLS will be used. Both SSL and TLS are acceptable protocols for securing the communication.

    Clear text/Plain text

    No security protocol is used at all. All commands, responses and data are transferred in plain text.

    client.Connect("mail.example.com");
    

    Implict SSL mode

    Implict SSL mode means, that you connect to SSL/TLS encrypted port.

    client.ConnectSSL("mail.example.com");
    

    Explicit SSL mode

    Explicit SSL mode means, that you connect to plaint text port and secure the connection by issuing STARTTLS (or STLS) command afterwards (you explicitly secure the connection).

    client.Connect("mail.example.com");
    client.StartTLS();
    

    Securing the connection

    Regardless of whether you use implict (connecting to an SSL/TLS encrypted port) or explicit (using STARTTLS to upgrade an existing connection) mode, both sides will negotiate which protocol and which version to use. This negotiation is based on how client and server have been configured and what each side supports.

    SSL/TLS support

    Support for SSL/TLS is virtually universal, however which versions are supported is variable. Pretty much everything supports SSLv3. Most machines support TLSv1.0.

    TLS vs STARTTLS naming problem

    One significant complicating factor is that some email software incorrectly uses the term TLS when they should have used “STARTTLS” or “explicit SSL/TLS”. Older versions of Thunderbird used “TLS” to mean “enforce use of STARTTLS to upgrade the connection, and fail if STARTTLS is not supported” and “TLS, if available” to mean “use STARTTLS to upgrade the connection, if the server advertises support for it, otherwise just use an insecure connection” (very problematic, as we’ll see below).

    Port numbers

    To add security to some existing protocols (IMAP, POP3, SMTP), it was decided to just add SSL/TLS encryption as a layer underneath the existing protocol. However to distinguish that software should talk the SSL/TLS encrypted version of the protocol rather than the plaintext one, a different port number was used for each protocol:

    ProtocolPlain textSSL
    IMAP143993
    POP3110995
    SMTP587 or 25465

    Too many ports? Solution: Plain text + STARTTLS

    At some point, it was decided that having 2 ports for every protocol was wasteful.

    Instead it’s better to have 1 port, that starts off as plain text, but clients can upgrade the connection to an SSL/TLS encrypted one, using STARTTLS (or STLS for POP3 protocol) command.

    STARTTLS problems

    There were a few problems with STARTTLS introduction. There exists lots of software, that used the alternate port numbers with pure SSL/TLS connections. Client software can be very long lived, so you can’t just disable the encrypted ports until all software has been upgraded.

    Each protocol received mechanisms to tell clients that the server supported upgrading to SSL/TLS (e.g. STARTTLS in IMAP’s CAPABILITY response), and that they should not attempt to login without doing the STARTTLS upgrade (LOGINDISABLED in IMAP’s CAPABILITY response).

    This created two unfortunate situations:

    • Some software just ignored the “login disabled until upgraded” announcement (LOGINDISABLED, STARTTLS) and just tried to log in anyway, sending the user login name and password over clear text channel. The server rejected the login and password, but the details had already been sent over the Internet in plain text.
    • Other software saw the “login disabled until upgraded” announcement, but then wouldn’t upgrade the connection automatically, and thus reported login errors back to the user, which caused confusion about what was wrong.

    Both of these problems resulted in significant compatibility issues with existing clients, and so most system administrators continued to just use plain text connections on one port, and encrypted connections on a separate port number.

    Disable plain text for IMAP and POP3

    Many companies (e.g. Gmail, Outlook.com) disabled plain IMAP (port 143) and plain POP3 (port 110), so people must use a SSL/TLS encrypted connection – this removes the need for having STARTTLS command completely.

    SMTP STARTTLS stays

    The one real exception to the above is SMTP. Most email software used SMTP on port 25 to submit messages to the email server for onward transmission to the destination. However SMTP was originally designed for transfer, not submission. So yet another port (587) was defined for message submission.

    Port 587 doesn’t mandate requiring STARTTLS, however the use of port 587 became popular around the same time as the realization that SSL/TLS encryption of communications between clients and servers was an important issue. The result is that most systems, that offer message submission over port 587 require clients to use STARTLS to upgrade the connection. Login and password to authenticate is also required.

    There has been an additional benefit to this approach as well. By moving users away from using port 25 for email submission, ISPs can block outgoing port 25 connections from users’ computers, which were a significant source of spam, due to user computers infected with spam sending viruses.

    Further readings

    The post SSL vs TLS vs STARTTLS – What are those? first appeared on Blog | Limilabs.

    ]]>
    Copy to public folder: “There is no replica for that mailbox on this server.” https://www.limilabs.com/blog/copy-to-public-folder-there-is-no-replica-for-that-mailbox-on-this-server Sun, 01 Sep 2013 18:11:25 +0000 http://www.limilabs.com/blog/?p=4186 When copying an mail from the personal folder to a Public folder, you may receive “There is no replica for that mailbox on this server.” error. This error is generated by Exchange server and unfortunately this is the Exchange limitation. Here’s Microsoft’s response to this problem: Copying from user mailboxes to public folders does not […]

    The post Copy to public folder: “There is no replica for that mailbox on this server.” first appeared on Blog | Limilabs.

    ]]>
    When copying an mail from the personal folder to a Public folder, you may receive “There is no replica for that mailbox on this server.” error.

    This error is generated by Exchange server and unfortunately this is the Exchange limitation. Here’s Microsoft’s response to this problem:

    Copying from user mailboxes to public folders does not work with Exchange IMAP4.
    Your users need to copy the message to a personal folder and then back up to the public folder (append) or forward it to an address that gets archived to a public folder.

    Workaround

    It seems the only way to workaround this is by downloading a message and uploading it to public folder. Important thing is that you don’t need to parse email message at all – you just download and upload raw eml data. Please also note that public folder may be in fact stored on a another IMAP server instance (different server address) – this is usually indicated during logon with REFERRAL error.

    // C#
    
    using(Imap imap = new Imap())
    {
        imap.Connect("imap.example.com");   // or ConnectSSL for SSL
        imap.UseBestLogin("user", "password");
    
        imap.SelectInbox();
        List<long> uids = imap.Search(Flag.All);
    
        foreach (long uid in uids)
        {
            var eml = imap.GetMessageByUID(uid);
            IMail email = new MailBuilder().CreateFromEml(eml);
    
            if (email.Subject.Contains("[REF"))
                UploadToPublic(email);
        }
        imap.Close();
    }
    
    ' VB.NET
    
    Using imap As New Imap()
    	imap.Connect("imap.example.com")	' or ConnectSSL for SSL
    	imap.UseBestLogin("user", "password")
    
    	imap.SelectInbox()
    	Dim uids As List(Of Long) = imap.Search(Flag.All)
    
    	For Each uid As Long In uids
    		Dim eml = imap.GetMessageByUID(uid)
    		Dim email As IMail = New MailBuilder().CreateFromEml(eml)
    
    		If email.Subject.Contains("[REF") Then
    			UploadToPublic(email)
    		End If
    	Next
    	imap.Close()
    End Using
    

    Here is the body of UploadToPublic method:

    // C# code
    
    private void UploadToPublic(IMail email)
    {
        using (Imap imap = new Imap())
        {
            imap.Connect("server");  // or ConnectSSL for SSL
            imap.Login("user", "password");
        
            imap.UploadMessage("#Public/Cases", email);
        
            imap.Close();
        }
    }
    
    ' VB.NET code
    
    Private Sub UploadToPublic(email As IMail)
    	Using imap As New Imap()
    		imap.Connect("server")
    		' or ConnectSSL for SSL
    		imap.Login("user", "password")
    
    		imap.UploadMessage("#Public/Cases", email)
    
    		imap.Close()
    	End Using
    End Sub
    

    The post Copy to public folder: “There is no replica for that mailbox on this server.” first appeared on Blog | Limilabs.

    ]]>
    Get IIS pickup directory location https://www.limilabs.com/blog/get-iis-pickup-directory-location Thu, 22 Aug 2013 12:35:50 +0000 http://www.limilabs.com/blog/?p=4190 If you plan to use local IIS SMTP service to send emails you created using Mail.dll, you’ll need to save those emails to IIS pickup folder. Default folder location is “c:\Inetpub\mailroot\Pickup” There is a way to get IIS pickup folder location directly from IIS metabase. To get this path programmatically we’ll use IisPickupDirectory class. Unfortunatelly […]

    The post Get IIS pickup directory location first appeared on Blog | Limilabs.

    ]]>
    If you plan to use local IIS SMTP service to send emails you created using Mail.dll, you’ll need to save those emails to IIS pickup folder.

    Default folder location is “c:\Inetpub\mailroot\Pickup”

    There is a way to get IIS pickup folder location directly from IIS metabase. To get this path programmatically we’ll use IisPickupDirectory class. Unfortunatelly this class is not public, we’ll use its name to get its type and Activator class to invoke private static method GetPickupDirectory.

    To get type reference, we need to specify fully qualified type name “System.Net.Mail.IisPickupDirectory System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”. We can also search CurrentDomain’s assemblies to find System assembly and get its full name.

    Assembly system = AppDomain.CurrentDomain.GetAssemblies()
        .First(x => x.GetName().Name == "System");
    
    Type iisPickupType = Type.GetType(
        "System.Net.Mail.IisPickupDirectory, "
        + system.GetName().FullName,
        true);
    // -or- use fully qualified assembly name directly:
    //Type iisPickupType = Type.GetType(
    //    "System.Net.Mail.IisPickupDirectory, "
    //    + "System, Version=4.0.0.0, Culture=neutral, " 
    //    + "PublicKeyToken=b77a5c561934e089",
    //    true);
    
    string pickupFolder = (string)iisPickupType.InvokeMember(
        "GetPickupDirectory",
        BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic,
        null, null, null);
    
    

    “Cannot get IIS pickup directory.” error

    Unfortunately, this exception is raised when any kind of problem occurs, while trying to determine the location of IIS/SMTP pickup directory.

    A common cause is simply missing IIS SMTP service.

    The pickup directory is stored in the IIS Metabase, so if the account that your web-app runs as does not have access to the required nodes, this error can be thrown. Metabase permissions are separate from file permissions, so you explore it with Metabase explorer (part of the IIS resource kit).

    These nodes need to have read permission given to your web-app user: \LM, \LM\Smtpsrv\ and \LM\Smtpsrv\1

    The post Get IIS pickup directory location first appeared on Blog | Limilabs.

    ]]>
    Read system.net/mailSettings/smtp settings from web.config https://www.limilabs.com/blog/read-system-net-mailsettings-smtp-settings-web-config https://www.limilabs.com/blog/read-system-net-mailsettings-smtp-settings-web-config#comments Sun, 18 Aug 2013 13:20:29 +0000 http://www.limilabs.com/blog/?p=4189 There is a standard way of specifying SMTP settings in .NET applications. .NET uses config files (app.config or web.config in case of ASP.NET) and element to specify the appropriate SMTP parameters to send e-mail. Sample configuration (in this case Gmail SMTP settings) looks as follows: <configuration> <system.net> <mailSettings> <smtp deliveryMethod="network" from="pam@gmail.com"> <network host="smtp.gmail.com" port="465" enableSsl="true" […]

    The post Read system.net/mailSettings/smtp settings from web.config first appeared on Blog | Limilabs.

    ]]>
    There is a standard way of specifying SMTP settings in .NET applications. .NET uses config files (app.config or web.config in case of ASP.NET) and element to specify the appropriate SMTP parameters to send e-mail.

    Sample configuration (in this case Gmail SMTP settings) looks as follows:

    <configuration>
    
    <system.net>
      <mailSettings>
        <smtp deliveryMethod="network" from="pam@gmail.com">
          <network
            host="smtp.gmail.com"
            port="465"
            enableSsl="true"
            userName="pam@gmail.com"
            password="password"
        />
        </smtp>
      </mailSettings>
    </system.net>
    
    </configuration>
    

    If port attribute is omitted default value (25) is used. SMTP protocol typically uses ports 587 and 25 for non SSL connections, and port 465 for SSL ones.

    Although Mail.dll SMTP component does not support reading from web.config directly, it is quite easy to read those settings programmatically and use them with Mail.dll classes.

    Here’s the simple sample that reads from mailSettings section:

    SmtpSection section = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
    
    string from = section.From;
    string host = section.Network.Host;
    int port = section.Network.Port;
    bool enableSsl = section.Network.EnableSsl;
    string user = section.Network.UserName;
    string password = section.Network.Password;
    

    Use web.config’s mailSettings with Mail.dll

    In most cases you want to send email via SMTP server (DeliveryMethod set to SmtpDeliveryMethod.Network). Here’s the sample that uses web.config settings and Mail.dll’s STMP component to send an email message:

    SmtpSection section = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
    
    IMail email = Fluent.Mail
                .Text("Hi, how are you?")
                .Subject("Hello")
                .To("to@example.com")
                .From(section.From)
                .Create();
    
    using (Smtp client = new Smtp())
    {
        client.Connect(section.Network.Host, section.Network.Port, 
            section.Network.EnableSsl);
        client.UseBestLogin(section.Network.UserName, section.Network.Password);
        client.SendMessage(email);
        client.Close();
    }
    

    IIS pickup folder

    If you plan to use local IIS SMTP service to send emails you created using Mail.dll, you’ll need to save those emails to IIS pickup folder.

    You can specify folder location explicitly using SpecifiedPickupDirectory.PickupDirectoryLocation (default location is “c:\Inetpub\mailroot\Pickup”). You can also use SmtpDeliveryMethod.PickupDirectoryFromIis constant – in this case we’ll get pickup folder location directly from IIS metabase.

    Following is the code that recognizes different DeliveryMethods and acts accordingly:

    SmtpSection section = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
    IMail email = Fluent.Mail
                .Text("Hi, how are you?")
                .Subject("Hello")
                .To("lesnikowski@limilabs.com")
                .From(section.From)
                .Create();
    
    if (section.DeliveryMethod == SmtpDeliveryMethod.Network)
    {
        using (Smtp client = new Smtp())
        {
            client.Connect(section.Network.Host, section.Network.Port, 
                section.Network.EnableSsl);
            client.UseBestLogin(section.Network.UserName, section.Network.Password);
            client.SendMessage(email);
            client.Close();
        }
    }
    else if (section.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory)
    {
        string pickupFolder = section.SpecifiedPickupDirectory.PickupDirectoryLocation;
        email.Save(Path.Combine(pickupFolder, "email.eml"));
    }
    else if (section.DeliveryMethod == SmtpDeliveryMethod.PickupDirectoryFromIis)
    {
        Assembly system = AppDomain.CurrentDomain.GetAssemblies()
            .First(x => x.GetName().Name == "System");
        
        Type iisPickupType = Type.GetType(
            "System.Net.Mail.IisPickupDirectory, " 
            + system.GetName().FullName, 
            true);
        // -or- use fully qualified system assembly name directly:
        //Type iisPickupType = Type.GetType(
        //    "System.Net.Mail.IisPickupDirectory, " 
        //    + "System, Version=4.0.0.0, Culture=neutral, "
        //    + "PublicKeyToken=b77a5c561934e089",
        //    true);
    
        string pickupFolder = (string)iisPickupType.InvokeMember(
            "GetPickupDirectory", 
            BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic, 
            null, null, null);
    
        email.Save(Path.Combine(pickupFolder, "email.eml"));
    }
    

    The post Read system.net/mailSettings/smtp settings from web.config first appeared on Blog | Limilabs.

    ]]>
    https://www.limilabs.com/blog/read-system-net-mailsettings-smtp-settings-web-config/feed 3
    How to shorten Connect timeout https://www.limilabs.com/blog/how-to-shorten-connect-timeout Thu, 21 Mar 2013 14:53:47 +0000 http://www.limilabs.com/blog/?p=3807 Connect and BeginConnect methods take quite a long time to timeout, when you use incorrect server address. It usually takes almost 20 seconds for those methods to decide that connection is impossible. Setting SendTimeout/ReceiveTimeout doesn’t influence this in any way. Not only Imap, Pop3, and Smtp classes suffer from this problem, it’s the same for […]

    The post How to shorten Connect timeout first appeared on Blog | Limilabs.

    ]]>
    Connect and BeginConnect methods take quite a long time to timeout, when you use incorrect server address. It usually takes almost 20 seconds for those methods to decide that connection is impossible. Setting SendTimeout/ReceiveTimeout doesn’t influence this in any way.

    Not only Imap, Pop3, and Smtp classes suffer from this problem, it’s the same for regular Socket class.

    There is a solution however, using BeginConnect and simply waiting for specified amount of time (AsyncWaitHandle.WaitOne) without calling EndConnect (which blocks):

    // C#
    
    using(Imap imap =new Imap())
    {
        IAsyncResult result = imap.BeginConnectSSL("imap.example.com");
    
        // 5 seconds timeout
        bool success = result.AsyncWaitHandle.WaitOne(5000, true);
    
        if (success == false)
        {
            throw new Exception("Failed to connect server.");
        }
        imap.EndConnect(result);
    
        //...
    
        imap.Close();
    }
    
    ' VB.NET
    
    Using imap As New Imap()
    	Dim result As IAsyncResult = imap.BeginConnectSSL("imap.example.com")
    
    	' 5 seconds timeout
    	Dim success As Boolean = result.AsyncWaitHandle.WaitOne(5000, True)
    
    	If success = False Then
    		Throw New Exception("Failed to connect server.")
    	End If
    	imap.EndConnect(result)
    
    	'...
    
    	imap.Close()
    End Using
    

    The post How to shorten Connect timeout first appeared on Blog | Limilabs.

    ]]>