Coder Social home page Coder Social logo

thevickypedia / gmail-connector Goto Github PK

View Code? Open in Web Editor NEW
17.0 1.0 4.0 663 KB

Python module to send SMS, emails and read emails.

Home Page: https://thevickypedia.github.io/gmail-connector/

License: MIT License

Python 96.21% Makefile 1.12% Batchfile 1.41% Shell 0.88% Dockerfile 0.38%
gmail-smtp sms-gateway imaplib

gmail-connector's Introduction

Pypi-version Python

pypi none

Pypi-format Pypi-status dependents

GitHub Repo created GitHub commit activity GitHub last commit

Gmail Connector

Python module to send SMS, emails and read emails in any folder.

As of May 30, 2022, Google no longer supports third party applications accessing Google accounts only using username and password (which was originally available through lesssecureapps)
An alternate approach is to generate apppasswords instead.
Reference: https://support.google.com/accounts/answer/6010255

Installation

pip install gmail-connector

Env Vars

Environment variables can be loaded from any .env file.

GMAIL_USER='[email protected]',
GMAIL_PASS='<ACCOUNT_PASSWORD>'
Env variable customization

To load a custom .env file, set the filename as the env var env_file before importing gmailconnector

import os
os.environ['env_file'] = 'custom'  # to load a custom .env file

To avoid using env variables, arguments can be loaded during object instantiation.

import gmailconnector as gc
kwargs = dict(gmail_user='EMAIL_ADDRESS',
              gmail_pass='PASSWORD',
              encryption=gc.Encryption.SSL,
              timeout=5)
email_obj = gc.SendEmail(**kwargs)

Usage

import gmailconnector as gc

sms_object = gc.SendSMS()
# sms_object = gc.SendSMS(encryption=gc.Encryption.SSL) to use SSL
auth = sms_object.authenticate  # Authentication happens before sending SMS if not instantiated separately
assert auth.ok, auth.body
response = sms_object.send_sms(phone='1234567890', country_code='+1', message='Test SMS using gmail-connector',
                               sms_gateway=gc.SMSGateway.verizon, delete_sent=True)  # set as False to keep the SMS sent
assert response.ok, response.json()
print(response.body)
More on Send SMS

⚠️ Gmail's SMS Gateway has a payload limit. So, it is recommended to break larger messages into multiple SMS.

Additional args:
  • subject: Subject of the message. Defaults to Message from email address
  • sms_gateway: SMS gateway of the carrier. Defaults to tmomail.net
  • delete_sent: Boolean flag to delete the outbound email from SentItems. Defaults to False

Note: If known, using the sms_gateway will ensure proper delivery of the SMS.

import gmailconnector as gc

mail_object = gc.SendEmail()
# mail_object = gc.SendEmail(encryption=gc.Encryption.SSL) to use SSL
auth = mail_object.authenticate  # Authentication happens in send_email if not instantiated beforehand
assert auth.ok, auth.body

# Send a basic email
response = mail_object.send_email(recipient='[email protected]', subject='Howdy!')
assert response.ok, response.json()
print(response.body)

To verify recipient email before sending. Authentication not required, uses SMTP port 25

import gmailconnector as gc

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:
    print('invalid')  # Validated and found the recipient address to be invalid
else:
    print('validation incomplete')  # Couldn't validate (mostly because port 25 is blocked by ISP)
More on Send Email
import os
import gmailconnector as gc

mail_object = gc.SendEmail()
auth = mail_object.authenticate  # Authentication happens in send_email if not instantiated beforehand
assert auth.ok, auth.body

# Different use cases to add attachments with/without custom filenames to an email
images = [os.path.join(os.getcwd(), 'images', image) for image in os.listdir('images')]
names = ['Apple', 'Flower', 'Balloon']

# Use case 1 - Send an email with attachments but no custom attachment name
response = mail_object.send_email(recipient='[email protected]', subject='Howdy!',
                                  attachment=images)
assert response.ok, response.body
print(response.json())

# Use case 2 - Use a dictionary of attachments and custom attachment names
response = mail_object.send_email(recipient='[email protected]', subject='Howdy!',
                                  custom_attachment=dict(zip(images, names)))
assert response.ok, response.body
print(response.json())

# Use case 3 - Use list of attachments and list of custom attachment names
response = mail_object.send_email(recipient='[email protected]', subject='Howdy!',
                                  attachment=[images], filename=[names])
assert response.ok, response.body
print(response.json())

# Use case 4 - Use a single attachment and a custom attachment name for it
response = mail_object.send_email(recipient='[email protected]', subject='Howdy!',
                                  attachment=os.path.join('images', 'random_apple_xroamutiypa.jpeg'), filename='Apple')
assert response.ok, response.body
print(response.json())
Additional args:
  • body: Body of the email. Defaults to blank.
  • html_body: Body of the email formatted as HTML. Supports inline images with a public src.
  • attachment: Filename(s) that has to be attached.
  • filename: Custom name(s) for the attachment(s). Defaults to the attachment name itself.
  • sender: Name that has to be used in the email.
  • cc: Email address of the recipient to whom the email has to be CC'd.
  • bcc: Email address of the recipient to whom the email has to be BCC'd.

Note: To send email to more than one recipient, wrap recipient/cc/bcc in a list.

recipient=['[email protected]', '[email protected]']

import datetime

import gmailconnector as gc

reader = gc.ReadEmail(folder=gc.Folder.all)
filter1 = gc.Condition.since(since=datetime.date(year=2010, month=5, day=1))
filter2 = gc.Condition.subject(subject="Security Alert")
filter3 = gc.Condition.text(reader.env.gmail_user)
filter4 = gc.Category.not_deleted
response = reader.instantiate(filters=(filter1, filter2, filter3, filter4))  # Apply multiple filters
assert response.ok, response.body
for each_mail in reader.read_mail(messages=response.body, humanize_datetime=False):  # False to get datetime object
    print(each_mail.date_time.date())
    print("[%s] %s" % (each_mail.sender_email, each_mail.sender))
    print("[%s] - %s" % (each_mail.subject, each_mail.body))

Linting

PreCommit will ensure linting, and the doc creation are run on every commit.

Requirement

pip install sphinx==5.1.1 pre-commit==2.20.0 recommonmark==0.7.1

Usage

pre-commit run --all-files

Requirement

python -m pip install gitverse

Usage

gitverse-release reverse -f release_notes.rst -t 'Release Notes'

Pypi Module

pypi-module

https://pypi.org/project/gmail-connector/

Runbook

made-with-sphinx-doc

https://thevickypedia.github.io/gmail-connector/

License & copyright

© Vignesh Rao

Licensed under the MIT License

gmail-connector's People

Contributors

dependabot[bot] avatar dormant-user avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

gmail-connector's Issues

Installation not properly explained

Thanks for this great software but unfortunately its not clear on how to make this sms work. I created .env file in "/gmail-connector" and have gmail user and pass in the file. I created a file name sendSMS.py in the same folder with .env and input send SMS script in it.

What i dont understand is where to create a custom file (env_file). Kindly please guide me through because i don't understand which python file to run and which area .env should be located. @thevickypedia

Thanks.

Screenshot 2023-10-28 at 1 10 29 PM Screenshot 2023-10-28 at 1 10 06 PM

Help

Hi , thanks for making this great program.
I would like to know how can i get the actual content of an email
when trying to read an email. I copied the sample code for reading
emails that you provided in the readme file.
When i run it all i get is a dictionary {'sender': 'john Delvin', 'subject': 'Job-Logs-for-learn-java', 'datetime': 'Today, at 06:34 PM'}. I need the actual message in the email to be printed.
Here is the code

from gmailconnector.read_email import ReadEmail

reader = ReadEmail(gmail_user='[email protected]',gmail_pass="my_app_password",folder='"[Gmail]/Important"')  # Folder defaults to inbox
response = reader.instantiate(category='UNSEEN')  # Search criteria defaults to UNSEEN
if response.ok:
    unread_emails = reader.read_email(response.body)
    for each_mail in list(unread_emails):
        print(each_mail)
else:
    print(response.body)

self.mail.select() # ken add 2022-1-17 fix ubuntu use this

err show:
raise self.error("command %s illegal in state %s, "
imaplib.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED

file on==>>
/.env/lib/python3.8/site-packages/gmailconnector/sms_deleter.py", line 49, in delete_sent

ogin:
self.mail.list()
self.mail.select('"[Gmail]/Sent Mail"')

now:
self.mail.list()
self.mail.select('"[Gmail]/Sent Mail"')
self.mail.select() # ken add 2022-1-17 fix ubuntu use this

Got a traceback after updating to the latest version

Hi, i don't know what has gone wrong but i got this log when ran my script. I hope you can look into it.

Traceback (most recent call last):
  File "/home/runner/work/learn-java/learn-java/main.py", line [9](https://github.com/John4650-hub/learn-java/actions/runs/4149066754/jobs/7177685489#step:4:10), in <module>
    response = reader.instantiate(filters=(filter1, filter2, filter3))  # Apply multiple filters at the same time
  File "/home/runner/.local/lib/python3.[10](https://github.com/John4650-hub/learn-java/actions/runs/4149066754/jobs/7177685489#step:4:11)/site-packages/gmailconnector/read_email.py", line 98, in instantiate
    return_code, messages = self.mail.search(None, filters)
  File "/usr/lib/python3.10/imaplib.py", line 734, in search
    typ, dat = self._simple_command(name, *criteria)
  File "/usr/lib/python3.10/imaplib.py", line [12](https://github.com/John4650-hub/learn-java/actions/runs/4149066754/jobs/7177685489#step:4:13)30, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "/usr/lib/python3.10/imaplib.py", line 968, in _command
    raise self.error("command %s illegal in state %s, "
imaplib.IMAP4.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED

May 30, 2022 ... Less Secure App Access Disabled

Hi,

In the past I have used my own code to send gmail from within Python using smtplib. Recently, this stopped working and
I discovered that Google doesn't like apps that sign in using just user/pass ... they now prefer 2-factor authentication. This
is not possible for my application but they did allow "Less Secure App Access" to be enabled. Now, however, Google is
dropping support for this on May 30, 2022. At that time, my app will stop working again.

Does/Will gmail-connector handle this problem? TIA.

syntax issue

from gmailconnector.send_email import SendEmail
File "/Users/aditya/PycharmProjects/PyProject/venv/lib/python3.6/site-packages/gmailconnector/send_email.py", line 59
if cc := self.cc:
^
SyntaxError: invalid syntax

I am using python 3.6

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.