Skip to content

Commit

Permalink
Merge pull request #35 from Miksus/ref/rename_user_name
Browse files Browse the repository at this point in the history
ENH: Rename user_name
  • Loading branch information
Miksus authored Mar 18, 2022
2 parents 6340115 + 9b7608a commit e1a8447
Show file tree
Hide file tree
Showing 11 changed files with 107 additions and 24 deletions.
10 changes: 6 additions & 4 deletions ci/test_send.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
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']
)

Expand Down Expand Up @@ -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>
Expand All @@ -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()),
}
)

Expand Down Expand Up @@ -218,6 +219,7 @@ def log_simple():
"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__)
Expand Down
6 changes: 3 additions & 3 deletions docs/tutorials/config.rst
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ and then you can use the sender:
.. code-block:: python
from redmail import outlook
outlook.user_name = '[email protected]'
outlook.username = '[email protected]'
outlook.password = '<YOUR PASSWORD>'
outlook.send(
Expand Down Expand Up @@ -66,7 +66,7 @@ server pre-configured:
.. code-block:: python
from redmail import gmail
gmail.user_name = '[email protected]' # Your Gmail address
gmail.username = '[email protected]' # Your Gmail address
gmail.password = '<APP PASSWORD>'
# And then you can send emails
Expand All @@ -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 = '[email protected]'
outlook.username = '[email protected]'
outlook.password = '<YOUR PASSWORD>'
# And then you can send emails
Expand Down
2 changes: 1 addition & 1 deletion docs/tutorials/example.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ sender object as:
email = EmailSender(
host='localhost',
port=0,
user_name='[email protected]',
username='[email protected]',
password='<PASSWORD>'
)
Expand Down
2 changes: 1 addition & 1 deletion docs/tutorials/getting_started.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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>'
)
Expand Down
2 changes: 1 addition & 1 deletion docs/tutorials/sending.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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::
Expand Down
8 changes: 5 additions & 3 deletions redmail/email/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
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
Expand All @@ -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)
31 changes: 25 additions & 6 deletions redmail/email/sender.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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``
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -241,7 +249,7 @@ def send(self,
email = EmailSender(
host='localhost',
port=0,
user_name='[email protected]',
username='[email protected]',
password='<PASSWORD>'
)
email.send(
Expand Down Expand Up @@ -379,7 +387,7 @@ def get_bcc(self, bcc:Union[list, str, None]) -> Union[List[str], None]:

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()
Expand Down Expand Up @@ -435,7 +443,7 @@ def close(self):

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)
Expand Down Expand Up @@ -535,3 +543,14 @@ def set_template_paths(self,
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
8 changes: 6 additions & 2 deletions redmail/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from logging.handlers import SMTPHandler, BufferingHandler
from textwrap import dedent
from typing import List, Optional
import warnings

from redmail.email.sender import EmailSender

Expand All @@ -22,12 +23,15 @@ def __init__(self, email, kwargs):

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)
Expand Down
26 changes: 23 additions & 3 deletions redmail/test/email/test_send.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ def starttls(self):

def login(self, user=None, password=None):
self.is_login = True
self.user = user
self.password = password
return

def send_message(self, msg):
Expand All @@ -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=['[email protected]']
)
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)

Expand All @@ -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
Expand Down
8 changes: 8 additions & 0 deletions redmail/test/log/test_handler_multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -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=["[email protected]"], 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 == ["[email protected]"]
assert sender.subject == "Some logging"

@pytest.mark.parametrize("kwargs,exp_headers,exp_payload",
[
Expand Down
28 changes: 28 additions & 0 deletions redmail/test/test_deprecated.py
Original file line number Diff line number Diff line change
@@ -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=["[email protected]"])
sender = hdlr.email
assert sender.username == "testing"
assert sender.password == "1234"

0 comments on commit e1a8447

Please sign in to comment.