SMTP | Blog | Limilabs https://www.limilabs.com/blog Using Limilabs .net components Wed, 29 Jan 2025 08:27:03 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.5 Authenticate using Gmail’s App Passwords to IMAP, POP3 and SMTP https://www.limilabs.com/blog/using-app-passwords-with-gmail Thu, 27 Jul 2023 14:45:20 +0000 https://www.limilabs.com/blog/?p=5552 An app password is a 16-digit passcode that serves as an alternative authentication method, granting Mail.dll .NET IMAP, POP3 or SMTP client access to your Gmail Account with the same level of security as using a regular password. Your primary password can’t be used to authenticate anymore, because of Gmail’s secure access policies. Gmail introduced […]

The post Authenticate using Gmail’s App Passwords to IMAP, POP3 and SMTP first appeared on Blog | Limilabs.

]]>
An app password is a 16-digit passcode that serves as an alternative authentication method, granting Mail.dll .NET IMAP, POP3 or SMTP client access to your Gmail Account with the same level of security as using a regular password.

Your primary password can’t be used to authenticate anymore, because of Gmail’s secure access policies. Gmail introduced app passwords as a means to enhance account security.

This unique 16-digit passcode acts as a one-time key, eliminating the need to share your primary Google Account password with the application.

By generating an app password, users can rest assured that their sensitive credentials remain protected, and the Mail.dll .NET client can seamlessly interact with your Gmail Account, enabling efficient email management without compromising security.

OAuth 2.0 alternative

In many cases OAuth 2.0 is a better, but more complex option to access IMAP, POP3 and SMTP:

Enable 2-Step verification

Gmail’s App passwords can only be used with accounts that have 2-Step Verification turned on.

First go to your Google Account and on the left navigation panel, choose Security.

On the “Signing in to Google” panel:

  • Make sure I that 2-Step Verification is turned on
  • Finally choose App Passwords (you may need to scroll down a bit):

Generate new App password

On the “App password” screen select device and choose the device you’re using.

Then click Generate to create a new password:

New password will be generated – ready to use with Mail.dll clients.

Remember to copy the new password, because it won’t be displayed again:

Now you are ready to log in to your IMAP, SMTP, POP3 account using your email and the generated password (instead of your email’s primary password).

Authenticate using IMAP component

Mail.dll .NET email library provides a secure and efficient way to access email accounts, manage and parse email messages. It is a powerful .NET library that simplifies the implementation of IMAP functionality in various .NET applications.

We’ll use IMAP .NET client in an example below. Note that same password can be used for POP3 .NET client and SMTP .NET clients in exactly the same way.

Remember not to include any spaces when coping the app password to IMAP client’s authentication method, because authentication will fail.

C# code:

using (Imap client = new Imap()) 
{ 
    client.ConnectSSL("imap.gmail.com"); 
    client.UseBestLogin("XXXXX@gmail.com", "kvrcdzlicajaupje"); 

    // ... 

    client.Close(); 
}

VB.NET code:

Using imap As New Imap 
    imap.ConnectSSL("imap.gmail.com") 
    imap.UseBestLogin("XXXXX@gmail.com", "kvrcdzlicajaupje") 

    ' ... 

    imap.Close() 
End Using

Suggested reading


Get Mail.dll

The post Authenticate using Gmail’s App Passwords to IMAP, POP3 and SMTP first appeared on Blog | Limilabs.

]]>
OAuth 2.0 client credential flow with Office365/Exchange IMAP/POP3/SMTP https://www.limilabs.com/blog/oauth2-client-credential-flow-office365-exchange-imap-pop3-smtp Fri, 08 Jul 2022 10:23:20 +0000 https://www.limilabs.com/blog/?p=6211 In this series:   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 with Office365/Exchange IMAP/POP3/SMTP This article shows how to implement OAuth 2.0 client credential flow to access Office365 via IMAP, POP3 […]

The post OAuth 2.0 client credential flow with Office365/Exchange IMAP/POP3/SMTP first appeared on Blog | Limilabs.

]]>
In this series:

 

This article shows how to implement OAuth 2.0 client credential flow to access Office365 via IMAP, POP3 using Mail.dll .net email client. This flow is particularly useful for daemon/service apps that need to monitor certain mailboxes, without any user interaction.

Make sure IMAP/POP3 is enabled for your organization and mailbox:
Enable IMAP/POP3/SMTP in Office 365

Register your application in Azure Portal, here’s a detailed guide how to do that:
https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app

Add permissions to your application in the API permissions / Add a permission wizard:

Select APIs my organization uses and search for Office 365 Exchange Online:

…then click Application permissions:

For POP access, choose the POP.AccessAsApp permission.
For IMAP access, choose the IMAP.AccessAsApp permission.
For SMTP access, choose the SMTP.SendAsApp permission.

Remember to Grant admin consent:

Create an application secret in Certificates & secrets panel by clicking ‘New client secret’ button:

Note the secret value as it is shown only during creation.

Use Windows PowerShell on your machine to Register service principals in Exchange.

Set execution policy first:

Set-ExecutionPolicy RemoteSigned

Install ExchangeOnlineManagement module:

Install-Module -Name ExchangeOnlineManagement 
Import-Module ExchangeOnlineManagement 

Connect and log-in as an administrator (you’ll be prompted for password):

Connect-ExchangeOnline
 -UserPrincipalName your-admin-account@your-domain.onmicrosoft.com

For Exchange running in hybrid mode log-in using following code:

$lc = Get-Credential
Connect-ExchangeOnline -Credential $lc

Create service principal

New-ServicePrincipal
 -AppId <APPLICATION_ID>
 -ServiceId <OBJECT_ID> 
 [-Organization <ORGANIZATION_ID>]

You can find ApplicationId and ObjectId in Enterprise applications in your application’s Overview panel:

Make sure you use the Object ID from the Enterprise Application

Do not use the value from the App Registration screen. 

In our case:

New-ServicePrincipal
 -AppId 061851f7-08c0-40bf-99c1-ebd489c11f16
 -ServiceId 4352fc11-5c2f-4b0b-af40-447ff10664e8

Note: If you still get an error running the New-ServicePrincipal cmdlet after you perform these steps, it is likely due to the fact that the user doesn’t have enough permissions in Exchange online to perform the operation. By default this cmdlet is available to users assigned the Role Management role

Add permissions to a specific mailbox:

Add-MailboxPermission
 -Identity "<USER@your-domain.onmicrosoft.com>"
 -User <OBJECT_ID>
 -AccessRights FullAccess

In our case:

Add-MailboxPermission
 -Identity "AdeleV@your-domain.onmicrosoft.com"
 -User 4352fc11-5c2f-4b0b-af40-447ff10664e8
 -AccessRights FullAccess

Shared mailboxes

You need to use Add-MailboxPermission for every shared mailbox you need access to:

Add-MailboxPermission
 -Identity "shared@your-domain.onmicrosoft.com"
 -User <OBJECT_ID>
 -AccessRights FullAccess

Let’s code

Use Microsoft Authentication Library for .NET (MSAL.NET) nuget package to obtain an access token:
https://www.nuget.org/packages/Microsoft.Identity.Client/

// C#

string clientId = "Application (client) ID";    // 061851f7-...
string tenantId = "Directory (tenant) ID";
string clientSecret = "Client secret value";

string userName = "Username/email for mailbox";    // AdeleV@...

var app = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithTenantId(tenantId)
    .WithClientSecret(clientSecret)
    .Build();

string[] scopes = new string[] { 
    "https://outlook.office365.com/.default" 
};
' VB.NET

Dim clientId As String = "Application (client) ID" ' 061851f7-...
Dim tenantId As String = "Directory (tenant) ID"
Dim clientSecret As String = "Client secret value"

Dim userName As String = "Username/email for mailbox"  'AdeleV@...

Dim app = ConfidentialClientApplicationBuilder.Create(clientId) _
    .WithTenantId(tenantId) _
    .WithClientSecret(clientSecret) _
    .Build()

Dim scopes As String() = New String() { _
    "https://outlook.office365.com/.default" _
}

Now acquire an access token:

// C#

var result = await app.AcquireTokenForClient(scopes)
    .ExecuteAsync();

string accessToken = result.AccessToken;
' VB.NET

Dim result = Await app.AcquireTokenForClient(scopes).ExecuteAsync()
Dim accessToken As String = result.AccessToken

Finally you can connect using IMAP/POP3, authenticate and download user’s emails:

// C#

using (Imap client = new Imap())
{
    client.ConnectSSL("outlook.office365.com");
    client.LoginOAUTH2(userName, accessToken);
 
    client.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;
   }

   client.Close();
} 
' VB.NET

Using client As Imap = New Imap()
    client.ConnectSSL("outlook.office365.com")
    client.LoginOAUTH2(userName, accessToken)

    client.SelectInbox()

    Dim uids As List(Of Long) = imap.Search(Flag.Unseen)
    For Each uid As Long In uids
        Dim email As IMail = New MailBuilder() _
            .CreateFromEml(imap.GetMessageByUID(uid))
        Dim subject As String = email.Subject
    Next

    client.Close()
End Using

SMTP

Microsoft started supporting client credential flow and SMTP recently.

SMTP requires SMTP.SendAsApp permission added to your AD application.

All other OAuth flows (webdesktoppassword grantdevice) support SMTP client access as well.

For SMTP non-OAuth2 access:

SMTP AUTH will still be available when Basic authentication is permanently disabled on October 1, 2022.” (https://docs.microsoft.com/en-us/exchange/clients-and-mobile-in-exchange-online/deprecation-of-basic-authentication-exchange-online)

However Microsoft disables SMTP AUTH in all tenants in which it’s not being used.

Here’s how to enable SMTP AUTH:
https://learn.microsoft.com/en-us/exchange/clients-and-mobile-in-exchange-online/authenticated-client-smtp-submission

Additionally Exchange Online will permanently remove support for Basic authentication with SMTP submission in September 2025:
https://techcommunity.microsoft.com/blog/exchange/exchange-online-to-retire-basic-auth-for-client-submission-smtp-auth/4114750

Troubleshooting

1. Start with PowerShell commands:

Get-ServicePrincipal
Get-MailboxPermission -Identity "AdeleV@your-domain.onmicrosoft.com"

You should see following results:

Make sure the ServiceId is the same as the Object ID on the Enterprise Application screen (do not use the value from the App Registration screen)

Make sure the AppId is the same as the Application ID on the Enterprise Application screen

2. Check if you can connect to this account using IMAP and regular interactive flow:

https://www.limilabs.com/blog/office-365-oauth-2-0-imap-pop3-email-client-connectivity-tools

This proves you have IMAP access properly configured.

3. Check if you added correct permissions and have granted Admin consent for your domain.

4. Usually people use incorrect client/tenant ids/secrets – double check every single value you enter (also for additional spaces).

5. You may need to wait 20-30 minutes for some changes to take effect (it really may take this long!).

Additional links

https://docs.microsoft.com/en-us/powershell/exchange/exchange-online-powershell-v2?view=exchange-ps#install-and-maintain-the-exo-v2-module
https://docs.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth#use-client-credentials-grant-flow-to-authenticate-imap-and-pop-connections


Get Mail.dll

The post OAuth 2.0 client credential flow with Office365/Exchange IMAP/POP3/SMTP first appeared on Blog | Limilabs.

]]>
OAuth 2.0 web flow with Office365/Exchange IMAP/POP3/SMTP https://www.limilabs.com/blog/oauth2-web-flow-office365-exchange-imap-pop3-smtp Wed, 30 Mar 2022 10:04:28 +0000 https://www.limilabs.com/blog/?p=6049 In this series:   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 with Office365/Exchange IMAP/POP3/SMTP This article shows how to implement OAuth 2.0 web flow to access Office365 via IMAP, POP3 or […]

The post OAuth 2.0 web flow with Office365/Exchange IMAP/POP3/SMTP first appeared on Blog | Limilabs.

]]>
In this series:

 

This article shows how to implement OAuth 2.0 web flow to access Office365 via IMAP, POP3 or SMTP using Mail.dll .net email client.

Make sure IMAP/POP3/SMTP is enabled for your organization and mailbox:
Enable IMAP/POP3/SMTP in Office 365

Register your application in Azure Portal, here’s a detailed guide how to do that:
https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app

RedirectUri

Add an authentication redirect uri to your application:

Then you need to apply correct API permissions and grant the admin consent for your domain.

In the API permissions / Add a permission wizard, select Microsoft Graph and then Delegated permissions to find the following permission scopes listed:

  • offline_access
  • email
  • IMAP.AccessAsUser.All
  • POP.AccessAsUser.All
  • SMTP.Send

Remember to Grant admin consent:

Create an app secret and remember its value:

Use Microsoft Authentication Library for .NET (MSAL.NET) nuget package to obtain an access token:
https://www.nuget.org/packages/Microsoft.Identity.Client/

string clientId = "Application (client) ID";
string tenantId = "Directory (tenant) ID";
string clientSecret = "Client secret value";

// for @outlook.com/@hotmail accounts instead of setting .WithTenantId use:
// .WithAuthority(AadAuthorityAudience.PersonalMicrosoftAccount)

var app = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithTenantId(tenantId)
    .WithClientSecret(clientSecret)
    .WithRedirectUri("http://localhost/myapp/")
    .Build();
// This allows saving access/refresh tokens to some storage
TokenCacheHelper.EnableSerialization(app.UserTokenCache);

var scopes = new string[] 
{
    "offline_access",
    "email",
    "https://outlook.office.com/IMAP.AccessAsUser.All",
    "https://outlook.office.com/POP.AccessAsUser.All",
    "https://outlook.office.com/SMTP.Send",
};

In addition, you should request offline_access scope. When a user approves the offline_access scope, your app can receive refresh tokens from the Microsoft identity platform token endpoint. Refresh tokens are long-lived. Your app can get new access tokens as older ones expire.

Now try finding account by an identifier (it will be null on first access) in MSAL cache:

string userName;
string accessToken;

string identifier = null;

var account = await app.GetAccountAsync(identifier);

try
{
    AuthenticationResult refresh = await app
        .AcquireTokenSilent(scopes, account)
        .WithForceRefresh(true)
        .ExecuteAsync();

    userName = refresh.Account.Username;
    accessToken = refresh.AccessToken;

}
catch (MsalUiRequiredException e)
{
    // no token cache entry - perform authentication:

    Uri msUri = await app
        .GetAuthorizationRequestUrl(scopes)
        .ExecuteAsync();

    // Add a redirect code to the above 
    // Microsoft authentication uri and end this request.
}

On the first run user will be redirected to the msUri and will see a Microsoft login screen, with option to log-in, using a known account and granting access to the app (if needed):

After successful authentication Microsoft will redirect user’s browser back to your application – to the app’s RedirectUri (in our case http://localhost/MyApp/):

http://localhost/myapp/?code=0.Aa…AA&client_info=ey…I0In0&session_state=4dd….4488c8#

Controller responsible for handling this request should retrieve code parameter

string code = "get from url after redirect";

AuthenticationResult result = await app
    .AcquireTokenByAuthorizationCode(scopes, code)
    .ExecuteAsync();

string identifier = result.Account.HomeAccountId.Identifier;
string userName = result.Account.Username;
string accessToken = result.AccessToken;

Finally you can connect using IMAP/POP3/SMTP, authenticate and download user’s emails:

using (Imap client = new Imap())
{
    client.ConnectSSL("outlook.office365.com");
    client.LoginOAUTH2(userName, accessToken);
 
    client.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;
   }

    client.Close();
} 

Any organization and personal accounts

To access accounts from any organization and personal accounts as well, you need to specify correct account types when you create the App in your AD:

Additionally you need to use:    

    .WithAuthority(
        AadAuthorityAudience.AzureAdAndPersonalMicrosoftAccount
        )

instead of

    .WithTenantId(tenantId)

when creating the app:

var app = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithAuthority(
        AadAuthorityAudience.AzureAdAndPersonalMicrosoftAccount
        )
    .WithClientSecret(clientSecret)
    .WithRedirectUri("http://localhost/myapp/")
    .Build();

Token serialization

Below is a simple implementation that saves MSAL token cache to file:

static class TokenCacheHelper
{
    public static void EnableSerialization(ITokenCache tokenCache)
    {
        tokenCache.SetBeforeAccess(BeforeAccessNotification);
        tokenCache.SetAfterAccess(AfterAccessNotification);
    }

    private static readonly string _fileName = "msalcache.bin3";

    private static readonly object _fileLock = new object();


    private static void BeforeAccessNotification(TokenCacheNotificationArgs args)
    {
        lock (_fileLock)
        {
            byte[] data = null;
            if (File.Exists(_fileName))
                data = File.ReadAllBytes(_fileName);
            args.TokenCache.DeserializeMsalV3(data);
        }
    }

    private static void AfterAccessNotification(TokenCacheNotificationArgs args)
    {
        if (args.HasStateChanged)
        {
            lock (_fileLock)
            {
                byte[] data = args.TokenCache.SerializeMsalV3();
                File.WriteAllBytes(_fileName, data);
            }
        }
    }
};

Please note that most likely you should store this cache in an encrypted form in some kind of a database.
Consider using MSAL token serialization implementations available here:

https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-net-token-cache-serialization


Get Mail.dll

The post OAuth 2.0 web flow with Office365/Exchange IMAP/POP3/SMTP first appeared on Blog | Limilabs.

]]>
OAuth 2.0 device flow with Office365/Exchange IMAP/POP3/SMTP https://www.limilabs.com/blog/oauth2-device-flow-office365-exchange-imap-pop3-smtp Mon, 28 Mar 2022 13:18:36 +0000 https://www.limilabs.com/blog/?p=5988 In this series:   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 with Office365/Exchange IMAP/POP3/SMTP This article shows how to implement OAuth 2.0 device flow to access Office365 via IMAP, POP3 or […]

The post OAuth 2.0 device flow with Office365/Exchange IMAP/POP3/SMTP first appeared on Blog | Limilabs.

]]>
In this series:

 

This article shows how to implement OAuth 2.0 device flow to access Office365 via IMAP, POP3 or SMTP using Mail.dll .net email client.

Device flow allows operator/administrator to authenticate your application on a different machine than your application is installed.

Make sure IMAP/POP3/SMTP is enabled for your organization and mailbox:
Enable IMAP/POP3/SMTP in Office 365

Register your application in Azure Portal, here’s a detailed guide how to do that:
https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app

Then you need to apply correct API permissions and grant the admin consent for your domain.

In the API permissions / Add a permission wizard, select Microsoft Graph and then Delegated permissions to find the following permission scopes listed:

  • offline_access
  • email
  • IMAP.AccessAsUser.All
  • POP.AccessAsUser.All
  • SMTP.Send

Remember to Grant admin consent:

Use Microsoft Authentication Library for .NET (MSAL.NET) nuget package to obtain an access token:
https://www.nuget.org/packages/Microsoft.Identity.Client/

string clientId = "Application (client) ID";
string tenantId = "Directory (tenant) ID";

IPublicClientApplication app = PublicClientApplicationBuilder
    .Create(clientId)
    .WithTenantId(tenantId)
    .Build();
// This allows saving access/refresh tokens to some storage
TokenCacheHelper.EnableSerialization(app.UserTokenCache);

var scopes = new string[] 
{
    "offline_access",
    "email",
    "https://outlook.office.com/IMAP.AccessAsUser.All",
    "https://outlook.office.com/POP.AccessAsUser.All",
    "https://outlook.office.com/SMTP.Send",
};

Now acquire an access token and a user name:

string userName;
string accessToken;

var account = (await app.GetAccountsAsync()).FirstOrDefault();
try
{
    AuthenticationResult refresh = await app
        .AcquireTokenSilent(scopes, account)
        .ExecuteAsync();

    userName = refresh.Account.Username;
    accessToken = refresh.AccessToken;
}
catch (MsalUiRequiredException e)
{
    var acquire = await app.AcquireTokenWithDeviceCode(
        scopes, 
        callback=>
    {
        // Write url and code to logs so the operator can react:
        Console.WriteLine(callback.VerificationUrl);
        Console.WriteLine(callback.UserCode);

        // This happens on the first run, manually,
        //  on the operator machine.
        // The code below code is only to illustrate 
        // the operator opening browser on his machine,
        // opening the url and using the code 
        // (extracted from the application logs)
        // to authenticate the app.
        System.Diagnostics.Process.Start(
            new ProcessStartInfo(callback.VerificationUrl) 
                        { UseShellExecute = true }
            );

        return Task.CompletedTask;
    }).ExecuteAsync();

    userName = acquire.Account.Username;
    accessToken = acquire.AccessToken;
}

AcquireTokenWithDeviceCode call waits until operator/administrator gives consent by going to VerificationUrl, entering UserCode and authenticating – this usually happens on a different machine than the application is installed.

Finally your app will exit AcquireTokenWithDeviceCode method and connect using IMAP/POP3/SMTP, authenticate and download emails:

using (Imap client = new Imap())
{
    client.ConnectSSL("outlook.office365.com");
    client.LoginOAUTH2(userName, accessToken);
 
    client.SelectInbox();

    // ...

    client.Close();
} 

You can find more details on this flow here:

https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-device-code

Token serialization

Below is a simple implementation that saves MSAL token cache to file. Please note that most likely you should store this cache in an encrypted form:

static class TokenCacheHelper
{
    public static void EnableSerialization(ITokenCache tokenCache)
    {
        tokenCache.SetBeforeAccess(BeforeAccessNotification);
        tokenCache.SetAfterAccess(AfterAccessNotification);
    }

    private static readonly string _fileName = "msalcache.bin3";

    private static readonly object _fileLock = new object();


    private static void BeforeAccessNotification(TokenCacheNotificationArgs args)
    {
        lock (_fileLock)
        {
            byte[] data = null;
            if (File.Exists(_fileName))
                data = File.ReadAllBytes(_fileName);
            args.TokenCache.DeserializeMsalV3(data);
        }
    }

    private static void AfterAccessNotification(TokenCacheNotificationArgs args)
    {
        if (args.HasStateChanged)
        {
            lock (_fileLock)
            {
                byte[] data = args.TokenCache.SerializeMsalV3();
                File.WriteAllBytes(_fileName, data);
            }
        }
    }
};

More details on MSAL token serialization are available here:

https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-net-token-cache-serialization

Extending Sign-in frequency with policies

You can extend how often operator needs to re-authenticate the application up to 1 year:

Side note: Have in mind that similarly a client credential flow requires a client secret which is valid for 2 years maximum.


Get Mail.dll

The post OAuth 2.0 device flow with Office365/Exchange IMAP/POP3/SMTP first appeared on Blog | Limilabs.

]]>
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.

]]>
OAuth 2.0 password grant with Office365/Exchange IMAP/POP3/SMTP https://www.limilabs.com/blog/oauth2-password-grant-office365-exchange-imap-pop3-smtp Thu, 19 Nov 2020 13:47:47 +0000 https://www.limilabs.com/blog/?p=5768 In this series:   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 with Office365/Exchange IMAP/POP3/SMTP This article shows how to implement OAuth 2.0 password grant flow to access Office365 via IMAP, POP3 […]

The post OAuth 2.0 password grant with Office365/Exchange IMAP/POP3/SMTP first appeared on Blog | Limilabs.

]]>
In this series:

 

This article shows how to implement OAuth 2.0 password grant flow to access Office365 via IMAP, POP3 or SMTP using Mail.dll .NET email client.

Enable email protocols

Make sure IMAP/POP3/SMTP is enabled for your organization and mailbox:
Enable IMAP/POP3/SMTP in Office 365

Disable MFA for account

Password grant flow requires Multi-Factor Authentication (MFA) to be disabled for this mailbox – make also sure there are no Active Directory policies that match this account and require MFA (you can of course have policies that match all other accounts).

Go to Microsoft365 admin center. Select Setup on the left menu and in the Sign-in and security section select Configure multifactor authentication (MFA):

You can use per-user MFA or AD policies.

Register and configure application

Register your application in Azure Portal, here’s a detailed guide how to do that:
https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app

Enable additional flows:

Then you need to apply correct API permissions and grant the admin consent for your domain.

In the API permissions / Add a permission wizard, select Microsoft Graph and then Delegated permissions to find the following permission scopes listed:

  • offline_access
  • email
  • IMAP.AccessAsUser.All
  • POP.AccessAsUser.All
  • SMTP.Send

Remember to Grant admin consent:

Obtain OAuth 2.0 token

Use Microsoft Authentication Library for .NET (MSAL.NET) nuget package to obtain an access token:
https://www.nuget.org/packages/Microsoft.Identity.Client/

string clientId = "Application (client) ID";
string tenantId = "Directory (tenant) ID";

string userEmail = "Username for mailbox";
string userPassword = "Password for that user";

IPublicClientApplication app = PublicClientApplicationBuilder
    .Create(clientId)
    .WithTenantId(tenantId)
    .Build();

var scopes = new string[] 
{
    "offline_access",
    "email",
    "https://outlook.office.com/IMAP.AccessAsUser.All",
    "https://outlook.office.com/POP.AccessAsUser.All",
    "https://outlook.office.com/SMTP.Send",
};

Now acquire an access token and a user name:

string userName;
string accessToken;

var account = (await app.GetAccountsAsync()).FirstOrDefault();

try
{
    AuthenticationResult refresh = await app
        .AcquireTokenSilent(scopes, account)
        .ExecuteAsync();

    userName = refresh.Account.Username;
    accessToken = refresh.AccessToken;
}
catch (MsalUiRequiredException e)
{
    SecureString securePassword = new SecureString();
    foreach (char c in userPassword)
    {
        securePassword.AppendChar(c);
    }

    var result = await app.AcquireTokenByUsernamePassword(
        scopes, 
        userEmail, 
        securePassword).ExecuteAsync();

    userName = result.Account.Username;
    accessToken = result.AccessToken;
}

Install Mail.dll email library

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 and process emails

Finally you can connect using IMAP/POP3/SMTP, authenticate and download user’s emails:

using (Imap client = new Imap())
{
    client.ConnectSSL("outlook.office365.com");
    client.LoginOAUTH2(userName, accessToken);
 
    client.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;
   }

    client.Close();
} 


Get Mail.dll

The post OAuth 2.0 password grant with Office365/Exchange IMAP/POP3/SMTP first appeared on Blog | Limilabs.

]]>
OAuth 2.0 with Office365/Exchange IMAP/POP3/SMTP https://www.limilabs.com/blog/oauth2-office365-exchange-imap-pop3-smtp Tue, 23 Jun 2020 16:24:21 +0000 https://www.limilabs.com/blog/?p=5649 In this series:   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 with Office365/Exchange IMAP/POP3/SMTP This article shows how to implement OAuth 2.0 desktop flow to access Office365 via IMAP, POP3 or […]

The post OAuth 2.0 with Office365/Exchange IMAP/POP3/SMTP first appeared on Blog | Limilabs.

]]>
In this series:

 

This article shows how to implement OAuth 2.0 desktop flow to access Office365 via IMAP, POP3 or SMTP using Mail.dll .net email client.

Make sure IMAP/POP3/SMTP is enabled for your organization and mailbox:
Enable IMAP/POP3/SMTP in Office 365

Register your application in Azure Portal, here’s a detailed guide how to do that:
https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app

Remember to add authentication entries (localhost is needed for .net core):

RedirectUri

.NET desktop: https://login.microsoftonline.com/common/oauth2/nativeclient
.NET core/.NET 5,6,7+: http://localhost
ASP.NET: your application custom url

Then you need to apply correct API permissions and grant the admin consent for your domain.

In the API permissions / Add a permission wizard, select Microsoft Graph and then Delegated permissions to find the following permission scopes listed:

  • offline_access
  • email
  • IMAP.AccessAsUser.All
  • POP.AccessAsUser.All
  • SMTP.Send

Remember to Grant admin consent:

Use Microsoft Authentication Library for .NET (MSAL.NET) nuget package to obtain an access token:
https://www.nuget.org/packages/Microsoft.Identity.Client/

string clientId = "Application (client) ID";
string tenantId = "Directory (tenant) ID";

// for @outlook.com/@hotmail accounts instead of setting .WithTenantId use:
// .WithAuthority(AadAuthorityAudience.PersonalMicrosoftAccount)

var app = PublicClientApplicationBuilder
                .Create(clientId)
                .WithTenantId(tenantId)
                .WithDefaultRedirectUri()
                .Build();
// This allows saving access/refresh tokens to some storage
TokenCacheHelper.EnableSerialization(app.UserTokenCache);

var scopes = new string[] 
{
    "offline_access",
    "email",
    "https://outlook.office.com/IMAP.AccessAsUser.All",
    "https://outlook.office.com/POP.AccessAsUser.All",
    "https://outlook.office.com/SMTP.Send",
};

In addition, you should request offline_access scope. When a user approves the offline_access scope, your app can receive refresh tokens from the Microsoft identity platform token endpoint. Refresh tokens are long-lived. Your app can get new access tokens as older ones expire.

Now acquire the access token and user email address:

string userName;
string accessToken;

var account = (await app.GetAccountsAsync()).FirstOrDefault();

try
{
    AuthenticationResult refresh = await app
        .AcquireTokenSilent(scopes, account)
        .ExecuteAsync();

    userName = refresh.Account.Username;
    accessToken = refresh.AccessToken;
}
catch (MsalUiRequiredException e)
{
    var result = await app.AcquireTokenInteractive(scopes)
        .ExecuteAsync();

    userName = result.Account.Username;
    accessToken = result.AccessToken;
}

On the first run user will see a Microsoft login screen, with option to log-in, using a known account and granting access to the app (if needed):

Finally you can connect using IMAP/POP3/SMTP, authenticate and download user’s emails:

using (Imap client = new Imap())
{
    client.ConnectSSL("outlook.office365.com");
    client.LoginOAUTH2(userName, accessToken);
 
    client.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;
   }

    client.Close();
} 

Any organization and personal accounts

To access accounts from any organization and personal accounts as well, you need to specify correct account types when you create the App in your AD:

Additionally you need to use:    

    .WithAuthority(
        AadAuthorityAudience.AzureAdAndPersonalMicrosoftAccount
        )

instead of

    .WithTenantId(tenantId)

when creating the app:

 var app = PublicClientApplicationBuilder
    .Create(clientId)
    .WithAuthority(
        AadAuthorityAudience.AzureAdAndPersonalMicrosoftAccount
        )
    .WithDefaultRedirectUri()
    .Build();

Token serialization

Below is a simple implementation that saves MSAL token cache to file:

static class TokenCacheHelper
{
    public static void EnableSerialization(ITokenCache tokenCache)
    {
        tokenCache.SetBeforeAccess(BeforeAccessNotification);
        tokenCache.SetAfterAccess(AfterAccessNotification);
    }

    private static readonly string _fileName = "msalcache.bin3";

    private static readonly object _fileLock = new object();


    private static void BeforeAccessNotification(TokenCacheNotificationArgs args)
    {
        lock (_fileLock)
        {
            byte[] data = null;
            if (File.Exists(_fileName))
                data = File.ReadAllBytes(_fileName);
            args.TokenCache.DeserializeMsalV3(data);
        }
    }

    private static void AfterAccessNotification(TokenCacheNotificationArgs args)
    {
        if (args.HasStateChanged)
        {
            lock (_fileLock)
            {
                byte[] data = args.TokenCache.SerializeMsalV3();
                File.WriteAllBytes(_fileName, data);
            }
        }
    }
};

Please note that most likely you should store this cache in an encrypted form in some kind of a database.
Consider using MSAL token serialization implementations available here:

https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-net-token-cache-serialization


Get Mail.dll

The post OAuth 2.0 with Office365/Exchange IMAP/POP3/SMTP first appeared on Blog | Limilabs.

]]>
Using TLS 1.2 with .NET SMTP client https://www.limilabs.com/blog/use-tls12-with-smtp Tue, 02 Jul 2019 10:39:39 +0000 https://www.limilabs.com/blog/?p=5510 In the following article, we will provide a comprehensive guide on configuring the Mail.dll SMTP client to utilize the TLS 1.2 encryption protocol. This security enhancement ensures that sending email communications remain safeguarded against potential threats and unauthorized access. By default clients and SMTP servers negotiate SSL/TLS versions they can both use. Most systems don’t […]

The post Using TLS 1.2 with .NET SMTP client first appeared on Blog | Limilabs.

]]>
In the following article, we will provide a comprehensive guide on configuring the Mail.dll SMTP client to utilize the TLS 1.2 encryption protocol.

This security enhancement ensures that sending email communications remain safeguarded against potential threats and unauthorized access.

By default clients and SMTP servers negotiate SSL/TLS versions they can both use. Most systems don’t allow SSL 3.0, TLS 1.0, 1.1 anymore and Mail.dll SMTP component simply uses the most recent TLS version.

TLS 1.2 and 1.3 are the most secure versions of TLS protocols. It is easy to force the connection to use it.

All you need to do is to set Smtp.SSLConfiguration.EnabledSslProtocols property to SslProtocols.Tls12 before issuing ConnectSSL or Connect and StartTLS sequence:

// C#

using (Smtp smtp = new Smtp())
{
    smtp.SSLConfiguration.EnabledSslProtocols = SslProtocols.Tls12;

    smtp.ConnectSSL("smtp.example.com");

    smtp.UseBestLogin("user","password");

    // ... 

    smtp.Close();
}
' VB.NET

Using smtp As New Smtp()
	smtp.SSLConfiguration.EnabledSslProtocols = SslProtocols.Tls12

	smtp.ConnectSSL("smtp.example.com")

	smtp.UseBestLogin("user@example.com", "password")

	'...

	smtp.Close()
End Using

Explicit SSL/TLS (STARTTLS)

For explicit SSL/TLS, code is almost the same. You first connect to a default, non-secure SMTP email submission port (587) and secure the connection using Smtp.StartTLS method:

// C#

using (Smtp smtp= new Smtp())
{
    smtp.SSLConfiguration.EnabledSslProtocols = SslProtocols.Tls12;

    smtp.Connect("smtp.example.com");
    smtp.StartTLS();

    smtp.UseBestLogin("user@example.com","password");

    // ... 

    smtp.Close();
}
' VB.NET

Using smtp As New Smtp()
	smtp.SSLConfiguration.EnabledSslProtocols = SslProtocols.Tls12

	smtp.Connect("smtp.example.com")
	smtp.StartTLS()

	smtp.UseBestLogin("user@example.com", "password")

	'...

	smtp.Close()
End Using

Older .NET framework versions

To use TLS 1.2 in SMTP client at least .NET Framework 4.5+ must be installed on your machine and your application should target .NET 4.5+.

It is possible to use TLS 1.2 in applications targeting earlier .NET framework versions, but 4.5 must be installed on the machine. After you have .NET 4.5 installed, your 2.0 – 4.0 app will use the 4.5 System.dll and you can enable TLS 1.2 using this code:

// C#

smtp.SSLConfiguration.EnabledSslProtocols = 
    (SecurityProtocolType)3072;

The post Using TLS 1.2 with .NET SMTP client 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.

]]>
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.

]]>