GmailClient

Struct GmailClient 

Source
pub struct GmailClient { /* private fields */ }
Expand description

Gmail API client providing authenticated access to Gmail operations.

GmailClient manages the connection to Gmail’s REST API, handles OAuth2 authentication, maintains label mappings, and provides methods for message list operations.

The client contains internal state for:

  • Authentication credentials and tokens
  • Label name-to-ID mappings
  • Query filters and pagination settings
  • Retrieved message summaries
  • Rule processing configuration

§Examples

use cull_gmail::{ClientConfig, GmailClient};

let config = ClientConfig::builder()
    .with_client_id("client-id")
    .with_client_secret("client-secret")
    .build();
     
let mut client = GmailClient::new_with_config(config).await?;
client.show_label();

Implementations§

Source§

impl GmailClient

Source

pub async fn new_with_config(config: ClientConfig) -> Result<Self>

Creates a new Gmail client with the provided configuration.

This method initializes a Gmail API client with OAuth2 authentication using the “installed application” flow. It sets up the HTTPS connector, authenticates using the provided credentials, and fetches the label mapping from Gmail.

§Arguments
  • config - Client configuration containing OAuth2 credentials and settings
§Returns

Returns a configured GmailClient ready for API operations, or an error if:

  • Authentication fails (invalid credentials, network issues)
  • Gmail API is unreachable
  • Label fetching fails
§Errors

This method can fail with:

§Examples
use cull_gmail::{ClientConfig, GmailClient};

let config = ClientConfig::builder()
    .with_client_id("123456789-abc.googleusercontent.com")
    .with_client_secret("your-client-secret")
    .build();

let client = GmailClient::new_with_config(config).await?;
println!("Gmail client initialized successfully");
§Panics

This method contains .unwrap() calls for:

  • HTTPS connector building (should not fail with valid TLS setup)
  • Default max results parsing (hardcoded valid string)
  • OAuth2 authenticator building (should not fail with valid config)
Source

pub fn get_label_id(&self, name: &str) -> Option<String>

Retrieves the Gmail label ID for a given label name.

This method looks up a label name in the internal label mapping and returns the corresponding Gmail label ID if found.

§Arguments
  • name - The label name to look up (case-sensitive)
§Returns

Returns Some(String) containing the label ID if the label exists, or None if the label name is not found.

§Examples
// Look up standard Gmail labels
if let Some(inbox_id) = client.get_label_id("INBOX") {
    println!("Inbox ID: {}", inbox_id);
}

// Look up custom labels
match client.get_label_id("Important") {
    Some(id) => println!("Found label ID: {}", id),
    None => println!("Label 'Important' not found"),
}
Source

pub fn show_label(&self)

Displays all available labels and their IDs to the log.

This method iterates through the internal label mapping and outputs each label name and its corresponding ID using the log::info! macro.

§Examples
let client = GmailClient::new_with_config(config).await?;

// Display all labels (output goes to log)
client.show_label();

Output example:

INFO: INBOX: Label_1
INFO: SENT: Label_2
INFO: Important: Label_3

Trait Implementations§

Source§

impl Clone for GmailClient

Source§

fn clone(&self) -> GmailClient

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for GmailClient

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl MessageList for GmailClient

Source§

fn set_max_results(&mut self, value: u32)

Set the maximum results

Source§

fn max_results(&self) -> u32

Report the maximum results value

Source§

fn add_labels(&mut self, labels: &[String]) -> Result<()>

Add label to the labels collection

Source§

fn add_labels_ids(&mut self, label_ids: &[String])

Add label to the labels collection

Source§

fn set_query(&mut self, query: &str)

Set the query string

Source§

fn messages(&self) -> &Vec<MessageSummary>

Get the summary of the messages

Source§

fn message_ids(&self) -> Vec<String>

Get a reference to the message_ids

Source§

fn label_ids(&self) -> Vec<String>

Get a reference to the message_ids

Source§

fn hub(&self) -> Gmail<HttpsConnector<HttpConnector>>

Get the hub

Source§

async fn get_messages(&mut self, pages: u32) -> Result<()>

Run the Gmail api as configured

Source§

async fn list_messages( &mut self, next_page_token: Option<String>, ) -> Result<ListMessagesResponse>

Retrieves a list of messages from Gmail based on current filter settings. Read more
Source§

async fn log_messages(&mut self, pre: &str, post: &str) -> Result<()>

Fetches detailed metadata for stored messages and logs their subjects and dates. Read more
Source§

impl RuleProcessor for GmailClient

Source§

fn initialise_lists(&mut self)

Initialise the message list.

The message list is initialised to ensure that the rule is only processed on the in-scope messages.

This must be called before processing any labels.

Source§

fn set_rule(&mut self, value: EolRule)

Configures the end-of-life rule for this Gmail client.

The rule defines which messages to target and what action to perform on them. This must be called before processing any labels.

Source§

fn set_execute(&mut self, value: bool)

Controls whether destructive operations are actually executed.

When false (dry-run mode), all operations are simulated but no actual changes are made to Gmail messages. When true, destructive operations like moving to trash or deleting will be performed.

Default is false for safety.

Source§

fn action(&self) -> Option<EolAction>

Returns the action that will be performed by the current rule.

This is useful for logging and verification before executing destructive operations.

Source§

async fn find_rule_and_messages_for_label(&mut self, label: &str) -> Result<()>

Orchestrates the complete rule processing workflow for a Gmail label.

This method implements the main processing logic by delegating to the internal orchestration function, which enables better testability while maintaining the same external behaviour.

The method respects the execute flag - when false, it runs in dry-run mode and only logs what would be done without making any changes.

Source§

async fn prepare(&mut self, pages: u32) -> Result<()>

Fetches messages from Gmail API based on current query and label filters.

This is a read-only operation that retrieves message metadata from Gmail without modifying any messages. The results are cached internally for subsequent batch operations.

§Arguments
  • pages - Number of result pages to fetch (0 = all available pages)
Source§

async fn batch_delete(&mut self) -> Result<()>

Permanently deletes all prepared messages using Gmail’s batch delete API.

⚠️ DESTRUCTIVE OPERATION - This action cannot be undone!

This method uses the Gmail API’s batch delete functionality to permanently remove messages from the user’s mailbox. Once deleted, messages cannot be recovered through any means.

§API Scope Requirements

Uses https://mail.google.com/ scope as it is required to immediately and permanently delete threads and messages, bypassing Trash.

Source§

async fn batch_trash(&mut self) -> Result<()>

Moves all prepared messages to Gmail’s trash folder using batch modify API.

This is a recoverable operation - messages can be restored from trash within 30 days via the Gmail web interface or API calls. After 30 days, Gmail automatically purges trashed messages permanently.

The operation adds the TRASH label and removes any existing labels that were used to filter the messages, effectively moving them out of their current folders into the trash.

§API Scope Requirements

Uses https://www.googleapis.com/auth/gmail.modify scope for secure, minimal privilege access to Gmail message modification operations.

Source§

async fn process_in_chunks( &self, message_ids: Vec<String>, action: EolAction, ) -> Result<()>

Chunk the message lists to respect API limits and call required action. Read more
Source§

async fn call_batch_delete(&self, ids: &[String]) -> Result<()>

Calls the Gmail API to permanently deletes a slice from the list of messages. Read more
Source§

async fn call_batch_trash(&self, ids: &[String]) -> Result<()>

Moves all prepared messages to the Gmail trash folder. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,