Results 1 to 10 of 10
  1. #1
    spalax is offline Member
    Join Date
    Aug 2009
    Posts
    14
    Rep Power
    0

    Default Delete message from a sender in gmail using java

    Hi all,
    i want to log in to my gmail account, filter spam and delete them
    But i want to delete only spam from a particular sender, say for from spam@gmail.com
    How can i delete all messages from this sender only?

    The code i found is here but it.s not deleting any messages:
    Any help please, thank you


    Java Code:
    import java.util.Properties;
    import javax.mail.Address;
     
    import javax.mail.Flags;
    import javax.mail.Folder;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.NoSuchProviderException;
    import javax.mail.Session;
    import javax.mail.Store;
     
    
    public class MessageRemover {
     
     
        public void deleteMessages(String host, String port,
                String userName, String password, String senderToDelete) {
            Properties properties = new Properties();
     
            // server setting
            properties.put("mail.imap.host", host);
            properties.put("mail.imap.port", port);
     
            // SSL setting
            properties.setProperty("mail.imap.socketFactory.class",
                    "javax.net.ssl.SSLSocketFactory");
            properties.setProperty("mail.imap.socketFactory.fallback", "false");
            properties.setProperty("mail.imap.socketFactory.port",
                    String.valueOf(port));
     
            Session session = Session.getDefaultInstance(properties);
     
            try {
                // connects to the message store
                Store store = session.getStore("imap");
                store.connect(userName, password);
     
                // opens the inbox folder
                Folder folderInbox = store.getFolder("INBOX");
                folderInbox.open(Folder.READ_WRITE);
     
                // fetches new messages from server
                Message[] arrayMessages = folderInbox.getMessages();
     
                for (int i = 0; i < arrayMessages.length; i++) {
                    Message message = arrayMessages[i];
                    Address[] sender = message.getFrom();
                    if (sender.equals(senderToDelete)) {
                        message.setFlag(Flags.Flag.DELETED, true);
                        System.out.println("Marked DELETE for message: " + senderToDelete);
                    }
     
                }
    
                boolean expunge = true;
                folderInbox.close(expunge);
    
                // disconnect
                store.close();
            } catch (NoSuchProviderException ex) {
                System.out.println("No provider.");
                ex.printStackTrace();
            } catch (MessagingException ex) {
                System.out.println("Could not connect to the message store.");
                ex.printStackTrace();
            }
        }
     
        
        public static void main(String[] args) {
            String host = "imap.gmail.com";
            String port = "993";
            
         
             
             
             String userName = "myemail@gmail.com";
             String password = "password";
             
             
            
            MessageRemover remover = new MessageRemover();
            
     
           
            String senderToDelete = "spam@gmail.com";
            remover.deleteMessages(host, port, userName, password,senderToDelete );
           
     
        }
    }

  2. #2
    esprittn is offline Member
    Join Date
    Oct 2014
    Posts
    2
    Rep Power
    0

    Default Re: Delete message from a sender in gmail using java

    Hello
    I have this code.
    Java Code:
    package JavaMailAPI;
    import javax.mail.Authenticator;
    import javax.mail.PasswordAuthentication;
    
    class GMailAuthenticator extends Authenticator {
         String user;
         String pw;
         public GMailAuthenticator (String username, String password)
         {
            super();
            this.user = username;
            this.pw = password;
         }
        public PasswordAuthentication getPasswordAuthentication()
        {
           return new PasswordAuthentication(user, pw);
        }
    }
    Java Code:
    package JavaMailAPI;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Properties;
    
    import javax.mail.Flags;
    import javax.mail.Folder;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.NoSuchProviderException;
    import javax.mail.Session;
    import javax.mail.Store;
    
    public class DeleteEmail {
    
       public static void delete(String pop3Host, String storeType, String user,
          String password) 
       {
          try 
          {
             // get the session object
             Properties properties = new Properties();
             properties.put("mail.store.protocol", "pop3");
             properties.put("mail.pop3s.host", pop3Host);
             properties.put("mail.pop3s.port", "995");
             properties.put("mail.pop3.starttls.enable", "true");
             Session emailSession = Session.getInstance(properties, new GMailAuthenticator(user, password));
             // emailSession.setDebug(true);
    
             // create the POP3 store object and connect with the pop server
             Store store = emailSession.getStore("pop3s");
    
             store.connect(pop3Host, user, password);
    
             // create the folder object and open it
             Folder emailFolder = store.getFolder("INBOX");
             emailFolder.open(Folder.READ_WRITE);
    
             BufferedReader reader = new BufferedReader(new InputStreamReader(
                System.in));
             // retrieve the messages from the folder in an array and print it
             Message[] messages = emailFolder.getMessages();
             System.out.println("messages.length---" + messages.length);
             for (int i = 0; i < messages.length; i++) {
                Message message = messages[i];
                System.out.println("---------------------------------");
                System.out.println("Email Number " + (i + 1));
                System.out.println("Subject: " + message.getSubject());
                System.out.println("From: " + message.getFrom()[0]);
                System.out.println("---------------------------------");
                String subject = message.getSubject();
                System.out.print("Do you want to delete this message [y/n] ? ");
                String ans = reader.readLine();
                if ("Y".equals(ans) || "y".equals(ans)) {
    	       // set the DELETE flag to true
    	       message.setFlag(Flags.Flag.DELETED, true);
    	       System.out.println("Marked DELETE for message: " + subject);
                } else if ("n".equals(ans)) {
    	           continue;
                }
             }
             // expunges the folder to remove messages which are marked deleted
             emailFolder.close(true);
             store.close();
    
          } catch (NoSuchProviderException e) {
             e.printStackTrace();
          } catch (MessagingException e) {
             e.printStackTrace();
          } catch (IOException io) {
             io.printStackTrace();
          }
       }
    
       public static void main(String[] args) {
    
          String host = "pop.gmail.com";// change accordingly
          String mailStoreType = "pop3";
          String username = "a@a.a";// change accordingly
          String password = "a";// change accordingly
    
          delete(host, mailStoreType, username, password);
       }
    }
    this code will :
    • Retrieves messages from inbox folder.
    • Iterate through the messages and type "Y" or "y" if you want to delete the message by invoking the method setFlag(Flags.Flag.DELETED, true) on the Message object.
    • The messages marked DELETED are not actually deleted, until we call the expunge() method on the Folder object, or close the folder with expunge set to true

    .
    PS: you must change the security parameter in your gmail account(https://www.google.com/settings/security) to let this application access to your account.

  3. #3
    spalax is offline Member
    Join Date
    Aug 2009
    Posts
    14
    Rep Power
    0

    Default Re: Delete message from a sender in gmail using java

    Hello,
    thank you for your reply but this code is working for me by searching the Subject name and delete but what i want is to delete the message by search the sender email address.
    And i don't want to display any question like Do you want to delete this message etc etc.

    I just want to delete all message from a sender

    Thanks

  4. #4
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,423
    Blog Entries
    7
    Rep Power
    27

    Default Re: Delete message from a sender in gmail using java

    Quote Originally Posted by spalax View Post
    this code is working for me by searching the Subject name and delete but what i want is to delete the message by search the sender email address.
    And i don't want to display any question like Do you want to delete this message etc etc.

    I just want to delete all message from a sender
    So what keeps you from changing that bit of code?

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  5. #5
    spalax is offline Member
    Join Date
    Aug 2009
    Posts
    14
    Rep Power
    0

    Default Re: Delete message from a sender in gmail using java

    So what keeps you from changing that bit of code?
    i tried in the first code

  6. #6
    esprittn is offline Member
    Join Date
    Oct 2014
    Posts
    2
    Rep Power
    0

    Default Re: Delete message from a sender in gmail using java

    If you use only Gmail account so try Gmail API

  7. #7
    spalax is offline Member
    Join Date
    Aug 2009
    Posts
    14
    Rep Power
    0

    Default Re: Delete message from a sender in gmail using java

    I try to use gmail api for the first time and when i execute GmailAPIQuickStartthe.java
    i got a url and when i go to this url i have the error message

    Error: redirect_uri_mismatch

  8. #8
    spalax is offline Member
    Join Date
    Aug 2009
    Posts
    14
    Rep Power
    0

    Default Re: Delete message from a sender in gmail using java

    ok now the first step is passed
    i have to try how to send email and delete

  9. #9
    StormyWaters is offline Senior Member
    Join Date
    Feb 2009
    Posts
    312
    Rep Power
    11

    Default Re: Delete message from a sender in gmail using java

    Took a quick look at your code in the first post. It looks like your comparison for checking the sender's address is actually comparing the senderToDelete (String class) with the sender (Address[]). Instead, you should probably obtain the first entry like the example that was provided to you, though I believe that is still an Address object so you would have to figure out how to get the actual String representation.

  10. #10
    spalax is offline Member
    Join Date
    Aug 2009
    Posts
    14
    Rep Power
    0

    Default Re: Delete message from a sender in gmail using java

    I'm stucked with gmail api, the tutorial from google is completely confusing.
    The code to send email is not clear.

Similar Threads

  1. How to delete sender email address using java
    By 24042014a in forum New To Java
    Replies: 8
    Last Post: 10-09-2014, 02:43 AM
  2. Replies: 1
    Last Post: 07-17-2014, 06:37 PM
  3. How to login to gmail account using java
    By moizali89 in forum Java Servlet
    Replies: 2
    Last Post: 02-02-2011, 05:48 PM
  4. Replies: 0
    Last Post: 07-29-2010, 01:06 PM
  5. Java and gmail
    By ak88 in forum Advanced Java
    Replies: 1
    Last Post: 03-25-2010, 05:05 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •