Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete multiple emails from INBOX in gmail using GMAIL API

Tags:

email

gmail

Is there a way to select multiple emails from INBOX in gmail using GMAIL API and delete them in one request. For ex: I have selected 3 mails to delete and delete them in only one request.

In GMAIL API i found this service.users().threads().delete(userId, threadId).execute(); in which i have to pass message id of mails one by one to delete which will consume a lot of time. Thanks in advance

like image 864
Rider Avatar asked Feb 17 '26 10:02

Rider


1 Answers

Gmail provides API to delete multiple emails at once where you can pass multiple ids in request body. Here is the API reference.

https://developers.google.com/gmail/api/v1/reference/users/messages/batchDelete

Edit: Added Sample Ruby Code

I used google-api-ruby-client v0.8.2 gem to make API calls. Here is a sample code.

require 'google/api_client'
@client = Google::APIClient.new({application_name: 'MyApp', application_version: 'MyAppVersion'})
@client.authorization.access_token = MY_ACCESS_TOKEN
@service = @client.discovered_api('gmail')

payload = {ids: ['id_1', 'id_2']} # You can add multiple ids here
result = @client.execute(
    :api_method => @service.users.messages.batch_delete,
    :parameters => {userId: 'me'},
    :headers => {'Content-Type' => 'application/json'},
    :body => payload.to_json
)
puts result.success? # true/false

NOTE: The API used in sample code will not move your messages to trash, rather it will permanently delete your messages.

like image 98
Sambit Avatar answered Feb 20 '26 08:02

Sambit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!