본문 바로가기

Android

[Gmail API] Mail Move to Trash

기존 Label에서 휴지통으로 보내는 방법

public static void trashMailList(Context context, Account account, List<String> mailIds, GmailNetworkListener listener) {
        try {
            GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(context, Collections.singleton(MAIL_SCOPE));
            credential.setSelectedAccount(account);

            Gmail service = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).build();
            new TrashMailListTask(account, service, mailIds, listener).execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class TrashMailListTask extends AsyncTask<Void, Void, List<Message>> {

        private Account account;
        private Gmail service;
        private List<String> mailIds;
        private List<Message> messages;
        private GmailNetworkListener listener;

        public TrashMailListTask(Account account, Gmail service, List<String> mailIds, GmailNetworkListener listener) {
            this.account = account;
            this.service = service;
            this.mailIds = mailIds;
            this.messages = new ArrayList<>();
            this.listener = listener;
        }

        final JsonBatchCallback<Message> callback = new JsonBatchCallback<Message>() {
            @Override
            public void onSuccess(Message message, HttpHeaders responseHeaders) throws IOException {
                messages.add(message);
            }

            @Override
            public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException {

            }
        };

        @Override
        protected List<Message> doInBackground(Void... voids) {
            if (listener == null) return null;

            try {
                BatchRequest batch = service.batch();
                for (String item : mailIds) {
                    service.users().messages().trash(account.name, item).queue(batch, callback);
                }
                batch.execute();

                return messages;
            } catch (IOException e) {
                e.printStackTrace();
                listener.onFailure(e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(List<Message> result) {
            super.onPostExecute(result);
            if (listener != null) {
                listener.onSuccess(result);
            }
        }
    }