مدیریت فیلترهای جیمیل

این سند نحوه استفاده از فیلترها در Gmail API را توضیح می‌دهد.

شما می‌توانید از منبع settings.filters برای پیکربندی قوانین فیلترینگ پیشرفته برای یک حساب کاربری استفاده کنید. فیلترها می‌توانند به طور خودکار برچسب‌ها را اضافه یا حذف کنند یا ایمیل‌ها را بر اساس ویژگی‌ها یا محتوای پیام دریافتی به نام‌های مستعار تأیید شده ارسال کنند.

برای اطلاعات در مورد نحوه ایجاد ، فهرست کردن ، دریافت یا حذف فیلترهای Gmail، به منبع settings.filters مراجعه کنید.

معیارهای مطابقت

پیام‌ها را بر اساس ویژگی‌هایی مانند فرستنده، موضوع، تاریخ، اندازه و محتوای پیام فیلتر کنید. فیلترها فقط برای پیام‌های خاص اعمال می‌شوند و نه کل رشته ایمیل. هر پرس‌وجویی که از سینتکس جستجوی پیشرفته جیمیل استفاده می‌کند، می‌تواند در یک فیلتر نیز استفاده شود. به عنوان مثال، الگوهای فیلتر رایج عبارتند از:

فیلتر مسابقات
criteria.from='sender@example.com' ایمیل‌های دریافتی از sender@example.com
criteria.size=10485760
criteria.sizeComparison='larger'
ایمیل‌های بزرگتر از ۱۰ مگابایت
criteria.hasAttachment=true ایمیل‌های دارای پیوست
criteria.subject='[People with Pets]' ایمیل‌هایی با عنوان [People with Pets]
criteria.query='"my important project"' ایمیل‌هایی حاوی my important project
criteria.negatedQuery='"secret knock"' ایمیل‌هایی که حاوی secret knock نیستند

اگر چندین معیار در یک فیلتر وجود داشته باشد، یک پیام باید تمام معیارهای لازم برای اعمال فیلتر را داشته باشد.

اقدامات

یک Action را روی پیام‌هایی که با معیارهای فیلتر مطابقت دارند اعمال کنید. با استفاده از یک Action ، می‌توانید پیام‌ها را به یک آدرس ایمیل تأیید شده ارسال کنید، یا برچسب‌ها را اضافه و حذف کنید.

برای تغییر وضعیت ایمیل، برچسب‌ها را اضافه یا حذف کنید. برای مثال، برخی از اقدامات رایج عبارتند از:

اکشن اثر
action.removeLabelIds=['INBOX'] بایگانی ایمیل (از صندوق ورودی صرف نظر کنید)
action.removeLabelIds=['UNREAD'] علامت گذاری به عنوان خوانده شده
action.removeLabelIds=['SPAM'] هرگز به عنوان هرزنامه علامت گذاری نکنید
action.removeLabelIds=['IMPORTANT'] هرگز به عنوان مهم علامت گذاری نکنید
action.addLabelIds=['IMPORTANT'] علامت گذاری به عنوان مهم
action.addLabelIds=['TRASH'] ایمیل را حذف کنید
action.addLabelIds=['STARRED'] علامت گذاری به عنوان ستاره دار
action.addLabelIds=['<user label id>'] ایمیل را با برچسب تعریف‌شده توسط کاربر برچسب‌گذاری کنید. فقط یک برچسب تعریف‌شده توسط کاربر برای هر فیلتر مجاز است.

نمونه‌های کد

نمونه‌های کد زیر نحوه برچسب‌گذاری و بایگانی پیام‌ها از یک فهرست پستی را نشان می‌دهند:

جاوا

gmail/snippets/src/main/java/CreateFilter.java
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.Filter;
import com.google.api.services.gmail.model.FilterAction;
import com.google.api.services.gmail.model.FilterCriteria;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Arrays;

/* Class to demonstrate the use of Gmail Create Filter API */
public class CreateFilter {
  /**
   * Create a new filter.
   *
   * @param labelId - ID of the user label to add
   * @return the created filter id, {@code null} otherwise.
   * @throws IOException - if service account credentials file not found.
   */
  public static String createNewFilter(String labelId) throws IOException {
        /* Load pre-authorized user credentials from the environment.
           TODO(developer) - See https://developers.google.com/identity for
            guides on implementing OAuth2 for your application. */
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
        .createScoped(GmailScopes.GMAIL_SETTINGS_BASIC,
            GmailScopes.GMAIL_LABELS);
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);

    // Create the gmail API client
    Gmail service = new Gmail.Builder(new NetHttpTransport(),
        GsonFactory.getDefaultInstance(),
        requestInitializer)
        .setApplicationName("Gmail samples")
        .build();

    try {
      // Filter the mail from sender and archive them(skip the inbox)
      Filter filter = new Filter()
          .setCriteria(new FilterCriteria()
              .setFrom("gduser2@workspacesamples.dev"))
          .setAction(new FilterAction()
              .setAddLabelIds(Arrays.asList(labelId))
              .setRemoveLabelIds(Arrays.asList("INBOX")));

      Filter result = service.users().settings().filters().create("me", filter).execute();
      // Prints the new created filter ID
      System.out.println("Created filter " + result.getId());
      return result.getId();
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      GoogleJsonError error = e.getDetails();
      if (error.getCode() == 403) {
        System.err.println("Unable to create filter: " + e.getDetails());
      } else {
        throw e;
      }
    }
    return null;
  }
}

پایتون

gmail/snippet/settings snippets/create_filter.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def create_filter():
  """Create a filter.
  Returns: Draft object, including filter id.

  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """
  creds, _ = google.auth.default()

  try:
    # create gmail api client
    service = build("gmail", "v1", credentials=creds)

    label_name = "IMPORTANT"
    filter_content = {
        "criteria": {"from": "gsuder1@workspacesamples.dev"},
        "action": {
            "addLabelIds": [label_name],
            "removeLabelIds": ["INBOX"],
        },
    }

    # pylint: disable=E1101
    result = (
        service.users()
        .settings()
        .filters()
        .create(userId="me", body=filter_content)
        .execute()
    )
    print(f'Created filter with id: {result.get("id")}')

  except HttpError as error:
    print(f"An error occurred: {error}")
    result = None

  return result.get("id")


if __name__ == "__main__":
  create_filter()