Search code examples
bashemailspam

bash script delete mails from specific address (pop3 account)


I want to clean my mailbox from mails from specific address

I have thousands of messages, I want to do this in bash script, and run it from time to time (a receive SPAM from different addresses, and unfortunately my "spam filters" have only small effect on them)


Solution

  • To interact with a mail server through command line, you could use either telnet or openssl.

    You can connect to your pop server using the following command (I've taken gmail as an example. You'll have to look for your email host pop3 address and socket.) :

    openssl s_client -connect pop.gmail.com:995 -quiet
    

    As this command is interactive, it will ask for a username, a password and a serie of commands.

    expect is a tool that can automate interaction with interactive commands. The basic syntax is as follow : expect "somestring" action -> If the program we monitor displays "somestring", we execute the action.

    Here is a script that would delete all the messages present on your email address :

    #!/usr/bin/expect
    
    #you can modify the timeout if the script fails
    set timeout 1
    
    #our connection variables
    set ip "pop.gmail.com"
    set socket "995"
    set user "user.name"
    set pass "password"
    
    #we set the address we want to remove mails from here. Escape special regex characters such as dots.
    set target_address "mail\.example@gmail\.com"
    
    #we launch the subprocess we want to interact with
    spawn openssl s_client -connect $ip:$socket -quiet
    
    #if connection went all right, we try to login
    expect -re ".OK.*" {send "user $user\r"}
    expect -re ".OK.*" {send "pass $pass\r"}
    
    #if login went alright, we try to count the messages on the server
    #you will get the following output :
    #+OK NB_MSG TOTAL_SIZE
    expect -re ".OK.*" {send "stat\r"}
    
    #if the stat command went alright ...
    expect -re ".OK.*" {
            #we extract the number of mail from the output of the stat command
            set mail_count [lindex [split [lindex [split $expect_out(buffer) \n] 1] " "] 1]
    
            #we iterate through every email...
            for {set i 1} {$i <= $mail_count} {incr i 1} {
                #we retrieve the header of the email
                send "top $i 0\r"
                
                #if the header contains "To: $target_address" (or "To: <$target_address>" or "To: Contact Name <$target_address>" ...)
                #to filter according to the sender, change the regex to "\nFrom: ..."
                expect -re "\nTo: \[^\n\]*$target_address" {
                        #we delete the email
                        send "dele $i\r"
                }
            }
    }
    expect default
    

    You might need to alter your email account settings to allow the use of external programs