Package: gmail-connector
Gmail ConnectorPython 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 throughlesssecureapps)An alternate approach is to generateapppasswordsinstead.Reference:https://support.google.com/accounts/answer/6010255Installationpipinstallgmail-connectorEnv VarsEnvironment variables can be loaded from any.envfile.GMAIL_USER='username@gmail.com',GMAIL_PASS='<ACCOUNT_PASSWORD>'Env variable customizationTo load a custom.envfile, set the filename as the env varenv_filebefore importinggmailconnectorimportosos.environ['env_file']='custom'# to load a custom .env fileimportgmailconnectorasgcTo avoid using env variables, arguments can be loaded during object instantiation.importgmailconnectorasgckwargs=dict(gmail_user='EMAIL_ADDRESS',gmail_pass='PASSWORD',encryption=gc.Encryption.SSL,timeout=5)email_obj=gc.SendEmail(**kwargs)UsageSend SMSimportgmailconnectorasgcsms_object=gc.SendSMS()# sms_object = gc.SendSMS(encryption=gc.Encryption.SSL) to use SSLauth=sms_object.authenticate# Authentication happens before sending SMS if not instantiated separatelyassertauth.ok,auth.bodyresponse=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 sentassertresponse.ok,response.json()print(response.body)More onSend SMS:warning: 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 toMessage from email addresssms_gateway:SMS gateway of the carrier. Defaults totmomail.netdelete_sent:Boolean flag to delete the outbound email from SentItems. Defaults toFalseNote: If known, using thesms_gatewaywill ensure proper delivery of the SMS.Send Emailimportgmailconnectorasgcmail_object=gc.SendEmail()# mail_object = gc.SendEmail(encryption=gc.Encryption.SSL) to use SSLauth=mail_object.authenticate# Authentication happens in send_email if not instantiated beforehandassertauth.ok,auth.body# Send a basic emailresponse=mail_object.send_email(recipient='username@gmail.com',subject='Howdy!')assertresponse.ok,response.json()print(response.body)To verify recipient email before sending. Authentication not required, uses SMTP port25importgmailconnectorasgcvalidation_result=gc.validate_email(email_address='someone@example.com')ifvalidation_result.okisTrue:print('valid')# Validated and found the recipient address to be validelifvalidation_result.okisFalse:print('invalid')# Validated and found the recipient address to be invalidelse:print('validation incomplete')# Couldn't validate (mostly because port 25 is blocked by ISP)More onSend Emailimportosimportgmailconnectorasgcmail_object=gc.SendEmail()auth=mail_object.authenticate# Authentication happens in send_email if not instantiated beforehandassertauth.ok,auth.body# Different use cases to add attachments with/without custom filenames to an emailimages=[os.path.join(os.getcwd(),'images',image)forimageinos.listdir('images')]names=['Apple','Flower','Balloon']# Use case 1 - Send an email with attachments but no custom attachment nameresponse=mail_object.send_email(recipient='username@gmail.com',subject='Howdy!',attachment=images)assertresponse.ok,response.bodyprint(response.json())# Use case 2 - Use a dictionary of attachments and custom attachment namesresponse=mail_object.send_email(recipient='username@gmail.com',subject='Howdy!',custom_attachment=dict(zip(images,names)))assertresponse.ok,response.bodyprint(response.json())# Use case 3 - Use list of attachments and list of custom attachment namesresponse=mail_object.send_email(recipient='username@gmail.com',subject='Howdy!',attachment=[images],filename=[names])assertresponse.ok,response.bodyprint(response.json())# Use case 4 - Use a single attachment and a custom attachment name for itresponse=mail_object.send_email(recipient='username@gmail.com',subject='Howdy!',attachment=os.path.join('images','random_apple_xroamutiypa.jpeg'),filename='Apple')assertresponse.ok,response.bodyprint(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 publicsrc.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, wraprecipient/cc/bccin a list.recipient=['username1@gmail.com', 'username2@gmail.com']Read Emailimportdatetimeimportgmailconnectorasgcreader=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_deletedresponse=reader.instantiate(filters=(filter1,filter2,filter3,filter4))# Apply multiple filtersassertresponse.ok,response.bodyforeach_mailinreader.read_mail(messages=response.body,humanize_datetime=False):# False to get datetime objectprint(each_mail.date_time.date())print("[%s]%s"%(each_mail.sender_email,each_mail.sender))print("[%s] -%s"%(each_mail.subject,each_mail.body))LintingPreCommitwill ensure linting, and the doc creation are run on every commit.Requirementpipinstallsphinx==5.1.1pre-commit==2.20.0recommonmark==0.7.1Usagepre-commitrun--all-filesRelease NotesRequirementpython-mpipinstallgitverseUsagegitverse-releasereverse-frelease_notes.rst-t'Release Notes'Pypi Modulehttps://pypi.org/project/gmail-connector/Runbookhttps://thevickypedia.github.io/gmail-connector/License & copyright© Vignesh RaoLicensed under theMIT License