C# | Blog | Limilabs https://www.limilabs.com/blog Using Limilabs .net components Wed, 07 Aug 2024 20:05:32 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 IMAP component for .NET https://www.limilabs.com/blog/imap-component-for-net Wed, 29 Nov 2023 11:51:36 +0000 http://www.limilabs.com/blog/?p=219 Mail.dll email component includes an excellent IMAP email component. Unleash the full potential of email management with Mail.dll’s outstanding IMAP email component. It offers .NET developers an unparalleled tool for handling IMAP email protocol. From retrieving messages to managing folders and attachments, the IMAP component in Mail.dll simplifies complex tasks into user-friendly functions. Mail.dll is […]

The post IMAP component for .NET first appeared on Blog | Limilabs.

]]>
Mail.dll email component includes an excellent IMAP email component. Unleash the full potential of email management with Mail.dll’s outstanding IMAP email component.

It offers .NET developers an unparalleled tool for handling IMAP email protocol. From retrieving messages to managing folders and attachments, the IMAP component in Mail.dll simplifies complex tasks into user-friendly functions.

Mail.dll is available for all regular .NET framework versions as well as for most recent .net 6, 7 and .net 8 and higher.

IMAP, short for Internet Message Access Protocol, is one of the two most prevalent Internet standard protocols for e-mail retrieval, the other being Post Office Protocol – POP3 (also available in Mail.dll).

IMAP has many advantages over POP3, most important are using folders to group emails, saving seen/unseen state of the messages and search capability.

This article is going to show how easy is to connect to use IMAP client from .NET, download and parse unseen messages.

Installation

The easiest way to install Mail.dll is to download it from nuget via Package Manager:

PM> Install-Package Mail.dll

Alternatively you can download Mail.dll directly from our website.

Connect to IMAP

First you need connect to IMAP server. You should use Imap class for that. Using block ensures that IMAP connection is properly closed and disposed when you’re done.

using(Imap imap = new Imap())

In most cases you should be using TLS secured connection – ConnectSSL method will choose a correct port and perform SSL/TLS negotiation, then you perform IMAP authentictation:

	imap.ConnectSSL("imap.server.com");
	imap.UseBestLogin("user", "password");

Mail.dll supports OAuth 2.0 for authentication, you can find OAuth2 samples for Office365 and Gmail on the Mail.dll samples page.

For Gmail you may want to use Gmail’s App Passwords.

Search for unseen emails

As IMAP groups messages into folder you need to select a well know INBOX folder. All new, received emails are first placed in the INBOX folder first:

imap.SelectInbox();

Then you perform a search that find all unseen messages

List<long> uids = imap.Search(Flag.Unseen);

Download and parse emails

Finally you download emails one-by-one and parse them. You should use MailBuider class to parse emails:

var eml = imap.GetMessageByUID(uid);
IMail email = new MailBuilder().CreateFromEml(eml);

Entire code to download emails in .net

Entire code to download emails using IMAP is less than 20 lines:

using(Imap imap = new Imap())
{
	imap.ConnectSSL("imap.server.com");	// or Connect for no TLS
	imap.UseBestLogin("user", "password");

	imap.SelectInbox();
	List<long> uids = imap.Search(Flag.Unseen);

	foreach (long uid in uids)
	{
		var eml = imap.GetMessageByUID(uid);
		IMail email = new MailBuilder().CreateFromEml(eml);

		string subject = mail.Subject;
	}
	imap.Close();
}

and for those who like VB.NET more:

Using imap As New Imap()
	imap.ConnectSSL("imap.server.com")
	imap.UseBestLogin("user", "password")

	imap.SelectInbox()
	Dim uids As List(Of Long) = imap.Search(Flag.Unseen)

	For Each uid As Long In uids
		Dim mail As IMail = New MailBuilder()_
			.CreateFromEml(imap.GetMessageByUID(uid))

		Console.WriteLine(mail.Subject)
	Next
	imap.Close()
End Using

It can’t get much simpler than that!

Summary

You can use Mail.dll .NET IMAP component to:

It works perfectly with Exchange, Office365, Gmail and all other IMAP servers.

Just give Mail.dll a try and download it at: Mail.dll .NET IMAP component


Get Mail.dll

The post IMAP component for .NET first appeared on Blog | Limilabs.

]]>
How to search IMAP in .NET https://www.limilabs.com/blog/how-to-search-imap-in-net https://www.limilabs.com/blog/how-to-search-imap-in-net#comments Mon, 31 Jul 2023 13:49:47 +0000 http://www.limilabs.com/blog/?p=181 One of many advantages IMAP protocol has over POP3 protocol is the ability to search. There are several ways of performing search using Mail.dll .NET IMAP library: IMAP search is done entirely on the server side, which means that it’s fast and doesn’t require Mail.dll client to download much data over the network. Installation The […]

The post How to search IMAP in .NET first appeared on Blog | Limilabs.

]]>
One of many advantages IMAP protocol has over POP3 protocol is the ability to search.

There are several ways of performing search using Mail.dll .NET IMAP library:

  • Search(Flag) – for common flag searches (seen, unseen, …).
  • SimpleImapQuery – easy one object query, where all conditions are joined with an AND operator.
  • Expression syntax – most advanced, allows using AND and OR operators and sorting.

IMAP search is done entirely on the server side, which means that it’s fast and doesn’t require Mail.dll client to download much data over the network.

Installation

The easiest way to install Mail.dll IMAP client for .NET is to download it from nuget via Package Manager:

PM> Install-Package Mail.dll

Alternatively you can download Mail.dll directly from our website.

Connect to IMAP

Let’s start with the basics: we’ll connect to the IMAP server in .NET app and authenticate:

// C# code:

using (Imap imap = new Imap())
{
    imap.ConnectSSL("imap.example.com");
    imap.UseBestLogin("user", "password");
    imap.SelectInbox();

    // Search code goes here

    imap.Close();
}
' VB.NET code:

Using imap As New Imap()
    imap.ConnectSSL("imap.example.com")
    imap.UseBestLogin("user", "password")
    imap.SelectInbox()

    ' Search code here

    imap.Close()
End Using

When using Gmail you can use application passwords, with Office 365 you’ll need to use OAuth 2.0 to authenticate.

Mail.dll fully supports OAuth 2.0 for authentication, you can find OAuth2 samples for Office365 and Gmail on the Mail.dll samples page.

Search(Flag)

Now, let’s look at the search code. The first and the simplest way to search is by using Imap.Search(Flag) method. This sample below finds all unseen email messages (those that have \UNSEEN flag).

// C#

List<long> uidList = imap.Search(Flag.Unseen);

// now download each message and get the subject
foreach (long uid in uidList)
{
    IMail message = new MailBuilder()
        .CreateFromEml(imap.GetMessageByUID(uid));

    string subject = message.Subject;
}
' VB.NET

Dim uidList As List(Of Long) = imap.Search(Flag.Unseen)

' now download each message and get the subject
For Each uid As Long In uidList
	Dim message As IMail = New MailBuilder()_
		.CreateFromEml(imap.GetMessageByUID(uid))

	Dim subject As String = message.Subject
Next

SimpleImapQuery

Second approach is to use an IMAP query object. The sample below searches for all unseen emails with a certain subject. All non-null SimpleImapQuery properties are combined using and operator.

// C#

SimpleImapQuery query = new SimpleImapQuery();
query.Subject = "subject to search";
query.Unseen = true;

List<long> uids = imap.Search(query);
' VB.NET

Dim query As New SimpleImapQuery()
query.Subject = "subject to search"
query.Unseen = True

Dim uids As List(Of Long) = imap.Search(query)

Expression syntax

Finally, the most advanced search option using Expression class. You can use AND, OR and NOT operators in your IMAP search.

Note that Mail.dll fully encapsulates IMAP search syntax, with easy to use and very readable .NET classes:

// C#

List<long> uids = imap.Search().Where(
    Expression.And(
        Expression.Not(Expression.Subject("subject not to search")),
        Expression.HasFlag(Flag.Unseen)));
' VB.NET

Dim uids As List(Of Long) = imap.Search().Where(_
    Expression.[And](_
        Expression.[Not](Expression.Subject("subject not to search")),_
        Expression.HasFlag(Flag.Unseen)))

Expression syntax with sorting

Expression search syntax also allows sorting (defined in RFC 5256).

This feature is not available for every IMAP server: you need to check if your IMAP server supports ImapExtension.Sort extension first.

// C#

List<long> uids = imap.Search()
    .Where(Expression.And(
            Expression.Not(Expression.Subject("subject not to search")),
            Expression.HasFlag(Flag.Unseen)))
    .Sort(SortBy.Multiple(
            SortBy.Date(),
            SortBy.Subject()));
' VB.NET

Dim uids As List(Of Long) = imap.Search() _
    .Where(Expression.[And]( _
        Expression.[Not](Expression.Subject("subject not to search")), _
        Expression.HasFlag(Flag.Unseen))) _
    .Sort(SortBy.Multiple( _
        SortBy.[Date](), _
        SortBy.Subject()))
)

Notice the neat trick in Mail.dll .NET client, that allows casting FluentSearch class, received from imap.Search() method, to List<longs>:

public static implicit operator List<long>(FluentSearch search)
{
        return search.GetList();
}

We tend to use it very often for builder objects used in our unit tests.

Suggested reading

If you like it just give it a try and download it at: Mail.dll .NET IMAP component


Get Mail.dll

The post How to search IMAP in .NET first appeared on Blog | Limilabs.

]]>
https://www.limilabs.com/blog/how-to-search-imap-in-net/feed 36
Save all attachments to disk using IMAP https://www.limilabs.com/blog/save-all-attachments-to-disk-using-imap https://www.limilabs.com/blog/save-all-attachments-to-disk-using-imap#comments Fri, 28 Jul 2023 15:41:29 +0000 http://www.limilabs.com/blog/?p=1232 Unlock the potential of efficient email processing in .NET with this comprehensive guide on saving email attachments using Mail.dll’s IMAP component and IMAP protocol. In this article, we’ll walk you through the step-by-step process of downloading email messages using Mail.dll’s IMAP component and, more importantly, demonstrate how to effortlessly save all attachments to your disk. […]

The post Save all attachments to disk using IMAP first appeared on Blog | Limilabs.

]]>
Unlock the potential of efficient email processing in .NET with this comprehensive guide on saving email attachments using Mail.dll’s IMAP component and IMAP protocol.

In this article, we’ll walk you through the step-by-step process of downloading email messages using Mail.dll’s IMAP component and, more importantly, demonstrate how to effortlessly save all attachments to your disk.

Email MIME structure

The first thing you need to know is that email attachments are tightly integrated with the email message itself, ensuring that they are conveniently stored and transport together.

In MIME (Multipurpose Internet Mail Extensions), email attachments are stored together with an email message to ensure a structured and standardized way of transmitting and receiving email content with multiple parts.

The primary reason for storing attachments within the email message is to maintain a single cohesive entity that encapsulates all the components of the email, including its text, formatting, and any attached files. By bundling attachments with the message, the entire email becomes a self-contained package, making it easier to handle and process by email clients and servers.

Attachments in Mail.dll

Invoking Imap.GetMessageByUID method is going to download entire email message, including all attachments.

Attachments are stored within the email as part of a mime tree. Usually Quoted-Printable or Base64 encoding is used.

However, with Mail.dll, you don’t need to worry about navigating this mime tree yourself. The library efficiently parses the email’s structure, effortlessly exposing all attachments as familiar .NET collections. This user-friendly approach simplifies the process of handling email attachments, allowing you to focus on building robust and efficient email management solutions with ease.

There are 4 collections that contain attachments:

  • IMail.Attachments – all attachments (includes Visuals, NonVisuals and Alternatives).
  • IMail.Visuals – visual elements, files that should be displayed to the user, such as images embedded in an HTML email.
  • IMail.NonVisuals – non visual elements, “real” attachments.
  • IMail.Alternatives – alternative content representations, for example ical appointment.

How to download all email attachments in .NET

To retrieve all attachments from an email, you can take advantage of the IMail.Attachments collection provided by Mail.dll. This collection serves as a comprehensive repository, housing all the attachments associated with the email.

Each attachment is represented by a dedicated MimeData object, which encapsulates the specific data and metadata of the attachment.

Using the IMail.Attachments collection eliminates the need for manual traversal of the email’s mime tree or deciphering complex structures. Instead, Mail.dll handles the heavy lifting for you, ensuring a streamlined and user-friendly experience when accessing email attachments programmatically.

Installation

The easiest way to install Mail.dll is to download it from nuget via Package Manager:

PM> Install-Package Mail.dll

Alternatively you can download Mail.dll directly from our website.

Download emails and all attachments

The C# code to download all emails and save all attachments using Mail.dll and IMAP is as follows.

using Limilabs.Client.IMAP;
using Limilabs.Mail;
using Limilabs.Mail.MIME
using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        using(Imap imap = new Imap())
        {
            imap.ConnectSSL("imap.example.com");
            imap.UseBestLogin("user", "password");

            imap.SelectInbox();
            List<long>; uids = imap.Search(Flag.Unseen);
            foreach (long uid in uids)
            {
                var eml = imap.GetMessageByUID(uid);
                IMail email = new MailBuilder()
                    .CreateFromEml(eml);
                Console.WriteLine(email.Subject);

                foreach (MimeData mime in email.Attachments)
                {
                    mime.Save(@"c:\" + mime.SafeFileName);
                }
            }
            imap.Close();
        }
    }
};

Below is the VB.NET code for your reference:

Imports Limilabs.Client.IMAP
Imports Limilabs.Mail
Imports Limilabs.Mail.MIME
Imports System
Imports System.Collections.Generic

Public Module Module1
    Public Sub Main(ByVal args As String())

        Using imap As New Imap()
            imap.ConnectSSL("imap.example.com")
            imap.UseBestLogin("user", "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 email As IMail = New MailBuilder() _
                    .CreateFromEml(eml)
                Console.WriteLine(email.Subject)

                For Each mime As MimeData In email.Attachments
                    mime.Save("c:\" + mime.SafeFileName)
                Next
            Next
            imap.Close()
        End Using

    End Sub
End Module

Accessing attachment data

You can also save attachment to a specific stream using MimeData.Save(Stream stream).

You can get direct access to attachment binary data with MimeData.GetMemoryStream().

Finally you can get a byte array (byte[]) using MimeData.Data property.

Downloading only parts of the message

IMAP protocol provides very useful features in regard to working with attachments and all are available in Mail.dll .NET IMAP component.

With Mail.dll you can download only parts of email message, which in conjunction with getting basic email information without downloading entire message can make your code extremely fast.

Process emails embedded as attachments

In some situations you’ll receive a message that has another message attached.

You can use Mail.dll to extract all attachments from such inner messages no matter how deep the embedding level is.


Get Mail.dll

The post Save all attachments to disk using IMAP first appeared on Blog | Limilabs.

]]>
https://www.limilabs.com/blog/save-all-attachments-to-disk-using-imap/feed 10
Office 365 enable IMAP/POP3 and SMTP access https://www.limilabs.com/blog/office365-enable-imap-pop3-smtp Fri, 18 Feb 2022 12:56:34 +0000 https://www.limilabs.com/blog/?p=5901 First log in to Microsoft 365 admin portal at https://admin.microsoft.com/ as an administrator, go to Org settings screen and find Modern authentication entry: Check ‘Turn on modern authentication…‘ for OAuth flows. Check IMAP, POP3 and SMTP for App passwords flows. Then go to Users screen: Select an user and on the Mail tab click Manage […]

The post Office 365 enable IMAP/POP3 and SMTP access first appeared on Blog | Limilabs.

]]>
First log in to Microsoft 365 admin portal at https://admin.microsoft.com/ as an administrator, go to Org settings screen and find Modern authentication entry:

Check ‘Turn on modern authentication…‘ for OAuth flows.

Check IMAP, POP3 and SMTP for App passwords flows.

Then go to Users screen:

Select an user and on the Mail tab click Manage email apps

Check IMAP, Pop and Authenticated SMTP to turn on the protocols for this account

Have in mind it takes 20-30 minutes for the changes to take effect.

AD configuration

In your Active Directory, make sure Enable Security defaults is set to No:

Make sure there are no Conditional Access | Policies defined in your AD:

Authentication – Basic Auth [deprecated]

It is no longer possible to re-enable Basic Auth or use App passwords.

To use basic authentication (username/password) you’ll need to
Re-enable Basic Auth for your tenant

For MFA enabled/enforced accounts you must
Create and use App passwords

using (Imap imap = new Imap())
{
    imap.ConnectSSL("outlook.office365.com");
 
    imap.UseBestLogin(
        "AdeleV@limilabs.onmicrosoft.com",  
        "password");
 
    imap.SelectInbox();

    List<long> uids = imap.Search(Flag.Unseen);
 
    foreach (long uid in uids)
    {
        IMail email = new MailBuilder()
            .CreateFromEml(imap.GetMessageByUID(uid));
        string subject = email.Subject;
    }
 
    imap.Close();
}

Authentication – OAuth 2.0

Daemons/Services: Password grant (MFA/2FA must be turned off for this account):
https://www.limilabs.com/blog/oauth2-password-grant-office365-exchange-imap-pop3-smtp

Daemons/Services: Client credential flow:
https://www.limilabs.com/blog/oauth2-client-credential-flow-office365-exchange-imap-pop3-smtp

Web apps (requires user interaction):
https://www.limilabs.com/blog/oauth2-web-flow-office365-exchange-imap-pop3-smtp

Standalone devices (requires very little interaction):
https://www.limilabs.com/blog/oauth2-device-flow-office365-exchange-imap-pop3-smtp

Desktop apps (requires user interaction):
https://www.limilabs.com/blog/oauth2-office365-exchange-imap-pop3-smtp

using (Imap imap = new Imap())
{
    imap.ConnectSSL("outlook.office365.com");
 
    imap.UseBestLogin(
        "AdeleV@limilabs.onmicrosoft.com",  
        "access-token");
 
    imap.SelectInbox();

    List<long> uids = imap.Search(Flag.Unseen);
 
    foreach (long uid in uids)
    {
        IMail email = new MailBuilder()
            .CreateFromEml(imap.GetMessageByUID(uid));
        string subject = email.Subject;
    }
 
    imap.Close();
}

Exchange administration

You can find the same mailbox/user settings through Exchange administration screens:


Get Mail.dll

The post Office 365 enable IMAP/POP3 and SMTP access first appeared on Blog | Limilabs.

]]>
Office 365 App passwords https://www.limilabs.com/blog/office365-app-passwords Fri, 18 Feb 2022 12:35:08 +0000 https://www.limilabs.com/blog/?p=5890 It is no longer possible to re-enable Basic Auth or use App passwords. You’ll need to use one of the OAuth 2.0 flows:   OAuth 2.0 with Office365/Exchange IMAP/POP3/SMTP OAuth 2.0 web flow with Office365/Exchange IMAP/POP3/SMTP OAuth 2.0 password grant with Office365/Exchange IMAP/POP3/SMTP OAuth 2.0 device flow with Office365/Exchange IMAP/POP3/SMTP OAuth 2.0 client credential flow […]

The post Office 365 App passwords first appeared on Blog | Limilabs.

]]>
It is no longer possible to re-enable Basic Auth or use App passwords.

First make sure IMAP/POP3/SMTP are turned on properly: enable IMAP / POP3 and SMTP in Office 365

To use App passwords, Multi-factor Authentication (MFA) must be turned on for the account.

On the other had, if you have MFA turned on for your account, App passwords are the simplest way to receive your emails – your primary password won’t work.

First log in to Microsoft 365 admin portal at https://admin.microsoft.com/ as an administrator. Go to Users screen and click Multi-factor authentication:

Select a user and change Multi-factor Auth Status to Enforced:

Log in as this user to his My Account at https://myaccount.microsoft.com/, then go My sign-ins and create a new App password on the Security info screen:

Write down the created password (you won’t be able to see it again).

Have in mind it takes 20-30 minutes for the changes to take effect.

Remember to turn IMAP on for those Office 365 accounts as well, now you can now use it as a standard password:

using (Imap imap = new Imap())
{
    imap.ConnectSSL("outlook.office365.com");

    imap.UseBestLogin(
        "AlexW@limilabs.onmicrosoft.com", 
        "qfhnlzsdaqew");

    imap.SelectInbox();

    List<long> uids = imap.Search(Flag.Unseen);

    foreach (long uid in uids)
    {
        IMail email = new MailBuilder()
            .CreateFromEml(imap.GetMessageByUID(uid));
        string subject = email.Subject;
    }

    imap.Close();
}

You can find more details here as well:
https://support.microsoft.com/en-us/account-billing/using-app-passwords-with-apps-that-don-t-support-two-step-verification-5896ed9b-4263-e681-128a-a6f2979a7944

The post Office 365 App passwords first appeared on Blog | Limilabs.

]]>
Outlook365: IMAP, POP3, and SMTP settings https://www.limilabs.com/blog/outlook365-imap-pop3-smtp-settings Wed, 02 Jan 2019 14:17:59 +0000 http://www.limilabs.com/blog/?p=3650 Outlook365 supports access via IMAP, POP3 and SMTP protocols. Below you can find the configuration settings for all protocols. Latest Office 365 version For latest Office 365 after the service upgrade, use the following settings: IMAP Server: outlook.office365.comSSL: true-implicit, true-explicit (StartTLS)Port: 993 (default), 143 (default)User: pat@domain.onmicrosoft.com or pat@your-domain.com POP3 Server: outlook.office365.comSSL: true-implicit, true-explicit (StartTLS)Port: 995 […]

The post Outlook365: IMAP, POP3, and SMTP settings first appeared on Blog | Limilabs.

]]>
Outlook365 supports access via IMAP, POP3 and SMTP protocols. Below you can find the configuration settings for all protocols.

Latest Office 365 version

For latest Office 365 after the service upgrade, use the following settings:

IMAP

Server: outlook.office365.com
SSL: true-implicit, true-explicit (StartTLS)
Port: 993 (default), 143 (default)
User: pat@domain.onmicrosoft.com or pat@your-domain.com

POP3

Server: outlook.office365.com
SSL: true-implicit, true-explicit (StartTLS)
Port: 995 (default), 110 (default)
User: pat@domain.onmicrosoft.com or pat@your-domain.com

SMTP

Server: outlook.office365.com
SSL: true-explicit (StartTLS)
Port: 587(default)
User: pat@domain.onmicrosoft.com or pat@your-domain.com

IMAP and POP3 servers allow both: implicit SSL/TLS and explicit SSL/TLS, so you can ConnectSSL method -or- Connect and StartTLS.

SMTP server requires explicit SSL – use Connect and StartTLS method.

Authentication

For Exchange Online/Office 365, we recommend using OAuth 2.0 flows:

Daemons/Services: Password grant (MFA/2FA must be turned off for this account):
https://www.limilabs.com/blog/oauth2-password-grant-office365-exchange-imap-pop3-smtp

Daemons/Services: Client credential flow:
https://www.limilabs.com/blog/oauth2-client-credential-flow-office365-exchange-imap-pop3-smtp

Web apps (requires user interaction):
https://www.limilabs.com/blog/oauth2-web-flow-office365-exchange-imap-pop3-smtp

Standalone devices (requires very little interaction):
https://www.limilabs.com/blog/oauth2-device-flow-office365-exchange-imap-pop3-smtp

Desktop apps (requires user interaction):
https://www.limilabs.com/blog/oauth2-office365-exchange-imap-pop3-smtp

It is no longer possible to re-enable Basic Auth or use App passwords.

// C#

using (Imap client = new Imap())
{
    client.ConnectSSL("outlook.office365.com");
    client.UseBestLogin("user@domain.onmicrosoft.com", "accesstoken");
    ...
}

using (Pop3 client = new Pop3())
{
    client.ConnectSSL("outlook.office365.com");
    client.UseBestLogin("user@domain.onmicrosoft.com", "accesstoken");
    ...
}

using (Smtp client = new Smtp ())
{
    client.Connect("outlook.office365.com");
    client.StartTLS();

    client.UseBestLogin("user@domain.onmicrosoft.com", "accesstoken");
    ...
}
' VB.NET

Using client As New Imap()
	client.ConnectSSL("outlook.office365.com")
	client.UseBestLogin("user@domain.onmicrosoft.com", "accesstoken")
	...
End Using

Using client As New Pop3()
	client.ConnectSSL("outlook.office365.com")
	client.UseBestLogin("user@domain.onmicrosoft.com", "accesstoken")
	...
End Using

Using client As New Smtp()
	client.Connect("outlook.office365.com")
	client.StartTLS()

	client.UseBestLogin("user@domain.onmicrosoft.com", "accesstoken")
	...
End Using

Office 365 pre-upgrade

For latest Office 365 pre-upgrade, use the following settings:

On the main screen go to “Options” / “See All Options…”:

Now click the “Settings for POP, IMAP, and SMTP access…” link:

You can find POP, SMTP and IMAP server addresses and settings on the popup window:

Office365 uses default ports for IMAP, POP3 and SMTP protocols. That means that you don’t need to remember port numbers, as Mail.dll .NET email component is going to use correct port numbers by default.

IMAP

Server: podXXXX.outlook.com
SSL: true-implicit
Port: 993 (default)
User: pat@domain.onmicrosoft.com or pat@your-domain.com

POP3

Server: podXXXX.outlook.com
SSL: true-implicit
Port: 995 (default)
User: pat@domain.onmicrosoft.com or pat@your-domain.com

SMTP

Server: podXXXX.outlook.com
SSL: true-explicit
Port: 587 (default)
User: pat@domain.onmicrosoft.com or pat@your-domain.com

You can find more details about using implicit and explicit SSL or TLS with email protocols:

The post Outlook365: IMAP, POP3, and SMTP settings first appeared on Blog | Limilabs.

]]>
OAuth 2.0 with Gmail over IMAP for installed applications https://www.limilabs.com/blog/oauth2-gmail-imap-installed-applications Mon, 13 Mar 2017 05:01:09 +0000 http://www.limilabs.com/blog/?p=3359 You can also read how to use:   OAuth 2.0 with Gmail over IMAP for web applications (Google.Apis) OAuth 2.0 with Gmail over IMAP for installed applications (Google.Apis) OAuth 2.0 with Gmail over IMAP for service account (Google.Apis) OAuth 2.0 is an open protocol to allow secure API authorization in a simple and standard method […]

The post OAuth 2.0 with Gmail over IMAP for installed applications first appeared on Blog | Limilabs.

]]>
You can also read how to use:

 

OAuth 2.0 is an open protocol to allow secure API authorization in a simple and standard method from desktop and web applications.

This article describes using OAuth 2.0 to access Gmail IMAP and SMTP servers using .NET IMAP component in installed applications scenario. You can also use OAuth 2.0 for web applications.

Google.Apis

Use Nuget to download “Google.Apis.Auth” package.

Import namespaces:

// c#

using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Requests;
using Google.Apis.Auth.OAuth2.Responses;

using Limilabs.Client.Authentication.Google;

using Limilabs.Client.IMAP;
' VB.NET 

Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Auth.OAuth2.Flows
Imports Google.Apis.Auth.OAuth2.Requests
Imports Google.Apis.Auth.OAuth2.Responses

Imports Limilabs.Client.Authentication.Google

Imports Limilabs.Client.IMAP

Register Application

Before you can use OAuth 2.0, you must register your application using the Google Cloud Console. After you’ve registered copy the “Client ID” and “Client secret” values which you’ll need later.

At least product name must be specified:

Now create credentials:

After you’ve registered, copy the “Client ID” and “Client secret” values, which you’ll need later:

Now we can define clientID, clientSecret and scope variables, as well as Google OAuth 2.0 server addresses. Scope basically specifies what services we want to have access to. In our case it is user’s email address and IMAP/SMTP access:

// C#

string clientID = "XXX.apps.googleusercontent.com";
string clientSecret = "IxBs0g5sdaSDUz4Ea7Ix-Ua";

var clientSecrets = new ClientSecrets
{
    ClientId = clientID,
    ClientSecret = clientSecret
};

var credential = new GoogleAuthorizationCodeFlow(
    new GoogleAuthorizationCodeFlow.Initializer
    {
        ClientSecrets = clientSecrets,
        Scopes = new[] { 
            GoogleScope.ImapAndSmtp.Name, 
            GoogleScope.UserInfoEmailScope.Name}
    });
' VB.NET 

Dim clientID As String = "XXX.apps.googleusercontent.com"
Dim clientSecret As String = "IxBs0g5sdaSDUz4Ea7Ix-Ua"

Dim clientSecrets = New ClientSecrets With { _
	.ClientId = clientID, _
	.ClientSecret = clientSecret _
}

Dim credential = New GoogleAuthorizationCodeFlow( _
    New GoogleAuthorizationCodeFlow.Initializer With { _
    	.ClientSecrets = clientSecrets, _
	    .Scopes = { _
            GoogleScope.ImapAndSmtp.Name,  _
            GoogleScope.UserInfoEmailScope.Name} _
})

Obtain an OAuth 2.0 access token

Now we’ll create authorization url.

As OOB addresses are no longer supported, to receive the authorization code using this URL, your application must be listening on the local web server. This is the recommended mechanism for obtaining the authorization code.

When your app receives the authorization response, for best usability it should respond by displaying an HTML page that instructs the user to close the browser and return to your app.

Your application needs to create a server that listens on this local address:

http://127.0.0.1:port or http://[::1]:port or http://localhost:port

Query your platform for the relevant loopback IP address and start an HTTP listener on a random available port. Substitute port with the actual port number your app listens on.

// C#

AuthorizationCodeRequestUrl url = credential
    .CreateAuthorizationCodeRequest("http://127.0.0.1:1234/auth2callback");

Process.Start(url.Build().ToString());
' VB.NET 

Dim url As AuthorizationCodeRequestUrl = credential _
    .CreateAuthorizationCodeRequest("http://127.0.0.1:1234/auth2callback")

Process.Start(url.Build().ToString())

We are using Process.Start here, but you can also embed WebBrowser control in your application.

At this point user is redirected to Google to authorize the access:

After this step user is redirected to the loopback address you provided.

Your application’s local web server, listening on this address, should obtain code from the url parameter.

Following is a code that reads this code and contacts Google to exchange it for a refresh-token and an access-token:

string authCode = "get from the url";

TokenResponse token = await credential.ExchangeCodeForTokenAsync(
    "", 
    authCode, 
    "http://127.0.0.1/auth2callback", 
    CancellationToken.None);

string accessToken = token.AccessToken;
' VB.NET 

Dim authCode As String = "get from the url";

Dim token As TokenResponse = Await credential.ExchangeCodeForTokenAsync( _
    "",  _
    authCode,  _
    "http://127.0.0.1/auth2callback",  _
    CancellationToken.None)

Dim accessToken As String = token.AccessToken

An access token is usually valid for a maximum of one hour, and allows you to access the user’s data. You also received a refresh token. A refresh token can be used to request a new access token once the previous expired.

Access IMAP/SMTP server

Finally we’ll ask Google for user’s email and use LoginOAUTH2 method to access Gmail’s IMAP server:

// C#

GoogleApi api = new GoogleApi(accessToken);
string user = api.GetEmail();

using (Imap imap = new Imap())
{
    imap.ConnectSSL("imap.gmail.com");
    imap.LoginOAUTH2(user, accessToken);

    imap.SelectInbox();
    List<long> uids = imap.Search(Flag.Unseen);

    foreach (long uid in uids)
    {
        var eml = imap.GetMessageByUID(uid);
        IMail email = new MailBuilder().CreateFromEml(eml);
        Console.WriteLine(email.Subject);
    }
    imap.Close();
}
' VB.NET 

Dim api As New GoogleApi(accessToken)
Dim user As String = api.GetEmail()

Using imap As New Imap()
	imap.ConnectSSL("imap.gmail.com")
	imap.LoginOAUTH2(user, accessToken)

	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 email As IMail = New MailBuilder().CreateFromEml(eml)
		Console.WriteLine(email.Subject)
	Next
	imap.Close()
End Using

Refreshing access token

An access token is usually short lived and valid for a maximum of one hour. The main reason behind this is security and prevention of replay attacks. This means that for long-lived applications you need to refresh the access token.

Your refresh token will be sent only once – don’t loose it!

We recommend storing entire TokenResponse object received from GoogleAuthorizationCodeFlow.ExchangeCodeForTokenAsync method call. This object contains both: refresh token and access token, along with its expiration time.

The process of refreshing access token is simple:

// c#

TokenResponse refreshed = await credential.RefreshTokenAsync(
    "", 
    token.RefreshToken, 
    CancellationToken.None);
' VB.NET 

Dim refreshed As TokenResponse = Await credential.RefreshTokenAsync( _
    "",  _
    token.RefreshToken,  _
    CancellationToken.None)

The post OAuth 2.0 with Gmail over IMAP for installed applications first appeared on Blog | Limilabs.

]]>
OAuth 2.0 with Gmail over IMAP for web applications https://www.limilabs.com/blog/oauth2-gmail-imap-web-applications Mon, 13 Mar 2017 05:00:39 +0000 http://www.limilabs.com/blog/?p=3328 You can also read how to use:   OAuth 2.0 with Gmail over IMAP for web applications (Google.Apis) OAuth 2.0 with Gmail over IMAP for installed applications (Google.Apis) OAuth 2.0 with Gmail over IMAP for service account (Google.Apis) OAuth 2.0 is an open protocol to allow secure API authorization in a simple and standard method […]

The post OAuth 2.0 with Gmail over IMAP for web applications first appeared on Blog | Limilabs.

]]>
You can also read how to use:

 

OAuth 2.0 is an open protocol to allow secure API authorization in a simple and standard method from desktop and web applications.

This article describes using OAuth 2.0 to access Gmail IMAP and SMTP servers using .NET IMAP component in web application scenario (ASP.NET/ASP.NET MVC). You can also use OAuth 2.0 for installed applications.

Google.Apis

Use Nuget to download “Google.Apis.Auth” package.

Import namespaces:

// c#

using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Requests;
using Google.Apis.Auth.OAuth2.Responses;

using Limilabs.Client.Authentication.Google;

using Limilabs.Client.IMAP;
' VB.NET 

Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Auth.OAuth2.Flows
Imports Google.Apis.Auth.OAuth2.Requests
Imports Google.Apis.Auth.OAuth2.Responses

Imports Limilabs.Client.Authentication.Google

Imports Limilabs.Client.IMAP

Register Application

Before you can use OAuth 2.0, you must register your application using the Google Cloud Console. After you’ve registered, specify “Redirect URI” and copy the “Client ID” and “Client secret” values which you’ll need later.

At least product name must be specified:

Now create credentials:

Specify redirect URI:

After you’ve registered, copy the “Client ID” and “Client secret” values, which you’ll need later:

Now we can define clientID, clientSecret, redirect url and scope variables, as well as Google OAuth 2.0 server addresses. Scope basically specifies what services we want to have access to. In our case it is user’s email address and IMAP/SMTP access:

// C#

string clientID = "XXX.apps.googleusercontent.com";
string clientSecret = "IxBs0g5sdaSDUz4Ea7Ix-Ua";
string redirectUri = "https://www.example.com/oauth2callback";

var clientSecrets = new ClientSecrets
{
    ClientId = clientID,
    ClientSecret = clientSecret
};

var credential = new GoogleAuthorizationCodeFlow(
    new GoogleAuthorizationCodeFlow.Initializer
        {
            ClientSecrets = clientSecrets,
            Scopes = new[] { 
                GoogleScope.ImapAndSmtp.Name, 
                GoogleScope.UserInfoEmailScope.Name}
        });
' VB.NET 

Dim clientID As String = "XXX.apps.googleusercontent.com"
Dim clientSecret As String = "IxBs0g5sdaSDUz4Ea7Ix-Ua"
Dim redirectUri As String = "https://www.example.com/oauth2callback"

Dim clientSecrets = New ClientSecrets With { _
	.ClientId = clientID, _
	.ClientSecret = clientSecret _
}

Dim credential = New GoogleAuthorizationCodeFlow(New GoogleAuthorizationCodeFlow.Initializer With { _
	.ClientSecrets = clientSecrets, _
	.Scopes = {GoogleScope.ImapAndSmtp.Name, GoogleScope.UserInfoEmailScope.Name} _
})

Obtain an OAuth 2.0 access token

Now we’ll create authorization url:

// C#

AuthorizationCodeRequestUrl url = credential
    .CreateAuthorizationCodeRequest(redirectUri);
' VB.NET 

Dim url As AuthorizationCodeRequestUrl = credential _
    .CreateAuthorizationCodeRequest(redirectUri)

Now we need to redirect the client:

// c#

return new RedirectResult(url.Build().ToString());
' VB.NET 

Return New RedirectResult(url.Build().ToString())

At this point user is redirected to Google to authorize the access:

After this step user is redirected back to your website (https://www.example.com/oauth2callback), with code request parameter:
https://www.example.com/oauth2callback?code=4/5Y7M4cARD9hrt0nuKnQa0YgasdbwprRtIIjk4Fus#

// C#

public class OAauth2CallbackController : Controller
{
    public ActionResult Index(string code)
    {
        ...
    }
}
' VB.NET 

Public Class OAauth2CallbackController
    Inherits Controller
    Public Function Index(code As String) As ActionResult
        ...
    End Function
End Class

Following is this callback code. Its purpose is to get a refresh-token and an access-token:

// c#

string authCode = code;

TokenResponse token = await credential.ExchangeCodeForTokenAsync(
    "", 
    authCode, 
    redirectUri, 
    CancellationToken.None);

string accessToken = token.AccessToken;
' VB.NET 

Dim authCode As String = code

Dim token As TokenResponse = Await credential.ExchangeCodeForTokenAsync( _
    "",  _
    authCode,  _
    redirectUri,  _
    CancellationToken.None)

Dim accessToken As String = token.AccessToken

An access token is usually valid for a maximum of one hour, and allows you to access the user’s data. You also received a refresh token. A refresh token can be used to request a new access token once the previous expired.

Access IMAP/SMTP server

Finally we’ll ask Google for user’s email and use LoginOAUTH2 method to access Gmail’s IMAP server:

// c#

GoogleApi api = new GoogleApi(accessToken);
string user = api.GetEmail();

using (Imap imap = new Imap())
{
    imap.ConnectSSL("imap.gmail.com");
    imap.LoginOAUTH2(user, accessToken);

    imap.SelectInbox();
    List<long> uids = imap.Search(Flag.Unseen);

    foreach (long uid in uids)
    {
        var eml = imap.GetMessageByUID(uid);
        IMail email = new MailBuilder().CreateFromEml(eml);
        Console.WriteLine(email.Subject);
    }
    imap.Close();
}
' VB.NET 

Dim api As New GoogleApi(accessToken)
Dim user As String = api.GetEmail()

Using imap As New Imap()
	imap.ConnectSSL("imap.gmail.com")
	imap.LoginOAUTH2(user, accessToken)

	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 email As IMail = New MailBuilder().CreateFromEml(eml)
		Console.WriteLine(email.Subject)
	Next
	imap.Close()
End Using

Refreshing access token

An access token is usually short lived and valid for a maximum of one hour. The main reason behind this is security and prevention of replay attacks. This means that for long-lived applications you need to refresh the access token.

Your refresh token will be sent only once – don’t loose it!

We recommend storing entire TokenResponse object received from GoogleAuthorizationCodeFlow.ExchangeCodeForTokenAsync method call. This object contains both: refresh token and access token, along with its expiration time.

The process of refreshing access token is simple:

// c#

TokenResponse refreshed = await credential.RefreshTokenAsync(
    "", 
    token.RefreshToken, 
    CancellationToken.None);
' VB.NET 

Dim refreshed As TokenResponse = Await credential.RefreshTokenAsync( _
    "",  _
    token.RefreshToken,  _
    CancellationToken.None)

The post OAuth 2.0 with Gmail over IMAP for web applications first appeared on Blog | Limilabs.

]]>
OAuth 2.0 with Gmail over IMAP for installed applications (DotNetOpenAuth) https://www.limilabs.com/blog/oauth2-gmail-imap-installed-applications-dotnetopenauth Mon, 13 Mar 2017 04:00:42 +0000 https://www.limilabs.com/blog/?p=5278 Consider using Google.Apis version for installed applications instead of DotNetOpenAuth version. OAuth is an open protocol to allow secure API authorization in a simple and standard method from desktop and web applications. This article describes using OAuth 2.0 to access Gmail IMAP and SMTP servers using .NET IMAP component in installed applications scenario. You can […]

The post OAuth 2.0 with Gmail over IMAP for installed applications (DotNetOpenAuth) first appeared on Blog | Limilabs.

]]>
Consider using Google.Apis version for installed applications instead of DotNetOpenAuth version.

OAuth is an open protocol to allow secure API authorization in a simple and standard method from desktop and web applications.

This article describes using OAuth 2.0 to access Gmail IMAP and SMTP servers using .NET IMAP component in installed applications scenario. You can also use OAuth 2.0 for web applications.

DotNetOpenAuth

First download the latest version of DotNetOpenAuth – it’s free, open source library that implements OAuth 2.0: http://www.dotnetopenauth.net

Register Application

Before you can use OAuth 2.0, you must register your application using the Google Developers Console.

At least product name must be specified:

Now create credentials:

After you’ve registered, copy the “Client ID” and “Client secret” values, which you’ll need later:

Now we can define clientID, clientSecret and scope variables, as well as Google OAuth 2.0 server addresses. Scope basically specifies what services we want to have access to. In our case it is user’s email address and IMAP/SMTP access:

const string clientID = "12345.apps.googleusercontent.com";
const string clientSecret = "XXXYYY111";

AuthorizationServerDescription server = new AuthorizationServerDescription
    {
        AuthorizationEndpoint = new Uri("https://accounts.google.com/o/oauth2/auth"),
        TokenEndpoint = new Uri("https://oauth2.googleapis.com/token"),
        ProtocolVersion = ProtocolVersion.V20,
    };
List<string> scope = new List<string>
    {
        GoogleScope.ImapAndSmtp.Name,
        GoogleScope.UserInfoEmailScope.Name
    };

Obtain an OAuth 2.0 access token

As we are using installed applications scenario we’ll use NativeApplicationClient class.

Because of a small issue in DotNetOpenAuth we can not use UserAgentClient directly. NativeApplicationClient inherits UserAgentClient and workarounds this issue. You can find the implementation of NativeApplicationClient on the bottom of this article.

NativeApplicationClient consumer = new NativeApplicationClient(server, clientID, clientSecret);
Uri userAuthorizationUri = consumer.RequestUserAuthorization(scope);

Process.Start(userAuthorizationUri.AbsoluteUri);

We are using Process.Start here, but you can also embed WebBrowser control in your application.

At this point user is redirected to Google to authorize the access:

As OOB addresses are no longer supported, to receive the authorization code using this URL, your application must be listening on the local web server. This is the recommended mechanism for obtaining the authorization code.

When your app receives the authorization response, for best usability it should respond by displaying an HTML page that instructs the user to close the browser and return to your app.

Your application needs to create a server that listens on this local address:

http://127.0.0.1:port or http://[::1]:port or http://localhost:port

Query your platform for the relevant loopback IP address and start an HTTP listener on a random available port. Substitute port with the actual port number your app listens on.

In our example we’ll use http://127.0.0.1/auth2callback address.

After this step user is presented a code that needs to be pasted to your application:

Please note that this code also appears in the title of the browser:

  • It is possible to monitor processes on your machine and act automatically when it is there.
  • If you use embedded WebBrowser control in your application, you can monitor the HTML document title after any redirect.

Following is a code that reads this code and contacts Google to exchange it for a refresh-token and an access-token:

string authCode = Console.ReadLine();

consumer.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(clientSecret);

IAuthorizationState grantedAccess = consumer.ProcessUserAuthorization(authCode);

string accessToken = grantedAccess.AccessToken;

An access token is usually valid for a maximum of one hour, and allows you to access the user’s data. You also received a refresh token. A refresh token can be used to request a new access token once the previous expired.

Access IMAP/SMTP server

Finally we’ll ask Google for user’s email and use LoginOAUTH2 method to access Gmail’s IMAP server:

GoogleApi api = new GoogleApi(accessToken);
string user = api.GetEmail();

using (Imap imap = new Imap())
{
    imap.ConnectSSL("imap.gmail.com");
    imap.LoginOAUTH2(user, accessToken);

    imap.SelectInbox();
    List<long>; uids = imap.Search(Flag.Unseen);

    foreach (long uid in uids)
    {
        var eml = imap.GetMessageByUID(uid);
        IMail email = new MailBuilder().CreateFromEml(eml);
        Console.WriteLine(email.Subject);
    }
    imap.Close();
}

NativeApplicationClient class

The OAuth 2.0 client for use by native applications. It’s main purpose is to build a generic URL containing the auth code, because DotNetOpenAuth library only allows parsing an URL as a method of retrieving the AuthorizationState.

/// <summary>
/// The OAuth2 client for use by native applications.
/// This is a partial implementation which  should be used until
/// the feature has been fully implemented in DotNetOpenAuth.
/// </summary>
public class NativeApplicationClient : UserAgentClient
{
    /// <summary>
    /// Represents a callback URL which points to a special out of band page
    /// used for native OAuth2 authorization. This URL will cause the authorization
    /// code to appear in the title of the window.
    /// </summary>
    /// <remarks>
    /// See http://code.google.com/apis/accounts/docs/OAuth2.html
    /// </remarks>
    public const string OutOfBandCallbackUrl = "http://127.0.0.1/auth2callback";

    /// <summary>
    /// Initializes a new instance of the <see cref="UserAgentClient"/> class.
    /// </summary>
    /// <param name="authorizationServer">The token issuer.</param>
    /// <param name="clientIdentifier">The client identifier.</param>
    /// <param name="clientSecret">The client secret.</param>
    public NativeApplicationClient(
        AuthorizationServerDescription authorizationServer,
        string clientIdentifier,
        string clientSecret)
        : base(authorizationServer, clientIdentifier, clientSecret)
    {
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="UserAgentClient"/> class.
    /// </summary>
    /// <param name="authorizationServer">The token issuer.</param>
    public NativeApplicationClient(
        AuthorizationServerDescription authorizationServer)
        : this(authorizationServer, null, null)
    {
    }

    /// <summary>
    /// Creates the URL which should be used by the user to request the initial
    /// authorization. Uses the default Out-of-band-URI as a callback.
    /// </summary>
    /// <param name="scope">Set of requested scopes</param>
    /// <returns>URI pointing to the authorization server</returns>
    public Uri RequestUserAuthorization(IEnumerable<string> scope)
    {
        var state = new AuthorizationState(scope);
        state.Callback = new Uri(OutOfBandCallbackUrl);
        return RequestUserAuthorization(state, false, null);
    }

    /// <summary>
    /// Uses the provided authorization code to create an authorization state.
    /// </summary>
    /// <param name="authCode">The authorization code for getting an access token.</param>
    /// <param name="authorizationState">The authorization.  Optional.</param>
    /// <returns>The granted authorization, or <c>null</c> if the authorization was null or rejected.</returns>
    public IAuthorizationState ProcessUserAuthorization(
        string authCode,
        IAuthorizationState authorizationState)
    {
        if (authorizationState == null)
        {
            authorizationState = new AuthorizationState(null);
            authorizationState.Callback = new Uri(OutOfBandCallbackUrl);
        }

        // Build a generic URL containing the auth code.
        // This is done here as we cannot modify the DotNetOpenAuth library
        // and the underlying method only allows parsing an URL as a method
        // of retrieving the AuthorizationState.
        string url = "http://example.com/?code=" + authCode;
        return ProcessUserAuthorization(new Uri(url), authorizationState);
    }

    /// <summary>
    /// Uses the provided authorization code to create an authorization state.
    /// </summary>
    /// <param name="authCode">The authorization code for getting an access token.</param>
    /// <returns>The granted authorization, or <c>null</c> if the authorization was null or rejected.</returns>
    public IAuthorizationState ProcessUserAuthorization(string authCode)
    {
        return ProcessUserAuthorization(authCode, null);
    }
};

Refreshing access token

An access token is usually short lived and valid for a maximum of one hour. The main reason behind this is security and prevention of replay attacks. This means that for long-lived applications you need to refresh the access token.

Your refresh token will be sent only once – don’t loose it!

We recommend storing entire IAuthorizationState object received from NativeApplicationClient.ProcessUserAuthorization method call. This object contains both: refresh token and access token, along with its expiration time.

The process of refreshing access token is simple:

IAuthorizationState grantedAccess = ...
consumer.RefreshAuthorization(grantedAccess, TimeSpan.FromMinutes(20));

In the example above the access token will not be refreshed if its remaining lifetime exceeds 20 minutes.

Retrieving lost refresh token

When your application receives a refresh token, it is important to store that refresh token for future use. If your application loses the refresh token, it will have to re-prompt the user for consent before obtaining another refresh token.

You’ll need to add approval_prompt=force to your parameters:

AuthorizationServerDescription authServer = new AuthorizationServerDescription
{
    AuthorizationEndpoint =
        new Uri("https://accounts.google.com/o/oauth2/auth?access_type=offline&approval_prompt=force"),
    ...
};

The post OAuth 2.0 with Gmail over IMAP for installed applications (DotNetOpenAuth) first appeared on Blog | Limilabs.

]]>
Logging in Mail.dll email client https://www.limilabs.com/blog/logging-in-mail-dll Mon, 01 Aug 2016 16:03:54 +0000 http://www.limilabs.com/blog/?p=1478 This article provides a comprehensive guide on how to perform logging within the Mail.dll .NET email client. It outlines step-by-step instructions for implementing robust logging mechanisms, enhancing troubleshooting capabilities, and tracking email communication effectively. By following the methods detailed in the article, VisualBasic and C# developers can seamlessly integrate logging features into their applications, gaining […]

The post Logging in Mail.dll email client first appeared on Blog | Limilabs.

]]>
This article provides a comprehensive guide on how to perform logging within the Mail.dll .NET email client. It outlines step-by-step instructions for implementing robust logging mechanisms, enhancing troubleshooting capabilities, and tracking email communication effectively.

By following the methods detailed in the article, VisualBasic and C# developers can seamlessly integrate logging features into their applications, gaining valuable insights into the Imap, Pop3 and Smtp clients behavior and facilitating streamlined debugging processes.

To enable logging for all Mail.dll .NET clients (Imap, Pop3, Smtp) you only need to add the following line before you connect:

// C# version:

Limilabs.Mail.Log.Enabled = true;
' VB.NET version:

Limilabs.Mail.Log.Enabled = True

You can observe the log output by:

  • looking at the Visual Studio’s output window (View/Output/’Show output from’: Debug)
  • subscribing to Log.WriteLine event
  • defining custom listeners using your application’s config file (App.config or Web.config)
  • using log4net

This is how the log looks like in the Visual Studio’s output window:

For regular .NET framework you can also enable logging using your application’s config file (App.config, Web.config):

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.diagnostics>

      <switches>
        <add name="Mail.dll" value="Verbose" />
      </switches>

    </system.diagnostics>
</configuration>

Logging with log4net

If you are using log4net, Mail.dll is going to use log4net instead of standard .NET System.Net.TraceSource class. Please refer to log4net manual on how to capture log entries.

Mail.dll uses logger called “Mail.dll”

_logger = LogManager.GetLogger("Mail.dll")

and level Info _logger.Info(message) to log information.

Please remember that even when using log4net, you need to enable logging by setting “Limilabs.Mail.Log.Enabled = True” or by setting Mail.dll trace switch in the config file (App.config, Web.config) to Verbose as shown above.

Log.WriteLine

Limilabs.Mail.Log class exposes WriteLine event. You can use that event to subscribe your own logging library in both .NET and .NET framework.

// C#

Limilabs.Mail.Log.WriteLine += Console.WriteLine;
' VB.NET

AddHandler Limilabs.Mail.Log.WriteLine, AddressOf Console.WriteLine

Log to file (.NET framework)

You’ll need to define a TextWriterTraceListener that writes to a file and connect it with Mail.dll trace source. The easiest solution is to modify your application’s config file App.config or Web.config accordingly:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.diagnostics>

        <trace autoflush="true"/>

        <switches>
            <add name="Mail.dll" value="Verbose"/>
        </switches>

        <sources>
            <source name="Mail.dll">
                <listeners>
                    <add name="MailLogFile"/>
                </listeners>
            </source>
        </sources>

        <sharedListeners>
            <add
                name="MailLogFile"
                type="System.Diagnostics.TextWriterTraceListener"
                initializeData="c:\folder-with-write-access\mail.log"/>
        </sharedListeners>

    </system.diagnostics>
</configuration>

The post Logging in Mail.dll email client first appeared on Blog | Limilabs.

]]>