Automatically find all returned e-mails from “Undelivered messages”

If you’ve got your mails under a text format in a folder (like the unix Maildir) you can use this command to extract the e-mails with a 550 return error.

 

cat * | grep --text -Pzoi '([a-z0-9._-]+@[a-z0-9.]+)(?=.*host.*said.*55[0-9])'

 

The first command in the pipe, cat, send all files content to the next command in the pipe : grep. Grep is removing everything except what is an adress, and only if it is followed by “host * said * 55[0-9] ” where * can be everything and [0-9] is a number between 0 and 9. We also use the –text parameter because some mails could contain binary data.

 

As grep give you the mail separated by new line, and an sql command takes a list of strings separated by comma, you can copy the list in gedit or notepad++ and use search->replace to change them in the format ‘mail1’, ‘mail2’, … You have to put “(.*)” in the search field, “‘\1’,” in the replace by field, and select “regular expression”. You then place the result in the parenthesis after IN, in SQL command below :

 

UPDATE contact SET mail='' WHERE mail IN ('bad@hotmail.com', 'error@mail.com')