我们的办公室使用2个IMAP服务器进行电子邮件,一个是传入服务器并保存最近的电子邮件,另一个是归档服务器。我们主要使用Outlook 2010,而我们当前的过程是定期将发送的邮件从传入服务器拖动到存档。将邮件从一个IMAP服务器移动到另一个IMAP服务器的脚本
今天我被要求研究编写脚本,并定期(可能使用crontab)抓住所有发送的消息并将它们移动到归档。
我已经看过一些SSL或telnet访问服务器和周围的例子。但是,我不知道在IMAP环境中编写脚本或如何移动文件跨服务器的最佳方式。
完成此操作的最佳方法是什么?我宁愿仅仅从舒适的角度来使用Python,但如果已经有另一种语言的现有解决方案,我可以处理它。
更新:
好吧,这里是一些代码。目前它复制消息就好了,但是,它会复制存档服务器上的现有消息。
import imaplib
import sys
#copy from
f_server = 'some.secret.ip.address'
f_username = '[email protected]'
f_password = 'password'
f_box_name = 'Sent Messages'
#copy to
t_server = 'archive.server.i.p'
t_username = 'username'
t_password = 'password'
t_box_name = 'test'
To = imaplib.IMAP4(t_server)
To.login(t_username, t_password)
print 'Logged into mail server'
From = imaplib.IMAP4(f_server)
From.login(f_username, f_password)
print 'Logged into archive'
From.select(f_box_name) #open box which will have its contents copied
print 'Fetching messages...'
typ, data = From.search(None, 'ALL') #get all messages in the box
msgs = data[0].split()
sys.stdout.write(" ".join(['Copying', str(len(msgs)), 'messages']))
for num in msgs: #iterate over each messages id number
typ, data = From.fetch(num, '(RFC822)')
sys.stdout.write('.')
To.append(t_box_name, None, None, data[0][1]) #add a copy of the message to the archive box specified above
sys.stdout.write('\n')
try:
From.close()
From.logout()
try:
To.close()
To.logout()
一些来源:
Doug Hellman's Blog: imaplib - IMAP4 Client Library
Tyler Lesmann's Blog: Copying IMAP Mailboxes with Python and imaplib
我还需要:
- 删除/直播服务器
- 不可复制副本(在清除邮件实际上这将是通过复制后删除原件进行修复,但...)
- 错误捕获
更新2:
人对如何不创建重复复印时,任何想法? (现在不包括删除原件的选项),我想过要搜索文本,但是意识到嵌套的回复可能会导致这种情况。
rsync是从一个系统复制到另一个系统的选项吗? –