Преглед изворни кода

Merge pull request #35 from Miksus/ref/rename_user_name

ENH: Rename user_name
Mikael Koli пре 3 година
родитељ
комит
e1a8447d8c

+ 6 - 4
ci/test_send.py

@@ -10,7 +10,7 @@ load_dotenv()
 email = EmailSender(
     host=os.environ['EMAIL_HOST'],
     port=int(os.environ['EMAIL_PORT']),
-    user_name=os.environ['EMAIL_USERNAME'],
+    username=os.environ['EMAIL_USERNAME'],
     password=os.environ['EMAIL_PASSWORD']
 )
 
@@ -111,7 +111,8 @@ def send_images():
     plt.plot([1,2,3,2,3])
 
     email.send(
-        receivers=[os.environ['EMAIL_RECEIVER']],
+        sender=f"An Alias <{os.environ['EMAIL_SENDER']}>",
+        receivers=[os.environ['EMAIL_RECEIVERS']],
         subject="Embedded images",
         html='''
             <p>Dict image (JPEG):</p>
@@ -127,8 +128,8 @@ def send_images():
                 'subtype': 'jpg',
             },
             "plot_image": fig,
-            "path_image": Path(__file__).parent / "example.png",
-            "path_image_str": str((Path(__file__).parent / "example.png").absolute()),
+            "path_image": Path(__file__).parent.parent / "docs/imgs/email_emb_img.png",
+            "path_image_str": str((Path(__file__).parent.parent / "docs/imgs/email_emb_img.png").absolute()),
         }
     )
 
@@ -218,6 +219,7 @@ if __name__ == "__main__":
         "bodies": fn_bodies,
         "full": fn_bodies + fn_attachments + fn_log,
         "logging": fn_log,
+        "images": fn_imgs,
     }[os.environ.get("EMAIL_FUNCS", "full")]
     for func in funcs:
         print("Running:", func.__name__)

+ 3 - 3
docs/tutorials/config.rst

@@ -21,7 +21,7 @@ and then you can use the sender:
 .. code-block:: python
 
     from redmail import outlook
-    outlook.user_name = 'example@hotmail.com'
+    outlook.username = 'example@hotmail.com'
     outlook.password = '<YOUR PASSWORD>'
 
     outlook.send(
@@ -66,7 +66,7 @@ server pre-configured:
 .. code-block:: python
 
     from redmail import gmail
-    gmail.user_name = 'example@gmail.com' # Your Gmail address
+    gmail.username = 'example@gmail.com' # Your Gmail address
     gmail.password = '<APP PASSWORD>'
 
     # And then you can send emails
@@ -88,7 +88,7 @@ account. There is a pre-configured sender which you may use:
 .. code-block:: python
 
     from redmail import outlook
-    outlook.user_name = 'example@hotmail.com'
+    outlook.username = 'example@hotmail.com'
     outlook.password = '<YOUR PASSWORD>'
 
     # And then you can send emails

+ 1 - 1
docs/tutorials/example.rst

@@ -15,7 +15,7 @@ sender object as:
     email = EmailSender(
         host='localhost', 
         port=0, 
-        user_name='me@example.com', 
+        username='me@example.com', 
         password='<PASSWORD>'
     )
 

+ 1 - 1
docs/tutorials/getting_started.rst

@@ -23,7 +23,7 @@ You can configure your sender by:
    email = EmailSender(
        host='<SMTP HOST>',
        port='<SMTP PORT>',
-       user_name='<USER_NAME>',
+       username='<USERNAME>',
        password='<PASSWORD>'
    )
 

+ 1 - 1
docs/tutorials/sending.rst

@@ -22,7 +22,7 @@ is configured. At minimum, sending an email requires:
 
     If you don't spesify the ``sender``, the sender is considered to 
     be ``email.sender``. If ``email.sender`` is also missing, the sender
-    is then set to be ``email.user_name``. Ensure that any of these is a 
+    is then set to be ``email.username``. Ensure that any of these is a 
     valid email address. 
 
 .. note::

+ 5 - 3
redmail/email/__init__.py

@@ -10,7 +10,7 @@ outlook = EmailSender(
     port=587,
 )
 
-def send_email(*args, host:str, port:int, user_name:str=None, password:str=None, **kwargs):
+def send_email(*args, host:str, port:int, username:str=None, password:str=None, **kwargs):
     """Send email
 
     Parameters
@@ -19,17 +19,19 @@ def send_email(*args, host:str, port:int, user_name:str=None, password:str=None,
         Address of the SMTP host
     port : int
         Port of the SMTP server
-    user_name : str
+    username : str
         User to send the email with
     password : str
         Password of the user to send the email with
+    username : str
+        Deprecated alias for username. Please use username instead.
     **kwargs : dict
         See redmail.EmailSender.send
     """
     sender = EmailSender(
         host=host, 
         port=port, 
-        user_name=user_name,
+        username=username,
         password=password
     )
     return sender.send(*args, **kwargs)

+ 25 - 6
redmail/email/sender.py

@@ -2,6 +2,7 @@
 from copy import copy
 from email.message import EmailMessage
 from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
+import warnings
 
 import jinja2
 from redmail.email.attachment import Attachments
@@ -33,7 +34,7 @@ class EmailSender:
         SMTP host address.
     port : int
         Port to the SMTP server.
-    user_name : str, optional
+    username : str, optional
         User name to authenticate on the server.
     password : str, optional
         User password to authenticate on the server.
@@ -43,6 +44,8 @@ class EmailSender:
     use_starttls : bool
         Whether to use `STARTTLS <https://en.wikipedia.org/wiki/Opportunistic_TLS>`_ 
         when connecting to the SMTP server.
+    user_name : str, optional
+        Deprecated alias for username. Please use username instead.
     **kwargs : dict
         Additional keyword arguments are passed to initiation in ``cls_smtp``.
         These are stored as attribute ``kws_smtp``
@@ -136,11 +139,16 @@ class EmailSender:
 
     attachment_encoding = 'UTF-8'
 
-    def __init__(self, host:str, port:int, user_name:str=None, password:str=None, cls_smtp:smtplib.SMTP=smtplib.SMTP, use_starttls:bool=True, **kwargs):
+    def __init__(self, host:str, port:int, username:str=None, password:str=None, cls_smtp:smtplib.SMTP=smtplib.SMTP, use_starttls:bool=True, **kwargs):
+
+        if "user_name" in kwargs and username is None:
+            warnings.warn("Argument user_name was renamed as username. Please use username instead.", FutureWarning)
+            username = kwargs.pop("user_name")
+
         self.host = host
         self.port = port
 
-        self.user_name = user_name
+        self.username = username
         self.password = password
 
         # Defaults
@@ -241,7 +249,7 @@ class EmailSender:
                 email = EmailSender(
                     host='localhost', 
                     port=0, 
-                    user_name='me@example.com', 
+                    username='me@example.com', 
                     password='<PASSWORD>'
                 )
                 email.send(
@@ -379,7 +387,7 @@ class EmailSender:
 
     def get_sender(self, sender:Union[str, None]) -> str:
         """Get sender of the email"""
-        return sender or self.sender or self.user_name
+        return sender or self.sender or self.username
 
     def _create_body(self, subject, sender, receivers=None, cc=None, bcc=None) -> EmailMessage:
         msg = EmailMessage()
@@ -435,7 +443,7 @@ class EmailSender:
 
     def get_server(self) -> smtplib.SMTP:
         "Connect and get the SMTP Server"
-        user = self.user_name
+        user = self.username
         password = self.password
         
         server = self.cls_smtp(self.host, self.port, **self.kws_smtp)
@@ -535,3 +543,14 @@ class EmailSender:
     def copy(self) -> 'EmailSender':
         "Shallow copy EmailSender"
         return copy(self)
+
+
+    @property
+    def user_name(self):
+        warnings.warn("Attribute user_name was renamed as username. Please use username instead.", FutureWarning)
+        return self.username
+
+    @user_name.setter
+    def user_name(self, user):
+        warnings.warn("Attribute user_name was renamed as username. Please use username instead.", FutureWarning)
+        self.username = user

+ 6 - 2
redmail/log.py

@@ -4,6 +4,7 @@ from logging import Handler, LogRecord
 from logging.handlers import SMTPHandler, BufferingHandler
 from textwrap import dedent
 from typing import List, Optional
+import warnings
 
 from redmail.email.sender import EmailSender
 
@@ -22,12 +23,15 @@ class _EmailHandlerMixin:
 
     def set_email(self, 
                    host, port,
-                   user_name=None, password=None,
+                   username=None, password=None,
                    **kwargs):
         "Create a simple default sender"
+        if "user_name" in kwargs and username is None:
+            warnings.warn("Argument user_name is replaced with username. Please use username instead.", FutureWarning)
+            username = kwargs.pop("user_name")
         self.email = EmailSender(
             host=host, port=port,
-            user_name=user_name, password=password
+            username=username, password=password
         )
         
         self._set_email_kwargs(kwargs)

+ 23 - 3
redmail/test/email/test_send.py

@@ -16,6 +16,8 @@ class MockServer:
 
     def login(self, user=None, password=None):
         self.is_login = True
+        self.user = user
+        self.password = password
         return
 
     def send_message(self, msg):
@@ -30,11 +32,29 @@ def test_send():
 
     msg = email.send(
         subject="An example",
-        receivers=['koli.mikael@example.com']
+        receivers=['me@example.com']
     )
     assert isinstance(msg, EmailMessage)
     assert email.connection is None
 
+def test_send_with_user():
+    email = EmailSender(host="localhost", port=0, username="myuser", password="1234", cls_smtp=MockServer)
+    assert email.connection is None
+    assert email.username == "myuser"
+    assert email.password == "1234"
+
+    msg = email.send(
+        subject="An example",
+        receivers=['me@example.com']
+    )
+    assert isinstance(msg, EmailMessage)
+    assert email.connection is None
+
+    # Testing the server
+    server = email.get_server()
+    assert server.user == "myuser"
+    assert server.password == "1234"
+
 def test_send_multi():
     email = EmailSender(host="localhost", port=0, cls_smtp=MockServer)
 
@@ -43,13 +63,13 @@ def test_send_multi():
         assert email.connection is not None
         msg = email.send(
             subject="An example",
-            receivers=['koli.mikael@example.com']
+            receivers=['me@example.com']
         )
         assert isinstance(msg, EmailMessage)
         assert email.connection is not None
         msg = email.send(
             subject="An example",
-            receivers=['koli.mikael@example.com']
+            receivers=['me@example.com']
         )
         assert isinstance(msg, EmailMessage)
         assert email.connection is not None

+ 8 - 0
redmail/test/log/test_handler_multi.py

@@ -16,6 +16,14 @@ def test_default_body():
     # By default, this should be body if text/html/html_template/text_template not specified
     assert hdlr.email.text == MultiEmailHandler.default_text
 
+def test_sender_with_login():
+    hdlr = MultiEmailHandler(host="localhost", port=0, username="myuser", password="1234", receivers=["me@example.com"], subject="Some logging")
+    # By default, this should be body if text/html/html_template/text_template not specified
+    sender = hdlr.email
+    assert sender.username == "myuser"
+    assert sender.password == "1234"
+    assert sender.receivers == ["me@example.com"]
+    assert sender.subject == "Some logging"
 
 @pytest.mark.parametrize("kwargs,exp_headers,exp_payload",
     [

+ 28 - 0
redmail/test/test_deprecated.py

@@ -0,0 +1,28 @@
+
+import pytest
+from redmail import EmailSender, MultiEmailHandler
+
+def test_user_name():
+    "user_name has been deprecated. Testing backward compatibility."
+
+    # Test EmailSender
+    with pytest.warns(FutureWarning):
+        email = EmailSender(host="localhost", port=0, user_name="testing", password="1234")
+
+    assert email.username == "testing"
+    with pytest.warns(FutureWarning):
+        assert email.user_name == "testing"
+
+    with pytest.warns(FutureWarning):
+        email.user_name = "another"
+
+    assert email.username == "another"
+    with pytest.warns(FutureWarning):
+        assert email.user_name == "another"
+
+    # Testing in handler
+    with pytest.warns(FutureWarning):
+        hdlr = MultiEmailHandler(host="localhost", port=0, user_name="testing", password="1234", subject="A log", receivers=["me@example.com"])
+    sender = hdlr.email
+    assert sender.username == "testing"
+    assert sender.password == "1234"