Задача - забираем почту по крон из Microsoft Exchange Server, сохраняем аттачи в отдельную папку. Для решения задачи, будем использовать скрипт на python, добавленный в cron и библиотеку exchangelib
Устанаваливаем необходимые библиотеки
yum -y install python-devel gcc libxml2 libxml2-devel libxslt libxslt-devel
Устанавливаем и активируем виртуальное окружение
virtualenv -ppython2.7 env
source env/bin/activate
(env) pip install exchangelib
Если при подключении возникает предупреждение с самоподписным ssl сертификатом.
/env/local/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py:852: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
Можно его отключить
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
Напишем скрипт сохраняющий аттачи.
$ nano save_attachments.py
# -*- coding: utf-8 -*-
from exchangelib import DELEGATE, Account, Credentials, Configuration, NTLM
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from exchangelib.folders import FileAttachment
import os
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
config = Configuration(
server='ir-mx-01.sats.local', #192.168.160.90
credentials=Credentials(username='DOMEN\username', password='secret'),
auth_type=NTLM,
verify_ssl=False
)
account = Account(
primary_smtp_address='email@outlook.com',
config=config,
access_type=DELEGATE,
)
for item in account.inbox.all().order_by('-datetime_received'):
for attachment in item.attachments:
if isinstance(attachment, FileAttachment):
local_path = os.path.join('/tmp', attachment.name)
with open(local_path, 'wb') as f:
f.write(attachment.content)
print('Saved attachment to', local_path)
item.delete()
Всё готово, спасибо за внимание. Тешу себя надеждой что может быть кому-то этот скрипт будет полезен.
comments powered by Disqus