I have this python script for inserting raw email to db. Do not ask me why I am inserting raw mail to database.
import sys
from DB import *
import email
full_msg = sys.stdin.readlines()
j = ''.join(full_msg)
msg = email.message_from_string(j)
sql = '''INSERT INTO Email(Id, Message) VALUES (NULL, %s)'''
db = DB()
db.query(sql, (msg, ))
It would be great if I can get uid of that message, so if I for example delete message from db I can also delete message my uid on imap server.
I do not want to login to imap server and then delete message by uid because I do not know user password since it is encrypted.
I was thinking to get for example msg['Message-Id'] and then to grep files in user maildir for that Message-Id and delete actual file but that sound totally wrong to me.
I know in python you have something like UIDNEXT in imaplib but that is under assumption I am logged in which I'm not.
UPDATE:
With this I can fetch next uid but I have to login. How to get UIDNEXT without login? By the way I use postfix/dovecot with mysql.
import getpass, sys
from imapclient import IMAPClient
try:
hostname, username = sys.argv[1:]
except ValueError:
print 'usage %s hostname username' % sys.argv[0]
c = IMAPClient(hostname, ssl=True)
try:
c.login(username, getpass.getpass())
except c.Error, e:
print "Could not login in:", e
sys.exit(1)
else:
select_dict = c.select_folder('INBOX', readonly=True)
for k, v in select_dict.items():
if k == 'UIDNEXT':
print '%s: %r' % (k,v)
c.logout()
NEW UPDATE
Sample of dovecot-uidlist
16762 W105493 S104093 :1417408077.2609_1.zumance
16763 S18340 W18608 :1417429204.3464_1.zumance
Code for geeting last line of dovecot-uidlist uid:
l = open("dovecot-uidlist").readlines()
print l[-1].split(" ")[0]
This is completed script for mail pipe:
import sys
import email
import re
from DB import *
full_msg = sys.stdin.readlines()
j = ''.join(full_msg)
msg = email.message_from_string(j)
match = re.search(r'[\w\.-]+@[\w\.-]+', msg['to'])
address = match.group(0)
address = address.split("@")
with open("/var/vmail/"+address[1]+"/"+address[0]+"/dovecot-uidlist", 'r') as f:
first_line = f.readline()
nextuid = first_line.split(" ")
nextuid = re.findall(r'\d+', nextuid[2])
sql = '''INSERT INTO Email(Id, Message, Uid, Domain, Mbox) VALUES (NULL, %s, %s, %s, %s)'''
db = DB()
db.query(sql, (msg, nextuid[0], address[1], address[0], ))
Blog post with files at https://pregmatch.org/read/python-procmail