Skip to content

Commit

Permalink
Remove unused namespace package
Browse files Browse the repository at this point in the history
Reformat imports and update README.md
  • Loading branch information
dormant-user committed Apr 3, 2023
1 parent 3dfed62 commit 4348669
Show file tree
Hide file tree
Showing 12 changed files with 61 additions and 33 deletions.
12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pip install gmail-connector
```

## Env Vars
Environment variables can be loaded from a `.env` file.
Environment variables can be loaded from any `.env` file.
```bash
# For authentication
GMAIL_USER='[email protected]',
Expand All @@ -38,6 +38,13 @@ RECIPIENT='[email protected]'
PHONE='1234567890'
```

*Optionally `.env` files can also be scanned for:*
```python
import gmailconnector as gc

gc.load_env(scan=True)
```

### [Send SMS](https://github.com/thevickypedia/gmail-connector/blob/master/gmailconnector/send_sms.py)
```python
import gmailconnector as gc
Expand Down Expand Up @@ -84,8 +91,7 @@ print(response.body)
```python
import gmailconnector as gc

email_addr = '[email protected]'
validation_result = gc.validate_email(email_address=email_addr)
validation_result = gc.validate_email(email_address='[email protected]')
if validation_result.ok is True:
print('valid') # Validated and found the recipient address to be valid
elif validation_result.ok is False:
Expand Down
11 changes: 8 additions & 3 deletions docs/README.html
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ <h2>Installation<a class="headerlink" href="#installation" title="Permalink to t
</section>
<section id="env-vars">
<h2>Env Vars<a class="headerlink" href="#env-vars" title="Permalink to this heading"></a></h2>
<p>Environment variables can be loaded from a <code class="docutils literal notranslate"><span class="pre">.env</span></code> file.</p>
<p>Environment variables can be loaded from any <code class="docutils literal notranslate"><span class="pre">.env</span></code> file.</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="c1"># For authentication</span>
<span class="nv">GMAIL_USER</span><span class="o">=</span><span class="s1">&#39;[email protected]&#39;</span>,
<span class="nv">GMAIL_PASS</span><span class="o">=</span><span class="s1">&#39;&lt;ACCOUNT_PASSWORD&gt;&#39;</span>
Expand All @@ -80,6 +80,12 @@ <h2>Env Vars<a class="headerlink" href="#env-vars" title="Permalink to this head
<span class="nv">PHONE</span><span class="o">=</span><span class="s1">&#39;1234567890&#39;</span>
</pre></div>
</div>
<p><em>Optionally <code class="docutils literal notranslate"><span class="pre">.env</span></code> files can also be scanned for:</em></p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">gmailconnector</span> <span class="k">as</span> <span class="nn">gc</span>

<span class="n">gc</span><span class="o">.</span><span class="n">load_env</span><span class="p">(</span><span class="n">scan</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
<section id="send-sms">
<h3><a class="reference external" href="https://github.com/thevickypedia/gmail-connector/blob/master/gmailconnector/send_sms.py">Send SMS</a><a class="headerlink" href="#send-sms" title="Permalink to this heading"></a></h3>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">gmailconnector</span> <span class="k">as</span> <span class="nn">gc</span>
Expand Down Expand Up @@ -127,8 +133,7 @@ <h3><a class="reference external" href="https://github.com/thevickypedia/gmail-c
<p><strong>To verify recipient email before sending. Authentication not required, uses SMTP port <code class="docutils literal notranslate"><span class="pre">25</span></code></strong></p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">gmailconnector</span> <span class="k">as</span> <span class="nn">gc</span>

<span class="n">email_addr</span> <span class="o">=</span> <span class="s1">&#39;[email protected]&#39;</span>
<span class="n">validation_result</span> <span class="o">=</span> <span class="n">gc</span><span class="o">.</span><span class="n">validate_email</span><span class="p">(</span><span class="n">email_address</span><span class="o">=</span><span class="n">email_addr</span><span class="p">)</span>
<span class="n">validation_result</span> <span class="o">=</span> <span class="n">gc</span><span class="o">.</span><span class="n">validate_email</span><span class="p">(</span><span class="n">email_address</span><span class="o">=</span><span class="s1">&#39;[email protected]&#39;</span><span class="p">)</span>
<span class="k">if</span> <span class="n">validation_result</span><span class="o">.</span><span class="n">ok</span> <span class="ow">is</span> <span class="kc">True</span><span class="p">:</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">&#39;valid&#39;</span><span class="p">)</span> <span class="c1"># Validated and found the recipient address to be valid</span>
<span class="k">elif</span> <span class="n">validation_result</span><span class="o">.</span><span class="n">ok</span> <span class="ow">is</span> <span class="kc">False</span><span class="p">:</span>
Expand Down
12 changes: 9 additions & 3 deletions docs/_sources/README.md.txt
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pip install gmail-connector
```

## Env Vars
Environment variables can be loaded from a `.env` file.
Environment variables can be loaded from any `.env` file.
```bash
# For authentication
GMAIL_USER='[email protected]',
Expand All @@ -38,6 +38,13 @@ RECIPIENT='[email protected]'
PHONE='1234567890'
```

*Optionally `.env` files can also be scanned for:*
```python
import gmailconnector as gc

gc.load_env(scan=True)
```

### [Send SMS](https://github.com/thevickypedia/gmail-connector/blob/master/gmailconnector/send_sms.py)
```python
import gmailconnector as gc
Expand Down Expand Up @@ -84,8 +91,7 @@ print(response.body)
```python
import gmailconnector as gc

email_addr = '[email protected]'
validation_result = gc.validate_email(email_address=email_addr)
validation_result = gc.validate_email(email_address='[email protected]')
if validation_result.ok is True:
print('valid') # Validated and found the recipient address to be valid
elif validation_result.ok is False:
Expand Down
2 changes: 1 addition & 1 deletion docs/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ <h1>Welcome to Gmail Connector’s documentation!<a class="headerlink" href="#we
<dl class="py class">
<dt class="sig sig-object py" id="gmailconnector.sms_deleter.DeleteSent">
<em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">gmailconnector.sms_deleter.</span></span><span class="sig-name descname"><span class="pre">DeleteSent</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwargs</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#gmailconnector.sms_deleter.DeleteSent" title="Permalink to this definition"></a></dt>
<dd><p>Initiates DeleteSent object to delete a particular email from SentItems.</p>
<dd><p>Initiates DeleteSent object to delete the sent SMS email from SentItems.</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">DeleteSent</span>
</pre></div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion docs/searchindex.js

Large diffs are not rendered by default.

15 changes: 10 additions & 5 deletions gmailconnector/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,20 @@
from .read_email import ReadEmail # noqa: F401
from .send_email import SendEmail # noqa: F401
from .send_sms import SendSMS # noqa: F401
from .validator import validate_email # noqa: F401
from .validator.validate_email import validate_email # noqa: F401

version = "0.7.4"
version = "0.7.5"


def load_env(filename: Union[str, os.PathLike] = ".env") -> NoReturn:
def load_env(filename: Union[str, os.PathLike] = ".env", scan: bool = False) -> NoReturn:
"""Load .env files."""
if os.path.isfile(filename):
dotenv.load_dotenv(dotenv_path=filename, verbose=False)
if scan:
for file in os.listdir():
if file.endswith(".env"):
dotenv.load_dotenv(dotenv_path=file, verbose=False)
else:
if os.path.isfile(filename):
dotenv.load_dotenv(dotenv_path=filename, verbose=False)


load_env()
5 changes: 3 additions & 2 deletions gmailconnector/read_email.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import email.header
import email
import imaplib
import os
import socket
from collections.abc import Generator
from datetime import datetime, timedelta, timezone
from email.header import decode_header, make_header
from typing import Iterable, NoReturn, Union

import pytz
Expand Down Expand Up @@ -155,7 +156,7 @@ def get_info(self, response_part: tuple, dt_flag: bool) -> Email:
else:
datetime_obj = datetime.now()
from_ = original_email['From'].split(' <')
sub = email.header.make_header(email.header.decode_header(original_email['Subject'])) \
sub = make_header(decode_header(original_email['Subject'])) \
if original_email['Subject'] else None
# Converts pacific time to local timezone as the default is pacific
local_time = datetime_obj.replace(tzinfo=pytz.timezone('US/Pacific')).astimezone(tz=self.LOCAL_TIMEZONE)
Expand Down
16 changes: 8 additions & 8 deletions gmailconnector/send_email.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import email.mime.application
import email.mime.multipart
import email.mime.text
import os
import smtplib
import socket
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from typing import Dict, NoReturn, Union

from .models.config import Encryption
Expand Down Expand Up @@ -105,7 +105,7 @@ def __del__(self):
self.server.close()

def multipart_message(self, subject: str, recipient: str or list, sender: str, body: str, html_body: str,
attachments: list, filenames: list, cc: str or list) -> email.mime.multipart.MIMEMultipart:
attachments: list, filenames: list, cc: str or list) -> MIMEMultipart:
"""Creates a multipart message with subject, body, from and to address, and attachment if filename is passed.
Args:
Expand All @@ -127,17 +127,17 @@ def multipart_message(self, subject: str, recipient: str or list, sender: str, b
recipient = [recipient] if isinstance(recipient, str) else recipient
cc = [cc] if cc and isinstance(cc, str) else cc

msg = email.mime.multipart.MIMEMultipart()
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = f"{sender} <{self.gmail_user}>"
msg['To'] = ','.join(recipient)
if cc:
msg['Cc'] = ','.join(cc)

if body:
msg.attach(payload=email.mime.text.MIMEText(body, 'plain'))
msg.attach(payload=MIMEText(body, 'plain'))
if html_body:
msg.attach(payload=email.mime.text.MIMEText(html_body, 'html'))
msg.attach(payload=MIMEText(html_body, 'html'))

for index, attachment_ in enumerate(attachments):
file_type = attachment_.split('.')[-1]
Expand All @@ -162,7 +162,7 @@ def multipart_message(self, subject: str, recipient: str or list, sender: str, b
continue

with open(attachment_, 'rb') as file:
attribute = email.mime.application.MIMEApplication(file.read(), _subtype=file_type)
attribute = MIMEApplication(file.read(), _subtype=file_type)
attribute.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(payload=attribute)

Expand Down
6 changes: 3 additions & 3 deletions gmailconnector/sms_deleter.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import email
import imaplib
from concurrent.futures import ThreadPoolExecutor
from email import message_from_bytes
from email.header import decode_header, make_header
from typing import Dict, Union


class DeleteSent:
"""Initiates DeleteSent object to delete a particular email from SentItems.
"""Initiates DeleteSent object to delete the sent SMS email from SentItems.
>>> DeleteSent
Expand All @@ -29,7 +29,7 @@ def thread_executor(self, item_id: bytes or str) -> Dict[str, str]:
for response_part in data:
if not isinstance(response_part, tuple):
continue
original_email = message_from_bytes(response_part[1]) # gets the raw content
original_email = email.message_from_bytes(response_part[1]) # gets the raw content
sender = str(make_header(decode_header((original_email['From']).split(' <')[0])))
sub = str(make_header(decode_header(original_email['Subject'])))
to = str(make_header(decode_header(original_email['To'])))
Expand Down
1 change: 0 additions & 1 deletion gmailconnector/validator/__init__.py

This file was deleted.

7 changes: 4 additions & 3 deletions gmailconnector/validator/address.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import ipaddress
from typing import Union

import idna.core
from idna.core import IDNAError
from idna.core import encode as idna_encode

from .exceptions import AddressFormatError

Expand All @@ -22,8 +23,8 @@ def __init__(self, address: str):
if not self._user:
raise AddressFormatError("Empty user")
try:
self._domain = idna.core.encode(self._domain).decode('ascii')
except idna.core.IDNAError as error:
self._domain = idna_encode(self._domain).decode('ascii')
except IDNAError as error:
raise AddressFormatError(error)

@property
Expand Down
5 changes: 5 additions & 0 deletions release_notes.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
Release Notes
=============

0.7.5 (04/02/2023)
------------------
- Remove unused namespace package
- Reformat imports and update README.md

0.7.4 (04/02/2023)
------------------
- Reformat and move objects to models dir
Expand Down

0 comments on commit 4348669

Please sign in to comment.