# Authenticating Yahoo accounts with Nylas

Source: https://developer.nylas.com/docs/provider-guides/yahoo-authentication/

Nylas supports two ways to authenticate users who have Yahoo as their provider: using [Yahoo's OAuth and Nylas' Bring Your Own (BYO) Authentication](#set-up-yahoo-oauth-and-nylas-bring-your-own-authentication), or by having them [create an app password](#create-yahoo-app-password) and using that password with [Nylas' BYO or Hosted IMAP authentication](#authenticate-yahoo-grants-with-app-password)

> **Info:** 
> **We strongly recommend using Yahoo's OAuth method instead of authenticating using IMAP**. This gives you more secure access to your users' data.

## Set up Yahoo OAuth and Nylas Bring Your Own Authentication

Before you authenticate users with Yahoo's OAuth and Nylas' BYO Authentication, you need to set up your environment and authentication flow:

1. [Request access to Yahoo data](#request-access-to-yahoo-data).
2. [Set up an OAuth-client endpoint](#set-up-oauth-client-endpoint) that can perform an OAuth handshake.
3. [Create and configure a Yahoo auth app](#create-yahoo-auth-app).
4. [Create a Yahoo connector](#create-yahoo-connector).
5. Use information from the OAuth process to [make BYO Authentication requests to Nylas](#create-grants-with-yahoo-oauth) and create grants for your users.

### Request access to Yahoo data

1. Create a Yahoo account that only your organization's administrators can access.
2. [Submit a Yahoo Mail API Access form to Yahoo](https://senders.yahooinc.com/developer/developer-access-mail-form/). This is _required_ if you want to use OAuth to access Yahoo's IMAP and SMTP servers. Make sure you mention somewhere in the form that you're using Nylas to connect.
   - **Email address**: Enter the email address that you created in step 1.
   - **API required**: Select **IMAP**.
   - **Your YDN account**: Enter the email address that you created in step 1.
3. Yahoo sends you a **Yahoo Mail Products Commercial Access Agreement**. Review the form, sign it, and send it back to Yahoo.

Yahoo sends you a message to notify you when they approve your data access request, or to ask for more information (if needed).

### Set up OAuth-client endpoint

After you [request access to Yahoo data](#request-access-to-yahoo-data), you need to set up an OAuth-client endpoint (also called a "redirect URI") in your project. This endpoint must be able to accept requests from Yahoo, extract information from the requests to complete an OAuth handshake process, then use the resulting refresh token to create a Nylas grant using BYO Authentication.

Take note of your OAuth-client endpoint URI. You'll need it when you [create your Yahoo auth app](#create-yahoo-auth-app).

### Create Yahoo auth app

1. Sign in to the [Yahoo Apps dashboard](https://developer.yahoo.com/apps/) using your admin Yahoo account.
2. Select **Create an app** and fill out the information.
   - **Application name**: Enter a brief, descriptive name for your application.
   - **Description**: Describe your application (for example, the region you'll be using it for).
   - **Homepage URL**: (Optional) Enter your application's homepage URL.
   - **Redirect URI(s)**: Enter your [OAuth-client endpoint URI](#set-up-oauth-client-endpoint). Registering a redirect URI might take _up to 24 hours_. You might experience inconsistencies when trying to log in to your Yahoo account during that time.
   - **OAuth client type**: Select **Confidential client**.
   - **API permissions**:
     - Select **Mail**. If you plan to use Nylas to send or modify messages, select **Read/Write**. If you don't send or modify messages, select **Read**.
     - Select **OpenID connect permissions**, then select **Email** and **Profile**.
3. Click **Create app**.
4. On the next page, Yahoo displays your app's client ID and secret. Take note of them, because you'll need them when you [create a Yahoo connector](#create-yahoo-connector).
> **Warn:** 
> **Be sure to save the client secret value somewhere secure, like a secrets manager**. For best practices, see [Store secrets securely](/docs/dev-guide/best-practices/#store-secrets-securely).

### Create Yahoo connector

After you [create a Yahoo auth app](#create-yahoo-auth-app), you can create a Yahoo connector for your Nylas application.

To create a connector using the Nylas API, make a [Create Connector request](/docs/reference/api/connectors-integrations/create_connector/) that specifies `"provider": "yahoo"`.

> **Info:** 
> **Your `scope` array must match the scopes you request in your Yahoo auth app**. If you request Mail Read/Write in your auth app, specify `mail-w` in your request. If you request Mail Read, specify `mail-r` instead. If you try to request both `mail-w` and `mail-r`, Nylas returns an error.

```bash {5,10-13} [group_1-cURL]
curl -X POST 'https://api.us.nylas.com/v3/connectors' \
  --header 'Authorization: Bearer <NYLAS_API_KEY>' \
  --header 'Content-Type: application/json' \
  --data '{
    "provider": "yahoo",
    "settings": {
      "client_id": "<YAHOO_CLIENT_ID>",
      "client_secret": "<YAHOO_CLIENT_SECRET>"
    },
    "scope": [
      "email",
      "mail-w"
    ]
  }'
```

```json [group_1-Response (JSON)]
{
  "request_id": "1",
  "data": {
    "provider": "yahoo"
    "scope": [
      "email",
      "mail-r"
    ]
  }
}
```

To make a connector in the Nylas Dashboard...

1. Select **Connectors** in the left navigation.
2. On the next screen, find **Yahoo** and click the **plus** symbol (**+**).
3. Enter your **Yahoo OAuth client ID** and **Yahoo OAuth client secret**.
4. Select either the **mail-r** or **mail-w** scope, depending on the scopes you requested in your Yahoo auth app.
5. **Save** your changes.

### Create grants with Yahoo OAuth

When your [OAuth-client endpoint](#set-up-oauth-client-endpoint) receives a request, you use the information it provides to fill out the following URL template:

```bash
https://api.login.yahoo.com/oauth2/request_auth?client_id=<YAHOO_CLIENT_ID>&redirect_uri=<CALLBACK_URI>&response_type=code
```

When a user requests this URL, they're redirected to Yahoo's login page. They then log in to their account and confirm that they're allowing Nylas to access their Yahoo Mail data. After they authenticate, Yahoo returns a refresh token that you use to make a [Bring Your Own Authentication request](/docs/reference/api/manage-grants/byo_auth/). This completes the Yahoo OAuth flow and creates a Nylas grant for the user.

Overall, the Yahoo OAuth flow follows these steps:

1. Yahoo sends a `GET` request that includes the `code` query parameter.
2. Your OAuth-client endpoint extracts the `code` value and makes a token request to Yahoo.

   ```bash
   curl --request POST \
     --location 'https://api.login.yahoo.com/oauth2/get_token' \
     --header 'Content-Type: application/x-www-form-urlencoded' \
     --data-urlencode 'grant_type=authorization_code' \
     --data-urlencode 'redirect_uri=<NYLAS_REDIRECT_URI>' \
     --data-urlencode 'code=<YAHOO_CODE>' \
     --data-urlencode 'client_id=<YAHOO_CLIENT_ID>' \
     --data-urlencode 'client_secret=<YAHOO_CLIENT_SECRET>'
   ```

3. Yahoo responds with a `refresh_token`.

   ```json
   {
     "access_token": "<ACCESS_TOKEN>",
     "token_type": "bearer",
     "expires_in": 3600,
     "refresh_token": "<REFRESH_TOKEN>",
     "xoauth_yahoo_guid": "<YAHOO_GUID>"
   }
   ```

4. Your OAuth-client endpoint makes a [BYO Authentication request](/docs/reference/api/manage-grants/byo_auth/) that includes the Yahoo `refresh_token`.

   ```bash
   curl -X POST 'https://api.us.nylas.com/v3/connect/custom' \
     --header 'Authorization: Bearer <NYLAS_API_KEY>' \
     --header 'Content-Type: application/json' \
     --data '{
       "provider": "yahoo",
       "settings": {
         "refresh_token": "<YAHOO_REFRESH_TOKEN>"
       }
     }'
   ```

5. Nylas creates a grant for the user and returns its `grant_id`.

## Authenticate Yahoo grants with app password

If you're not able to set up a Yahoo OAuth application, there are two ways to authenticate Yahoo users: you can either [use Hosted IMAP and an app password](/docs/v3/auth/imap/), or [use Bring Your Own Authentication and an app password](#create-grants-with-app-password-and-bring-your-own-authentication). For both of these methods, the user first needs to [create an app password](#create-yahoo-app-password).

### Create Yahoo app password

If your Yahoo users authenticate using IMAP, they need to create an [app password](https://help.yahoo.com/kb/SLN15241.html). They'll use this in place of their regular email password when authenticating.

1. Sign in to Yahoo Mail.
2. Navigate to **Account info > Account security**.
3. At the bottom of the screen, select **Generate app password**.
4. Follow the steps to generate a new app password.

These steps also work for users who have two-factor authentication enabled.

For more details, read the [generate third-party app passwords](https://help.yahoo.com/kb/SLN15241.html) article from Yahoo.

If the Yahoo responds with an incorrect credential error, Nylas prompts the user with an error message and a hint with a link to Yahoo guide about creating an application password

### Create grants with app password and Bring Your Own Authentication

When you authenticate Yahoo users with Nylas' [BYO Authentication](/docs/v3/auth/custom/), you pass a username, password, host, port, and type during the process instead of providing a refresh token.

```bash
curl -X POST 'https://api.us.nylas.com/v3/connect/custom' \
  --header 'Authorization: Bearer <NYLAS_API_KEY>' \
  --header 'Content-Type: application/json' \
  --data '{
    "provider": "imap",
    "settings": {
      "imap_username": "leyah@yahoo.com",
      "imap_password": "<YAHOO_APP_PASSWORD>",
      "imap_host": "imap.mail.yahoo.com",
      "imap_port": 993,
      "type": "yahoo"
    }
  }'
```

```js [customAuth-Node.js]


const config = {
  apiKey: process.env.NYLAS_API_KEY,
  apiUri: process.env.NYLAS_API_URI,
};

const nylas = new Nylas(config);

async function auth() {
  try {
    const response = await nylas.auth.grants.create({
      requestBody: {
        provider: "imap",
        settings: {
          imap_username: process.env.YAHOO_IMAP_USERNAME,
          imap_password: process.env.YAHOO_IMAP_PASSWORD,
          imap_host: "imap.mail.yahoo.com",
          imap_port: 993,
          type: "yahoo",
        },
      },
    });

    console.log("User connected:", response);
  } catch (error) {
    console.error("Error connecting user:", error);
  }
}

auth();
```

```python
from dotenv import load_dotenv
load_dotenv()


from nylas import Client

nylas = Client(
    os.environ.get('NYLAS_API_KEY'),
    os.environ.get('NYLAS_API_URI')
)

# Create a grant
response = nylas.auth.custom_authentication(
  request_body={
    "provider": "imap",
    "settings": {
      "imap_host": "imap.mail.yahoo.com",
      "imap_port": 993,
      "imap_username": os.environ.get('YAHOO_IMAP_USERNAME'),
      "imap_password": os.environ.get('YAHOO_IMAP_PASSWORD'),
      "type": "yahoo"
    },
  }
)
```

```ruby
# frozen_string_literal: true

require 'nylas'
require 'dotenv/load'
require 'sinatra'

set :show_exceptions, :after_handler

error 404 do
  'No authorization code returned from Nylas'
end

error 500 do
  'Failed to exchange authorization code for token'
end

nylas = Nylas::Client.new(api_key: ENV['NYLAS_API_KEY'])

get '/nylas/auth' do
  request_body = {
  provider: 'imap',
  settings: {
      "imap_username": "<YAHOO_USERNAME>",
      "imap_password": "<YAHOO_APP_PASSWORD>",
      "imap_host": "imap.mail.yahoo.com",
      "imap_port": 993,
      "type": "yahoo"
    }
  }

  response = nylas.auth.custom_authentication(request_body)
  "#{response}"
end
```

```kt
fun main(args: Array<String>) {
  val nylas: NylasClient = NylasClient(apiKey = "<NYLAS_API_KEY>")
  val http: Http = ignite()

  http.get("/nylas/auth") {
    val settings: MutableMap<String, String> = HashMap()

    settings["imap_username"] = "<YAHOO_USERNAME>";
    settings["imap_password"] = "<YAHOO_APP_PASSWORD>";
    settings["imap_host"] = "imap.mail.yahoo.com";
    settings["imap_username"] = "imap.mail.yahoo.com";
    settings["imap_port"] = "993";
    settings["type"] = "yahoo";

    var requestBody = CreateGrantRequest(AuthProvider.IMAP, settings)
    var authData = nylas.auth().customAuthentication(requestBody);

    response.redirect(authData.toString())
  }
}
```

```java
public class AuthRequest {
  public static void main(String[] args) throws NylasSdkTimeoutError, NylasApiError {
    NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();

    get("/nylas/auth", (request, response) -> {
      List<String> scope = new ArrayList<>();
      Map<String, String> settings = new HashMap<>();

      settings.put("imap_username","<YAHOO_USERNAME>");
      settings.put("imap_password","<YAHOO_APP_PASSWORD>");
      settings.put("imap_host","imap.mail.yahoo.com");
      settings.put("imap_port","993");
      settings.put("type","yahoo");

      CreateGrantRequest requestBody = new CreateGrantRequest(AuthProvider.IMAP, settings);
      Response<Grant> authData = nylas.auth().customAuthentication(requestBody);

      response.redirect(String.valueOf(authData));

      return null;
    });
  }
}
```

## Yahoo OAuth scopes

> **Info:** 
> **You can only use the Nylas Email API with grants authenticated using Yahoo OAuth**.

The table below lists the permissions you need to include in your Yahoo provider auth application for each endpoint.

| Endpoint                                                                                                                                                                                                                                                                                                             | Scopes                            |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
| `GET /v3/grants/<NYLAS_GRANT_ID>/messages`<br/>`GET /v3/grants/<NYLAS_GRANT_ID>/messages/<MESSAGE_ID>`                                                                                                                                                                                                               | `email`<br/>`mail-r`              |
| `PUT /v3/grants/<NYLAS_GRANT_ID>/messages/<MESSAGE_ID>`<br/>`DELETE /v3/grants/<NYLAS_GRANT_ID>/messages/<MESSAGE_ID>`<br/>`POST /v3/grants/<NYLAS_GRANT_ID>/messages/smart-compose`<br/>`POST /v3/grants/<NYLAS_GRANT_ID>/messages/<MESSAGE_ID>/smart-compose`<br/>`POST /v3/grants/<NYLAS_GRANT_ID>/messages/send` | `email`<br/>`mail-r`<br/>`mail-w` |

All [`message.*` notifications](/docs/reference/notifications/#message-notifications) require Yahoo's `email` and `mail-r` scopes.

## Yahoo provider limitations

By default, Nylas stores messages from Yahoo grants in a cache for 90 days after they're received or created. You can access older messages by specifying `"query_imap": true` when you make a request to the following endpoints: [Get Message](/docs/reference/api/messages/get-messages-id/), [Get all Messages](/docs/reference/api/messages/get-messages/), [Get Draft](/docs/reference/api/drafts/get-draft-id/), [Get all Drafts](/docs/reference/api/drafts/get-drafts/), and the [Attachments endpoints](/docs/reference/api/attachments/). This directly queries the IMAP server instead of Nylas' cache.

Nylas doesn't send webhook notifications for changes to messages older than 90 days.

### Yahoo rate limits

Yahoo doesn't publicize its sending limits for messages. If you encounter a rate limit notification, you'll need to wait until the limit expires to send messages. Usually, the duration of the limit is included in the notification. For more information, see [Yahoo's official documentation](https://help.yahoo.com/kb/limits-sending-email-yahoo-mail-sln3353.html).

## What's next

- [List Yahoo Mail from the terminal](https://cli.nylas.com/guides/list-yahoo-emails) - Read and search Yahoo Mail messages using the Nylas CLI