feluelle commented on a change in pull request #3661: [AIRFLOW-2780] Adds IMAP 
Hook to interact with a mail server
URL: https://github.com/apache/incubator-airflow/pull/3661#discussion_r217061994
 
 

 ##########
 File path: airflow/contrib/hooks/imap_hook.py
 ##########
 @@ -0,0 +1,262 @@
+# -*- coding: utf-8 -*-
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import email
+import imaplib
+import re
+
+from airflow import LoggingMixin
+from airflow.hooks.base_hook import BaseHook
+
+
+class ImapHook(BaseHook):
+    """
+    This hook connects to a mail server by using the imap protocol.
+
+    :param imap_conn_id: The connection id that contains the information
+                         used to authenticate the client.
+                         The default value is 'imap_default'.
+    :type imap_conn_id: str
+    """
+
+    def __init__(self, imap_conn_id='imap_default'):
+        super(ImapHook, self).__init__(imap_conn_id)
+        self.conn = self.get_connection(imap_conn_id)
+        self.mail_client = imaplib.IMAP4_SSL(self.conn.host)
+
+    def __enter__(self):
+        self.mail_client.login(self.conn.login, self.conn.password)
+        return self
+
+    def __exit__(self, exc_type, exc_val, exc_tb):
+        self.mail_client.logout()
+
+    def has_mail_attachment(self, name, mail_folder='INBOX', 
check_regex=False):
+        """
+        Checks the mail folder for mails containing attachments with the given 
name.
+
+        :param name: The name of the attachment that will be searched for.
+        :type name: str
+        :param mail_folder: The mail folder where to look at.
+                            The default value is 'INBOX'.
+        :type mail_folder: str
+        :param check_regex: Checks the name for a regular expression.
+                            The default value is False.
+        :type check_regex: bool
+        :returns: True if there is an attachment with the given name and False 
if not.
+        :rtype: bool
+        """
+        mail_attachments = self._retrieve_mails_attachments_by_name(name, 
mail_folder,
+                                                                    
check_regex,
+                                                                    
latest_only=True)
+        return len(mail_attachments) > 0
+
+    def retrieve_mail_attachments(self, name, mail_folder='INBOX', 
check_regex=False,
+                                  latest_only=False):
+        """
+        Retrieves mail's attachments in the mail folder by its name.
+
+        :param name: The name of the attachment that will be downloaded.
+        :type name: str
+        :param mail_folder: The mail folder where to look at.
+                            The default value is 'INBOX'.
+        :type mail_folder: str
+        :param check_regex: Checks the name for a regular expression.
+                            The default value is False.
+        :type check_regex: bool
+        :param latest_only: If set to True it will only retrieve
+                            the first matched attachment.
+                            The default value is False.
+        :type latest_only: bool
+        :returns: a list of tuple each containing the attachment filename and 
its payload.
+        :rtype: a list of tuple
+        """
+        mail_attachments = self._retrieve_mails_attachments_by_name(name, 
mail_folder,
+                                                                    
check_regex,
+                                                                    
latest_only)
+        return mail_attachments
+
+    def download_mail_attachments(self, name, local_output_directory, 
mail_folder='INBOX',
+                                  check_regex=False, latest_only=False):
+        """
+        Downloads mail's attachments in the mail folder by its name
+        to the local directory.
+
+        :param name: The name of the attachment that will be downloaded.
+        :type name: str
+        :param local_output_directory: The output directory on the local 
machine
+                                       where the files will be downloaded to.
+        :type local_output_directory: str
+        :param mail_folder: The mail folder where to look at.
+                            The default value is 'INBOX'.
+        :type mail_folder: str
+        :param check_regex: Checks the name for a regular expression.
+                            The default value is False.
+        :type check_regex: bool
+        :param latest_only: If set to True it will only download
+                            the first matched attachment.
+                            The default value is False.
+        :type latest_only: bool
+        """
+        mail_attachments = self._retrieve_mails_attachments_by_name(name, 
mail_folder,
+                                                                    
check_regex,
+                                                                    
latest_only)
+        self._download_files(mail_attachments, local_output_directory)
+
+    def _retrieve_mails_attachments_by_name(self, name, mail_folder, 
check_regex,
+                                            latest_only):
+        all_matching_attachments = []
+
+        self.mail_client.select(mail_folder)
+
+        for mail_id in self._list_mail_ids_desc():
+            response_mail_body = self._fetch_mail_body(mail_id)
+            matching_attachments = self._check_mail_body(response_mail_body, 
name,
+                                                         check_regex, 
latest_only)
+            if matching_attachments:
+                all_matching_attachments.extend(matching_attachments)
+                if latest_only:
+                    break
+
+        self.mail_client.close()
+
+        return all_matching_attachments
+
+    def _list_mail_ids_desc(self):
+        result, data = self.mail_client.search(None, 'All')
+        mail_ids = data[0].split()
+        return reversed(mail_ids)
+
+    def _fetch_mail_body(self, mail_id):
+        result, data = self.mail_client.fetch(mail_id, '(RFC822)')
+        mail_body = data[0][1]  # The mail body is always in this specific 
location
+        mail_body_str = mail_body.decode('utf-8')
+        return mail_body_str
+
+    def _check_mail_body(self, response_mail_body, name, check_regex, 
latest_only):
+        mail = Mail(response_mail_body)
+        if mail.has_attachments():
+            return mail.get_attachments_by_name(name, check_regex, 
find_first=latest_only)
+
+    def _download_files(self, mail_attachments, local_output_directory):
+        for name, payload in mail_attachments:
+            with open(local_output_directory + '/' + name, 'wb') as file:
+                file.write(payload)
+
+
+# TODO: Check if it isn't possible to use iter_attachments
 
 Review comment:
   btw.. there is an 
[iter_attachments](https://docs.python.org/3/library/email.message.html#email.message.EmailMessage.iter_attachments)
 method but this apparently does not work correctly so I made a Mail class that 
iterates through all assets and checks if it is really a valid attachment.
   I hope I can change this in the future.
   

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services

Reply via email to