Использование maildrop

Введение

maildrop выполняет функцию почтового фильтра и почтового агента, который используется Courier Mail сервером. Вам не нужно выкачивать maildrop, если у вас уже установлен Courier. В стандартной поставке maildrop почтовый фильтр может быть использован совместо с другими почтовыми серверами.

maildrop создан для замены локального почтового агента. maildrop читает почтовое сообщение через стандартный ввод и доставляет его в ваш почтовый ящик. maildrop может доставлять почту в mbox или maildirs. "maildir" это формат, используемый серверами Courier и Qmail.

maildrop дополнительно читает инструкции из файла, в котором правила описывают, каким образом фильтровать входящую почту. Эти правила могут перенаправить почту в другой почтовый ящик или куда нибудь еще, в зависимости от указаний. В отличие от procmail, maildrop использует структурированный язык фильтрации.

maildrop написан на C++, и значительно больше, чем procmail, хотя использует ресурсы более эффективно. В отличие от procmail, maildrop не будет читать сообщение размером 10 MB целиком в память. Сообщение будет записано на диск как временный файл и затем применятся правила фильтрации. Если стандартный ввод является файлом, а не конвейером, то во временном файле необходимости нет.

maildrop проверяет правила фильтрации прежде чем доставить сообщение. В отличие от procmail, если правила написаны с ошибками, maildrop отключится без доставки сообщения. Пользователь может исправить ошибку и затем получить сообщение. Таким образом мы не потеряем сообщения.


Установка

Тривиально emerge maildrop


Конфигурация


Для всех

/etc/maildroprc

File: /etc/maildroprc
# Global maildrop filter file
#DEFAULT="$HOME/.maildir/"

#
# Define variables
#
SHELL="/bin/bash"
DEFAULT = "$HOME/.maildir"
MAILDIR = "$HOME/.maildir"

#
# Logfile destination
# After your satisifed that this is working properly, comment out all
# the lines that start with "log"
#
logfile "$HOME/.getmail/.maildrop.log"
#
# Markers for the log file
#
log "Markers: ---------------------------------------------"
log " (**) from config file, (II) informational, (WW) warning"
log "--------------------------------------------------------"
log ""



######################################################################
#
# Adding missing headers for PGP/MIME
#

BPM="-----BEGIN PGP MESSAGE-----"
EPM="-----END PGP MESSAGE-----"
BPS="-----BEGIN PGP SIGNATURE-----"
EPS="-----END PGP SIGNATURE-----"

if (!/^Content-Type: message/ && !/^Content-Type: multipart/ \
&& !/^Content-Type: application\/pgp/)
{
if (/^$BPM/:b && /^$EPM/:b)
xfilter "reformail -A 'Content-Type: application/pgp; format=text; \
x-action=encrypt'"

if (/^$BPS/:b && /^$EPS/:b)
xfilter "reformail -A 'Content-Type: application/pgp; format=text; \
x-action=sign'"
}


#####################################################################
#
# Correcting wrong signature dashes
# it doesn't work, need to fix

if ( /^--$/:b)
{
xfilter "sed -e 's/^--$/-- /'"
log "(II) Sig Dashes corrected"
}

# Include any rules set up for the user - this gives the
# administrator a way to override the domain's mailfilter file
#
# this is also the "suggested" way to set individual values
# for maildrop such as quota. (why do you need quota on your own PC?)
#

`test -r $HOME/.mailfilter`
if( $RETURNCODE == 0 )
{
log "(==) Including $HOME/.mailfilter"
exception {
include $HOME/.mailfilter
}
}


Персонально

  • ~/.mailfilter будет вызываться из /etc/maildroprc

touch ~/.mailfilter

  • Необходимо выставить правильные права на файл (иначе будет выдавать ошибку)

chmod 600 ~/.mailfilter

  • Ну и сами правила фильтрации на разные случаи жизни
File: ~/.mailfilter
# - maildrop mailinglist.
# http://lists.sourceforge.net/lists/listinfo/courier-maildrop

# - Please browse the mailinglist archives for more examples.
# http://sourceforge.net/mailarchive/forum.php?forum=courier-maildrop

# - Save this file as .mailfilter in your home directory and do
# chmod 600 .mailfilter

# - Do not edit your .mailfilter file with a DOS or WINDOWS
# texteditor!!


# - Linebreaking doesn't work inside a pattern. So the following
# rule cannot work:
#
#if (/^Subject:.*(exim|sendmail| \
# gdm|xdm|imap|cgi)/)
#
# and must be in one line:
#
# if (/^Subject:.*(exim|sendmail|gdm|xdm|imap|cgi)/)
#
#
# - Linebreaking only works for quotet text and between patterns:
#
# "Imagine this is as a \
# long text string"
#
#
#if (/^To:.*mutt/ \
# || /^[Cc][Cc]:.*mutt/)
#

#''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
# Spam messages with numbered subjects
#
if (/^Subject:.*[:wbreak:][:digit:][:digit:][:digit:][:digit:][:wbreak:]/ \
&& !/^Precedence: bulk/)
{
exception {
to $DEFAULT/.Trash/
}
}


#''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
# What we can find in the header
if ( /^X-Advertisement:.*/ \
|| /^X-Mailer:.*(Advanced Mass)/ \
|| /^X-Spam-Status: YES / \
|| /^Message-ID:*<>/ )
{
exception {
to $DEFAULT/.Trash/
}
}

#''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
# Spam addresses From:
if (/^From:.*(galamail\.com|agentoflove|absoluteagency\.com|delphi\.com|238525) /)
{
exception {
to $DEFAULT/.Trash/
}
}


#''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
# Spam addresses To:
if (/^To:.*(spambot|undisclosed recipient)/ )
{
exception {
to $DEFAULT/.Trash/
}
}


#''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
# Long Subject spam words

# IT SHOULD BE JUST ONE LONG LINE (breaks are for wiki purpuses)
if (/^Subject:.*(SPAM|\[Vv\]iagra|offer|free|wanted|penis|chip|inch|please|pill|ydrocodone|remember|
prescription|1-800|inch|remove|XXX|sex|adults|business opportunity|unsuscribe|LANGUAGE CENTER|visit today|
penis|longer|size|GUARANTEE|\[Ll\] \[Aa\] \[Nn\] \[Gg\] \[Uu\] \[Aa\] \[Gg\] \[Ee\] ) / )
{
exception {
to $DEFAULT/.Trash/
}
}


#''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
# Trashing offtopic messages
if (/^Subject:.*(\[ot\]|\<ot\>|\[off\]|\[.*[ ]ot\])|off.*topic/)
{
exception {
to $DEFAULT/.Trash/
}
}

#''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
# Trashing test messages
if (/^Subject:test$/)
{
exception {
to $DEFAULT/.Trash/
}
}


if (/^Subject:.*[ ]test$/)
{
exception {
to $DEFAULT/.Trash/
}
}

#''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
# .Personal
#
if ( /^From:.*(friend_1|friend_2|friend_3)/ )
{
exception {
to $DEFAULT/.Personal/
}
}


#''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
# .2root
#
if (/^Subject:.*Cron/ || /^To:.*root/ )
{
exception {
to $DEFAULT/.2root/
}
}

#''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
# .yourmailbox
#
if (/^To:.*yourmailbox/)
{
exception {
to $DEFAULT/.youmailbox/
}
}

####################################################################
# .mailing lists and forums

#''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
# .gentoo-wiki
if ( /^Reply-To:.*devel@gentoo-wiki\.com/ \
|| /^Reply-To:.*users@gentoo-wiki\.com/ )
{
exception {
to $DEFAULT/.gentoo-wiki/
}
}

#''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
# .forums.gentoo-org
if (/^From:.*blackhole@forums\.gentoo\.org/ )
{
exception {
to $DEFAULT/.forums-gentoo/
}
}

#''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
# .courier-maildrop
if (/^List-Post:.*courier-maildrop*/ )
{
exception {
to $DEFAULT/.list.courier-maildrop/
}
}

  • Почтовые ящики для каждого правила необходимо создать вручную (иначе будет ругаться)

maildirmake -f Folder.Name $HOME/.maildir

  • И подписаться на вновь созданные почтовые ящики

echo INBOX.Folder.Name >> $MAILDIR/courierimapsubscribed


Интеграция с postfix

Надо сообщить postfix, кто у нас работает на локальной доставке, так что vim /etc/posfix/main.cf

File: /etc/posfix/main.cf
# The mailbox_command parameter specifies the optional external
# command to use instead of mailbox delivery. The command is run as
# the recipient with proper HOME, SHELL and LOGNAME environment settings.
# Exception: delivery for root is done as $default_user.
#
# Other environment variables of interest: USER (recipient username),
# EXTENSION (address extension), DOMAIN (domain part of address),
# and LOCAL (the address localpart).
#
# Unlike other Postfix configuration parameters, the mailbox_command
# parameter is not subjected to $parameter substitutions. This is to
# make it easier to specify shell syntax (see example below).
#
# Avoid shell meta characters because they will force Postfix to run
# an expensive shell process. Procmail alone is expensive enough.
#
# IF YOU USE THIS TO DELIVER MAIL SYSTEM-WIDE, YOU MUST SET UP AN
# ALIAS THAT FORWARDS MAIL FOR ROOT TO A REAL USER.
#
#mailbox_command = /some/where/procmail
#mailbox_command = /some/where/procmail -a "$EXTENSION"
mailbox_command = /usr/bin/maildrop

## Set to 1 because Maildrop only delivers one message at a time.
maildrop_destination_recipient_limit = 1

vim /etc/postfix/master.cf Примерно 113 строчка

File: /etc/postfix/master.cf
maildrop unix - n n - - pipe 

# объедините две последующие линии в одну!
flags=DRhu user=vmail:vmail argv=/usr/bin/maildrop -w 90 -d ${user} ${nexthop}
${extension} ${recipient} ${user}${nexthop} #thats should be joined with the above line!

# So what does maildrop do with all of these? The above looks somewhat
# redundant, as ${recipient} is made up of ${user}+${extension}@${nexthop}.
#
# Magic from a recipe :-).
#
#The answer: in the maildropfilter file, $recipient becomes $1, $user
#$2, etc. So for my purposes, $recipient is sufficient. In addition,
#I must put this, or something similar, in the maildropfilter:
# xfilter "reformail -I 'X-Panix-Recipient: $1'"

После изменения конфигурации перезапускаем postfix /etc/init.d/postfix restart


Интеграция с Qmail

Те, кто столкнулся с настройкой maildrop совместно с qmail, пожалуйста, допишите раздел.


Проблемы и решения


Invalid home directory permissions - world writable.

При получении сообщения вида:

Delivery error (command maildrop 24688 error (75, /usr/bin/maildrop: 
Invalid home directory permissions - world writable.))
msg 1/1 (812 bytes), delivery error (command maildrop 24688 error (75, /usr/bin/maildrop:
Invalid home directory permissions - world writable.))
1 messages retrieved, 0 skipped
Решение

chmod 600 ~/.mailfilter

 


For your own good

При получении сообщения:

Delivery error (command maildrop 5485 error (75, /usr/bin/maildrop: 
Cannot have world/group permissions on the filter file - for your own good.))
msg 1/1 (842 bytes), delivery error (command maildrop 5485 error (75, /usr/bin/maildrop:
Cannot have world/group permissions on the filter file - for your own good.))
Решение:

Избавиться от строки [arguments] в ~/.getmail/youmailbox.rc файле


Unable to create a dot-lock

При получении сообщения:

Delivery error (command maildrop 10143 error (75, /usr/bin/maildrop: Unable to create a dot-lock.))
msg 1/1 (3612 bytes), delivery error (command maildrop 10143 error
(75, /usr/bin/maildrop: Unable to create a dot-lock.))
1 messages retrieved, 0 skipped
Решение:

В файле ~/.mailfilter правило указывает на доставку сообщения в определенную директорию, которая не существует, в результате чего и выдается такое сообщение. Так что проверьте правила доставки и наличие директории.


Использованные источники

ru.gentoo-wiki.com