Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

« Newer Snippets
Older Snippets »
18 total  XML / RSS feed 

Read local Unix mail in Mail.app

The following instructions on how to set up a local POP3 (SSL) server to read local Unix mail in Mail.app require an admin user account and Upgrading Postfix with TLS (SSL) support on Mac OS X (10.4). Use at your own risk!


export PATH="/usr/local/bin:/usr/local/sbin:/usr/local/lib:/usr/local/include:/usr/bin:/bin:/usr/sbin:/sbin"


# create a SSL certificate
# cf. http://www.npcole.com/usingimaptiger.html
# NOTE: put "localhost" in the "Common Name" field

cd /System/Library/OpenSSL/certs
sudo openssl req -new -x509 -nodes -days 3650 -out ipop3d.pem -keyout ipop3d.pem 

# If Mail.app later complains about the newly created certificate, just:
- Click "Show Certificate"
- Alt-Drag the icon for the certificate onto your desktop.
- Double-click the file.
- In the dialog box that will appear, use the drop down list to add the key to the "X509Anchors" keychain.

openssl x509 -in /System/Library/OpenSSL/certs/ipop3d.pem -noout -fingerprint -subject -issuer


sudo ln -s /usr/include/pam /usr/include/security
sudo cp -p /private/etc/pam.d/ftpd /private/etc/pam.d/pop
#sudo cp -p /private/etc/pam.d/login /private/etc/pam.d/pop

cd ~/Desktop
curl -L -O http://www.macosxguru.net/downloads/localmail.zip
unzip -qq localmail.zip

sudo mkdir -p /usr/local/libexec
sudo cp ~/Desktop/localmail/ipop3d /usr/local/libexec/

sudo chown root:wheel /usr/local/libexec/ipop3d
sudo chmod 755 /usr/local/libexec/ipop3d

sudo cp ~/Desktop/localmail/edu.washington.pop3s.plist  /Library/LaunchDaemons/edu.washington.pop3s.plist


sudo nano /Library/LaunchDaemons/edu.washington.pop3s.plist

<?xml version="1.0" encoding="UTF-8"?>
DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.
com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Labelkey>
        edu.washington.pop3s</string>
        <key>ProgramArgumentskey>
        
                /usr/local/libexec/ipop3dstring>
        </array>
        <key>Socketskey>
        
                Listeners</key>
                <dict>
                        <key>Bonjourkey>
                        />
                        <key>SockServiceNamekey>
                        pop3s</string>
                        <key>SockTypekey>
                        stream</string>
                dict>
        </dict>
        <key>inetdCompatibilitykey>
        
                Wait</key>
                <false/>
        dict>
</dict>
plist>

sudo chown root:wheel /Library/LaunchDaemons/edu.washington.pop3s.plist
sudo chmod 644 /Library/LaunchDaemons/edu.washington.pop3s.plist


your_logname="$(/usr/bin/logname)"
echo $your_logname


sudo cp -p /private/etc/postfix/canonical /private/etc/postfix/canonical.orig
sudo nano /private/etc/postfix/canonical
<your_logname>: <your_logname>@localhost


sudo nano /private/etc/postfix/smtpd.conf
auxprop_plugin: login
pwcheck_method: auxprop
mech_list: plain login


sudo cp -p /private/etc/postfix/access /private/etc/postfix/access.orig
sudo nano /private/etc/postfix/access
localhost    OK
<your_logname>@localhost  OK
<your_logname>@local.local  OK
# cf. man hostname
<your_logname>@<your_hostname>  OK



# see man 5 postconf
# check with postconf -n
sudo nano /private/etc/postfix/main.cf

biff = no
command_directory = /usr/sbin
config_directory = /etc/postfix
daemon_directory = /usr/libexec/postfix
data_directory = /var/lib/postfix
debug_peer_level = 2
disable_vrfy_command = yes
html_directory = /private/etc/postfix/html
inet_interfaces = all
mail_owner = postfix
mailq_path = /usr/bin/mailq
manpage_directory = /usr/local/man
mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain
mydomain = localdomain
myhostname = localhost.localdomain
mynetworks = 127.0.0.0/24
mynetworks_style = host
myorigin = $mydomain
newaliases_path = /usr/bin/newaliases
queue_directory = /var/spool/postfix
readme_directory = /private/etc/postfix/readme
relayhost = [127.0.0.1]
#relayhost = [SMTP_server_address_of_your_ISP]
sample_directory = /etc/postfix
sender_canonical_maps = hash:/etc/postfix/canonical
sendmail_path = /usr/sbin/sendmail
setgid_group = postdrop
smtp_tls_cert_file = $smtpd_tls_cert_file
smtp_tls_key_file = $smtpd_tls_cert_file
smtp_tls_loglevel = 3
smtp_tls_note_starttls_offer = yes
smtp_tls_scert_verifydepth = 5
smtp_tls_session_cache_database = btree:/var/lib/postfix/smtp_tls_session_cache
smtp_use_tls = yes
smtpd_client_restrictions = check_client_access hash:/etc/postfix/access, reject_unknown_client
smtpd_helo_required = yes
smtpd_helo_restrictions = permit_mynetworks, reject_invalid_hostname, reject_non_fqdn_hostname
smtpd_recipient_restrictions = permit_mynetworks, reject_unauth_destination, reject_non_fqdn_recipient
smtpd_sender_restrictions = check_sender_access hash:/etc/postfix/access, reject_unknown_sender_domain
smtpd_tls_auth_only = yes
smtpd_tls_cert_file = /System/Library/OpenSSL/certs/ipop3d.pem
smtpd_tls_key_file = $smtpd_tls_cert_file
smtpd_tls_loglevel = 3
smtpd_tls_received_header = yes
smtpd_tls_session_cache_database = btree:/var/lib/postfix/smtpd_tls_session_cache
smtpd_use_tls = yes
tls_random_source = dev:/dev/urandom
unknown_local_recipient_reject_code = 550



# reload Postfix
function rpf() {
/usr/bin/sudo /usr/sbin/postmap /private/etc/postfix/access
/usr/bin/sudo /usr/sbin/postalias hash:/private/etc/postfix/canonical
/usr/bin/sudo /usr/bin/newaliases
/usr/bin/sudo /usr/sbin/postfix reload

/usr/bin/sudo /bin/launchctl unload -w /Library/LaunchDaemons/edu.washington.pop3s.plist  2>/dev/null
/usr/bin/sudo /bin/launchctl unload -w /System/Library/LaunchDaemons/org.postfix.master.plist 2>/dev/null

/bin/sleep 2

/usr/bin/sudo /bin/launchctl load -w /Library/LaunchDaemons/edu.washington.pop3s.plist  2>/dev/null
/usr/bin/sudo /bin/launchctl load -w /System/Library/LaunchDaemons/org.postfix.master.plist   2>/dev/null

return 0
}


rpf

sudo ln -s "/Applications/Utilities/Network Utility.app/Contents/Resources/stroke" /bin/portscan
portscan localhost 1  1000     #  Open TCP Port:  25  smtp; Open TCP Port:   995   pop3s


# now create a new mail account in Mail.app
Account Description: POP Account
Full Name: Your Name
Email Address: <your_logname>@localhost
User Name: <your_logname>
Password: <your system user account password>
Incoming Mail Server: localhost
SSL: on
Outgoing Mail Server: localhost
SSL: on
Mail -> Preferences ... -> Accounts -> POP Account -> Account Information -> Server Settings ...: 
- Server port: 25
- Use SSL -> [yes]
- Authentication -> None
Mail -> Preferences ... -> Accounts -> POP Account -> Advanced:
- Port: 995
- Use SSL -> [yes]
- Authentication -> Password


# ignore error message ...
The POP server "localhost" is not responding. Check your network connection and that you entered 
the correct information in the "Incoming Mail Server" field. If it still doesn't respond, the 
server might be temporarily unavailable.

If you continue, you may not be able to receive any email.

# ... but make sure SSL is actually being used in:
- Mail -> Preferences ... -> Accounts -> POP Account -> Account Information -> Server Settings ...
- Mail -> Preferences ... -> Accounts -> POP Account -> Advanced

# now quit Mail.app and save the changes made in Mail -> Preferences ... -> Accounts -> POP Account ... if necessary


open -a Mail


# dialog box 1:
- Enter Password for Account "POP Account"
- Please enter the password for user  on POP server "localhost"
- 
- [yes] Remember this password in my keychain


# dialog box 2:
- Unable to verify SSL server localhost
- Mail was unable to verify the identity of this server, which has a certificate issued to "localhost". The error was:

- The root certificate for this server could not be verified.
- ...

# Once again: if Mail.app complains about the newly created SSL certificate in the above way, just:
- Click "Show Certificate"
- Alt-Drag the icon for the certificate onto your desktop.
- Double-click the file.
- In the dialog box that will appear, use the drop down list to add the key to the "X509Anchors" keychain.
- enter your system user account password if prompted

killall Mail


# check Keychain Access items
open -a 'Keychain Access'

# cf. dialog box 1 above
Keychains -> login -> localhost -> click [i] -> Attributes
Name: localhost
Kind: Internet password
Account: 
Where: pop://localhost
Modified: 

Keychains -> login -> localhost -> click [i] -> Access Control
- [yes] Confirm before allowing access
#- [yes] Ask for Keychain password
- Always allow access by these applications: Name: Mail, Location: /Applications, Version: ...


# cf. dialog box 2 above
Keychains -> X509Anchors -> [Click to unlock the X509Anchors keychain] -> select "localhost - certificate -- X509Anchors" 
-> click [i] -> Trust Settings -> select Use System Settings or Always Trust 


#-------------------


# test

# curl -L -O http://www.unflyingobject.com/tarkvara/files/ssldump.zip
open /bin/bash
sudo ssldump -i lo0 port 995

open /bin/bash
sudo tcpdump -i lo0 port 995 and host localhost

# test 
echo 'hello world' | mail -s 'test mail' $(logname)@localhost
open -a Mail


Further information:

- How to read local Unix mail in Mail.app under Tiger?
- Enable postfix without inducing insomnia
- What is the difference between POP and IMAP?
- Setting up a local IMAP archive of your mail on Tiger
- Setting up IMAP in Apple Mail

Upgrading Postfix with TLS (SSL) support on Mac OS X

1. fix the command search path

echo '
export PATH="/usr/local/bin:/usr/local/sbin:/usr/local/lib:/usr/local/include:/usr/bin:/bin:/usr/sbin:/sbin"
' >> $HOME/.bash_login

source $HOME/.bash_login


2. upgrade Postfix

# first make a backup of the entire /private/etc/postfix directory
sudo /usr/bin/ditto -rsrc -c -k /private/etc/postfix "/private/etc/postfixdir-$(/bin/date "+%Y-%m-%d-%H.%M.%S").zip"

cd ~/Desktop
curl -L -O http://mirrors.isc.org/pub/postfix/official/postfix-2.5.0.tar.gz
tar -xzf postfix-2.5.0.tar.gz
cd postfix-2.5.0

# make -h


# cf. http://www.postfix.org/TLS_README.html
# requires Xcode, http://developer.apple.com/tools/download/

find /usr -type f \( -name "libcrypto*" -or -name "libssl*" \) -print0 2>/dev/null | xargs -0 ls -l

make makefiles \
   CFLAGS='-arch $(/usr/bin/arch) -isysroot /Developer/SDKs/MacOSX10.4u.sdk' \
   CCARGS="-DUSE_TLS" \
   AUXLIBS="-lssl.0.9.7 -lcrypto.0.9.7"


make

# sudo make install
# or
sudo make upgrade


3. remove comments & empty lines from /private/etc/postfix/main.cf

sudo cp -p /private/etc/postfix/main.cf /private/etc/postfix/main.cf.orig   # backup
sudo sed -i "" -e 's/^[[:space:]]*#.*$//g' -e '/^[[:space:]]*$/d' /private/etc/postfix/main.cf
sudo nano /etc/postfix/main.cf


4. create a new Postfix launch daemon

# backup
sudo cp -p /System/Library/LaunchDaemons/org.postfix.master.plist /System/Library/LaunchDaemons/org.postfix.master.plist.orig  

sudo nano /System/Library/LaunchDaemons/org.postfix.master.plist

<?xml version="1.0" encoding="UTF-8"?>
DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Disabledkey>
        />
        <key>Labelkey>
        org.postfix.master</string>
        <key>OnDemandkey>
        />
        <key>Programkey>
        /usr/libexec/postfix/masterstring>
        ProgramArguments</key>
        <array>
                <string>masterstring>
        </array>
        <key>QueueDirectorieskey>
        
                /var/spool/postfix/maildropstring>
        </array>
dict>
</plist>


sudo launchctl load -w /System/Library/LaunchDaemons/org.postfix.master.plist 2>/dev/null
#sudo launchctl unload -w /System/Library/LaunchDaemons/org.postfix.master.plist 2>/dev/null


5. initialize the configuration

sudo mv /private/etc/postfix/master.cf /private/etc/postfix/master.cf.orig
sudo cp -p /private/etc/postfix/master.cf.defaultserver /private/etc/postfix/master.cf

sudo nano /private/etc/postfix/master.cf
# uncomment the following line if necessary
#smtp      inet  n       -       n       -       -       smtpd     

sudo /usr/sbin/postfix reload


6. test

sudo ln -s "/Applications/Utilities/Network Utility.app/Contents/Resources/stroke" /bin/portscan
portscan localhost 25  25     #  Open TCP Port:  25  smtp

/usr/sbin/postconf -d | grep 'mail_version ='

sudo postfix check
sudo postfix status
#sudo postfix -vv status

open -a Console   # see /private/var/log/mail.log

dscl . -read /Users/postfix
dscl . -read /Groups/postfix
dscl . -read /Groups/postdrop
dscl . list /Groups GroupMembership

otool -Lv /usr/libexec/postfix/smtp       # libssl & libcrypto
otool -Lv /usr/libexec/postfix/smtpd
otool -Lv $(/usr/sbin/postconf -h daemon_directory)/smtpd


# send a mail 
echo 'hello world' | mail -s 'test mail' $(/usr/bin/logname)@localhost
mail   # quit with "q "

# send a mail via telnet

your_logname="$(/usr/bin/logname)"
echo $your_logname

telnet localhost 25
<...>
helo localhost
<...>
ehlo localhost
<...>
mail from:<your_logname>@localhost
<...>
rcpt to:<your_lognam>@localhost
<...>
data
<...>
subject: something
my message
.
<...>
quit

mail


Further information:

- Postfix Installation From Source Code
- Postfix Basic Configuration
- Postfix TLS Support
- Postfix on Mac OS X
- Troubleshooting Postfix
- DIYMacServer

Rewrite SPAM subject line with procmail

// Remove textdrive's ***SPAM*** addition
// by phearlez
// http://discuss.joyent.com/viewtopic.php?pid=154695#p154695

# Remove the word ***SPAM*** from SpamAssassin's subject line re-write

 :0 fHw
 * ^Subject: \*\*\*SPAM\*\*\*
 | sed -e 's/\*\*\*SPAM\*\*\*//g'

send email with attachment from command line

useful for sending db backups

echo command is for the body
-s specifies the subject
-a gives the attachment
finally the recipient
email will be sent as root@serveraxis
echo "database backup for 070614" | mutt -s "backup: myerasmus_db_070614" -a erasmus_db_070614.sql.bz2.gpg [email address]

Postfix virtual email

vi /etc/postfix/main.cf
virtual_alias_domains = domain1.tld domain2.tldvirtual_alias_maps = hash:/etc/postfix/virtual
vi /etc/postfix/virtual (ignore quotes)@domain1.tld user1@externaldomain1.tld’@domain2.tld user2@externaldomain2.tld’
newaliases
postmap /etc/postfix/virtual
/etc/init.d/postfix restart

Opened up SMTP port 25 in Shorewall:
vi /etc/shorewall/rules
SMTP/ACCEPT net $FW
/etc/init.d/shorewall reload

send mail with :login

// with ":login" you authenticate with user and password
// more info: Library Net:SMTP [Dave Thomas, The Pragmatc Programmer]
  # send email with :login
  def send_email(subject, message)
   
    from='sender@sender_address.de'
    from_alias='the sender'
    to='recipient@recip_address.de'
    to_alias='the recipient'
    smtp_host='smtp.1und1.com'
    port=25   # default port is 25
    user='username'
    password='its_a_secret'

    myMessage = <<END_OF_MESSAGE
From: #{from_alias} <#{from}>
To: #{to_alias} <#{to}>
Subject: #{subject}

#{message}
END_OF_MESSAGE

    Net::SMTP.start(smtphost, port, from, user, password, :login) do |smtp|
      smtp.send_message myMessage, from, to
    end
  end

backup multiple mysql databases and email results

// remember to check that the path is correct.
// This is running on a dedicated server on TextDrive

#!/bin/sh

# This file will run a backup of your desired MySQL database and
# remove any backups older than 7 days.
#
# If youOd like to preserve backups for longer than a week, like say 
# 2 weeks, then set the '-mtime' value from '+7' to '+14'.
#

TIME_STAMP=`date "+%Y-%m-%d"`
echo "starting "$0" on" `date`
for db in db1 db2 db3
do
  DB_STAMP=${db}_${TIME_STAMP}
  echo ${DB_STAMP}
  /opt/csw/mysql5/bin/mysqldump --opt --skip-add-locks --user=username --password=password ${db} | gzip > /domains/backups/mysql/${DB_STAMP}.gz
  /opt/csw/bin/mutt -s "mysql  ${TIME_STAMP}"  -a /domains/backups/mysql/${DB_STAMP}.gz someuser@somedomain.com dev/null
done

cd /domains/backups/mysql/

/usr/bin/find *.gz -mtime +14 -exec rm {} \;
echo "finished "$0" on" `date`

Running Mutt w/Maildirs (not IMAP) on TxD servers via ssh

I modified Pteron's muttrc file to use my local Maildir rather than login via IMAP.

This is A) Faster/better since it cuts out the bother of an imap connection to localhost and accesses your mail directly, B) It actually works (the imap method always failed on a segfault for me at least), C) You gotta like not having to store your username/password in the clear since there's no imap login to perform D) More responsive than webmail for quick email checks, and works even when webmail doesn't.

To use, change the realname line and save with filename ".muttrc"; upload this to your home directory, then login via ssh and type "mutt".

# For TextDrive accounts (running mutt on the server)

set mbox_type=Maildir
set folder="~/Maildir/"
set spoolfile="~/Maildir/"
set mask="!^\\.[^.]"
set record="+.Sent"
set postponed="+.Drafts"

set realname="Yourname"

mailboxes `\
echo -n "+ "; \
for file in ~/Maildir/.*; do \
  box=$(basename $file); \
  if [ ! $box = '.' -a ! $box = '..' -a ! $box = '.customflags' \
      -a ! $box = '.subscriptions' ]; then \
    echo -n "+$box "; \
  fi; \
done`

macro index c "?" "open a different folder"
macro pager c "?" "open a different folder"

set allow_8bit  # Don't do any Quoted-Printable encoding on 8-bit data!
set copy=yes    # Ask me if I want to save a copy of my outgoing messages.
set delete=yes
set noaskcc
set nomark_old
set reverse_alias
set reverse_name
set reply_to
set attribution="On %d, %n wrote:"
set envelope_from
set noconfirmappend
set print=ask-no
set print_cmd="echo Nix printi printi!"
set nosave_empty
set sort=threads
set read_inc=10
set write_inc=10
set noprompt_after
set status_format="%r %v [%?M?%M/?%m] %?n?%n new, ?%?p?%p postponed, ?%?t?%t +tagged, ?%?d?%d delet ed, ?(%h:%f) %?b?%b more to go.?%> %r"

#set alias_file="~/.aliases"
set quote_regexp="^([A-Za-z ]+>|[]>:|}-][]>:|}-]*)"
set include
set hdr_format="%4C %Z %{%b %d} %-15.15n (%4l) %s"
set nomove
set tilde
set noautoedit
set pager_context=1
set pager_stop
set pipe_decode
set postponed="+postponed"
set to_chars="b .c>"

set fast_reply

color header brightcyan black .
color header yellow black Subject:
color body brightyellow black [_a-z\.\$A-Z0-9-]+@[a-zA-Z0-9\./\-]+
color body yellow black (http|ftp)://[_a-zA-Z0-9\./~\-]+
color quoted green black
color signature brightblue black
color attachment yellow black
color tree red black
color indicator black cyan
color status yellow blue
color tilde blue black

bind pager 'w' previous-page
bind pager 'j' next-line
bind pager 'k' previous-line
bind index '#' tag-entry
bind index '{' previous-thread
bind index '}' next-thread

# Headers to ignore
ignore *
unignore date from to cc subject x-mailer resent-from reply-to

PHP e-mail validator

// regular expression to check for e-mail address validity

function valid_email($email) {

  if( eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email) ) { 
    return true;
  }
  else { 
    return false;
  }

}

Validate an email address

I don't remember where this came from, but it's very useful for validating input from a form


function valid_email($email) {

  if( eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email) ) { 
    return true;
  }
  else { 
    return false;
  }

}

Measure the daily number of E-mail messages in a mailbox

This snippet written in bash with calls to perl from the command line measures the number of E-mail messages sent to a mailbox per calendrical day.

#!/bin/bash
grep -h '^Date:' * |
    perl -pe 's!^Date: !!' |
    perl -pe 's!^\w\w\w, !!' |
    perl -pe 's{\d{2}:\d{2}:\d{2}.*$}{}' |
    perl -pe 's!^\s+!!' |
    perl -pae '$_=sprintf("%.2d-%s-%s\n", @F)' |
    sort | uniq -c | sort -n


I used perl for some places where sed would have been more suitable because I find the sed regexp syntax confusing. :-)

Quickly put a bunch of emails into one file

A little bit of Python I used to run through a couple hundred emails in an Evolution folder and put their contents (minus headers) into one file for analysis.

import os, re
output_file = open('/path/to/output/file', 'a')
email_pat = re.compile('^\d+\.$')
[output_file.write(open(email).read().split('From: ')[1]) for email in os.listdir(os.getcwd()) if email_pat.match(email)]

extract email addresses

<?php

function extract_emails_from($string){
  preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $string, $matches);
  return $matches[0];
}

$text = "blah blah blah [email protected] blah blah blah [email protected]";

$emails = extract_emails_from($text);

print(implode("\n", $emails));

?>


Context: http://forum.textdrive.com/viewtopic.php?pid=46783

Howto Send Email When Rails Throws An Exception

Add the following to your application.rb:

  protected  

  def log_error(exception) 
    super(exception)

    begin
      ErrorMailer.deliver_snapshot(
        exception, 
        clean_backtrace(exception), 
        @session.instance_variable_get("@data"), 
        @params, 
        @request.env)
    rescue => e
      logger.error(e)
    end
  end


Taken from http://wiki.rubyonrails.com/rails/show/HowtoSendEmailWhenRailsThrowsAnException

rip calendar attachments from an email (in ruby)

See here for context.

I did this for undees

#!/usr/local/bin/ruby
$: << '/home/username/usr/local/lib/ruby/site_ruby/1.8'
require 'tmail'

s = $stdin.read
mail = TMail::Mail.parse s
mail.parts.each do |part|
  if 'text/calendar' == part.content_type
    t = part.body
    t.gsub!(/=[\r\n]+/, '')
    t.gsub!(/=(\w\w)/) {$1.hex.chr}
    
    outPath = '/home/username/path/to/Calendar.ics'
    File.open outPath, 'w' do |f|
      f.write t
    end
    File.chmod 0664, outPath    
  end
end

Validate email addresses with RegEx

Regular Expression to really validate email addresses.
[from Paul Warren via photomatt.net]

(Note: I haven't personally used this, but it's been sitting in my bookmarks bar for quite a while...)

(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?: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 \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*
)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]
)+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)
*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+
|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r
\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:
\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t
]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031
]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](
?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?
:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?
:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?
:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?
[ \t]))*"(?:(?:\r\n)?[ \t])*)*:(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\] 
\000-\031]+(?:(?:(?:\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(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\
r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] 
\000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]
|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \0
00-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\
.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,
;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?
:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*
(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".
\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[
^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]
]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)(?:,\s*(
?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(
?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[
\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t
])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t
])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?
:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|
\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:
[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\
]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)
?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["
()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)
?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>
@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[
 \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,
;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t]
)*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?
(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".
\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:
\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[
"()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])
*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])
+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\
.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z
|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(
?:\r\n)?[ \t])*))*)?;\s*)

rip calendar attachments from an email

See here for context.

#!/usr/bin/env /usr/local/bin/python

import sys, email

msg = email.message_from_string(sys.stdin.read())

for part in msg.walk():
  if part.get_content_type() == 'text/calendar':
    f = open(part.get_filename(), 'w')
    f.write(part.get_payload())
    f.close()

Clearing out a bunch of spam with spoofed emails that were bounced back to some poor guy with a catchall email

We don't really want to delete them all just in case.

cd /usr/local/scratch/
mkdir junk
find /var/spool/postfix -exec grep "somediscernible-feature.com" '{}' \; | awk '{print($3)}' | xargs -J X mv X ./junk/


The "find" produces

Binary file /var/spool/postfix/active/D/D8832E38 matches
Binary file /var/spool/postfix/active/D/D78EC1C72 matches
Binary file /var/spool/postfix/active/D/D593D279D matches
Binary file /var/spool/postfix/active/D/D0EB32833 matches


The awk

/var/spool/postfix/active/D/D8832E38
/var/spool/postfix/active/D/D78EC1C72
/var/spool/postfix/active/D/D593D279D
/var/spool/postfix/active/D/D0EB32833


And then the mv, moves it.
« Newer Snippets
Older Snippets »
18 total  XML / RSS feed