Welcome to Gmail Connector’s documentation!

Send SMS

class gmailconnector.send_sms.SendSMS(**kwargs: Unpack)

Initiates Messenger object to send an SMS to a phone number using SMS gateway provided by the mobile carrier.

>>> SendSMS

Loads all the necessary args, creates a connection with Gmail host based on chosen encryption type.

Keyword Arguments:
  • gmail_user – Gmail username to authenticate SMTP lib.

  • gmail_pass – Gmail password to authenticate SMTP lib.

  • timeout – Connection timeout for SMTP lib.

  • encryption – Type of encryption to be used.

  • gmail_host – Hostname for gmail’s smtp server.

property authenticate: Response

Initiates authentication.

Returns:

A custom response object with properties: ok, status and body to the user.

Return type:

Response

create_ssl_connection(host: str, timeout: Union[int, float]) None

Create a connection using SSL encryption.

create_tls_connection(host: str, timeout: Union[int, float]) None

Create a connection using TLS encryption.

send_sms(message: str, phone: str = None, country_code: str = None, subject: str = None, sms_gateway: SMSGatewayModel(att='mms.att.net', tmobile='tmomail.net', verizon='vtext.com', boost='smsmyboostmobile.com', cricket='sms.cricketwireless.net', uscellular='email.uscc.net') = None, delete_sent: bool = False) Response

Initiates an SMTP connection and sends a text message through SMS gateway of destination number.

Parameters:
  • phone – Phone number.

  • message – Content of the message.

  • country_code – Country code of the phone number.

  • subject – Subject line for the message. Defaults to “Message from email address.”

  • sms_gateway – Takes the SMS gateway of the carrier as an argument.

  • delete_sent – Boolean flag to delete the message from GMAIL’s sent items. Defaults to False.

See also

  • Encodes body of the message to ascii with ignore flag and then decodes it.

  • This is done to ignore special characters (like °) without raising UnicodeEncodeError

Notes

Other flags that can be set includes replace and xmlcharrefreplace

Returns:

A custom response object with properties: ok, status and body to the user.

Return type:

Response

Delete Sent SMS

class gmailconnector.sms_deleter.DeleteSent(**kwargs)

Instantiate the DeleteSent object to delete the SMS email from SentItems.

>>> DeleteSent

Initiates keyword arguments and creates an SSL connection.

Keyword Arguments:
  • username – Gmail username to authenticate SMTP lib.

  • password – Gmail password to authenticate SMTP lib.

  • subject – Subject of the email to be deleted.

  • body – Body of the email to be deleted.

  • to – To address of the email to be deleted.

create_ssl_connection() None

Creates a connection using SSL encryption and selects the sent folder.

delete_sent() Optional[Dict[str, str]]

Deletes the email from GMAIL’s sent items right after sending the message.

See also

Invokes thread_executor to sweep through sent items to delete the email.

Warning

Time taken for deletion depends on the number of existing emails in the Sent folder.

thread_executor(item_id: Union[bytes, str]) Dict[str, str]

Gets invoked in multiple threads, to set the flag as Deleted for the message which was just sent.

Parameters:

item_id – Takes the ID of the message as an argument.

Send Email

class gmailconnector.send_email.SendEmail(**kwargs: Unpack)

Initiates Emailer object to send an email.

>>> SendEmail

Loads all the necessary args, creates a connection with Gmail host based on chosen encryption type.

Keyword Arguments:
  • gmail_user – Gmail username to authenticate SMTP lib.

  • gmail_pass – Gmail password to authenticate SMTP lib.

  • timeout – Connection timeout for SMTP lib.

  • encryption – Type of encryption to be used.

  • gmail_host – Hostname for gmail’s smtp server.

property authenticate: Response

Initiates authentication.

Returns:

A custom response object with properties: ok, status and body to the user.

Return type:

Response

create_ssl_connection(host: str, timeout: Union[int, float]) None

Create a connection using SSL encryption.

create_tls_connection(host: str, timeout: Union[int, float]) None

Create a connection using TLS encryption.

multipart_message(subject: str, recipient: Union[str, List[str]], sender: str, body: str, html_body: str, attachments: list, filenames: list, cc: Union[str, List[str]]) MIMEMultipart

Creates a multipart message with subject, body, from and to address, and attachment if filename is passed.

Parameters:
  • subject – Subject line of the email.

  • recipient – Email address of the recipient to whom the email has to be sent.

  • sender – Name of the sender.

  • body – Body of the email. Defaults to None.

  • html_body – Body of the email. Defaults to None.

  • attachments – Names of the files that has to be attached.

  • filenames – Custom names of the attachments.

  • cc – Email address of the recipient to whom the email has to be CC’d.

  • sender – Add sender name to the email.

Returns a message if a filename is given for attachment but not available at the given path.

Returns:

MIMEMultipart version of the created message.

Return type:

multipart.MIMEMultipart

send_email(subject: str, recipient: Union[str, list], sender: str = 'GmailConnector', body: str = None, html_body: str = None, attachment: Union[str, list] = None, filename: Union[str, list] = None, custom_attachment: Dict[Union[str, PathLike], str] = None, cc: Union[str, list] = None, bcc: Union[str, list] = None, fail_if_attach_fails: bool = True) Response

Initiates a TLS connection and sends the email.

Parameters:
  • recipient – Email address of the recipient to whom the email has to be sent.

  • subject – Subject line of the email.

  • body – Body of the email. Defaults to None.

  • html_body – Body of the email. Defaults to None.

  • attachment – Name of the file that has to be attached.

  • filename – Custom name of the attachment.

  • custom_attachment – Dictionary of the filepath as key and the custom name for the attachment as value.

  • 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.

  • sender – Add sender name to the email.

  • fail_if_attach_fails – Boolean flag to restrict sending the email if attachment is included but fails.

Returns:

A custom response object with properties: ok, status and body to the user.

Return type:

Response

gmailconnector.send_email.validate_email(address: Union[str, List[str]]) Union[str, List[str]]

Validates email addresses and returns them as is.

Read Email

class gmailconnector.read_email.ReadEmail(**kwargs: Unpack)

Initiates Emailer object to authenticate and yield the emails according the conditions/filters.

>>> ReadEmail

Loads all the necessary args, creates a connection with Gmail host to read emails from the chosen folder.

Keyword Arguments:
  • gmail_user – Gmail username to authenticate SMTP lib.

  • gmail_pass – Gmail password to authenticate SMTP lib.

  • timeout – Connection timeout for SMTP lib.

  • gmail_host – Hostname for gmail’s smtp server.

  • folder – Folder where the emails have to be read from.

References

https://imapclient.readthedocs.io/en/2.1.0/_modules/imapclient/imapclient.html#IMAPClient.xlist_folders

See also

Uses broad Exception clause to catch login errors, since the same is raised by imaplib

property authenticate: Response

Initiates authentication.

Returns:

A custom response object with properties: ok, status and body to the user.

Return type:

Response

create_ssl_connection(gmail_host: str, timeout: Union[int, float]) None

Creates an SSL connection to gmail’s SSL server.

get_info(response_part: tuple, dt_flag: bool) Email

Extracts sender, subject, body and time received from response part.

Parameters:
  • response_part – Encoded tuple of the response part in the email.

  • dt_flag – Boolean flag whether to convert datetime as human-readable format.

Returns:

Email object with information.

Return type:

Email

instantiate(filters: Iterable[__str__] = 'UNSEEN') Response

Searches the number of emails for the category received and forms.

Parameters:

filters – Category or Condition

References

https://imapclient.readthedocs.io/en/2.1.0/api.html#imapclient.IMAPClient.search

Returns:

A Response class containing number of email messages, return code and the encoded messages itself.

Return type:

Response

read_mail(messages: Union[list, str], humanize_datetime: bool = False) Generator[Email]

Yield emails matching the filters’ criteria.

Parameters:
  • messages – Takes the encoded message list as an argument. This is the body of the instantiate method.

  • humanize_datetime – Converts received time to human-readable format.

Yields:

dict – A custom response object with properties: ok, status and body to the user.

Validator

gmailconnector.validator.validate_email.validate_email(email_address: str, timeout: ~typing.Union[int, float] = 5, sender: str = None, debug: bool = False, smtp_check: bool = True, logger: ~logging.Logger = <Logger validator (DEBUG)>) Response

Validates email address deliver-ability using SMTP.

Parameters:
  • email_address – Email address.

  • timeout – Time in seconds to wait for a result.

  • sender – Sender’s email address.

  • debug – Debug flag enable logging.

  • smtp_check – Flag to check SMTP.

  • logger – Bring your own logger.

See also

  • Sets the ok flag in Response class to
    • False only if the email address or domain is clearly invalid.

    • True only if the email address is clearly valid.

    • None if port 25 is blocked or all mx records returned temporary errors.

Returns:

Boolean flag to indicate if the email address is valid.

Return type:

bool

Email Address Validation

class gmailconnector.validator.address.EmailAddress(address: str)

Initiates ValidateAddress object to split the address into user and domin to further validate.

>>> EmailAddress

Converts address into IDNA (Internationalized Domain Name) format.

Parameters:

address – Email address as a string.

property domain: Union[str, IPv4Address, IPv6Address]

Returns only the domain part of the address.

property email: str

Returns the email address.

property user: str

Returns only the user part of the address.

Domain Validation

gmailconnector.validator.domain.get_mx_records(domain: str, logger: ~logging.Logger = <Logger validator (DEBUG)>) Generator[Union[str, IPv4Address, IPv6Address]]

Get MX (Mail Exchange server) records for the given domain.

Parameters:
  • domain – FQDN (Fully Qualified Domain Name) extracted from the email address.

  • logger – Bring your own logger.

Yields:

IPv4Address – IP addresses of the mail exchange servers from authoritative/non-authoritative answer section.

Exceptions

exception gmailconnector.validator.exceptions.AddressFormatError

Custom error object for invalid address format.

exception gmailconnector.validator.exceptions.InvalidDomain

Custom error object for invalid domain.

exception gmailconnector.validator.exceptions.NotMailServer

Custom error object for domain that is not a mail server.

exception gmailconnector.validator.exceptions.UnresponsiveMailServer

Custom error object for unresponsive mail server.

Models - Config

class gmailconnector.models.config.EgressConfig(_case_sensitive: bool | None = None, _env_prefix: str | None = None, _env_file: DotenvType | None = PosixPath('.'), _env_file_encoding: str | None = None, _env_nested_delimiter: str | None = None, _secrets_dir: str | Path | None = None, *, gmail_user: EmailStr, gmail_pass: str, recipient: Optional[EmailStr] = None, phone: Optional[str] = None, gmail_host: str = 'smtp.gmail.com', encryption: Encryption = Encryption.TLS, timeout: int = 10, **values: Any)

Configure arguments for SendEmail/SendSMS and validate using pydantic to share across modules.

>>> EgressConfig

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

__init__ uses __pydantic_self__ instead of the more common self for the first arg to allow self as a field name.

class Config

Environment variables configuration.

env_file = '.env'
env_prefix = ''
extra = 'allow'
encryption: Encryption
gmail_host: str
gmail_pass: str
gmail_user: EmailStr
model_config: ClassVar[SettingsConfigDict] = {'arbitrary_types_allowed': True, 'case_sensitive': False, 'env_file': '.env', 'env_file_encoding': None, 'env_nested_delimiter': None, 'env_prefix': '', 'extra': 'allow', 'protected_namespaces': ('model_', 'settings_'), 'secrets_dir': None, 'validate_default': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_fields: ClassVar[dict[str, FieldInfo]] = {'encryption': FieldInfo(annotation=Encryption, required=False, default=<Encryption.TLS: 'TLS'>), 'gmail_host': FieldInfo(annotation=str, required=False, default='smtp.gmail.com'), 'gmail_pass': FieldInfo(annotation=str, required=True), 'gmail_user': FieldInfo(annotation=EmailStr, required=True), 'phone': FieldInfo(annotation=Union[str, NoneType], required=False, metadata=[PydanticGeneralMetadata(pattern='\\d{10}$')]), 'recipient': FieldInfo(annotation=Union[EmailStr, NoneType], required=False), 'timeout': FieldInfo(annotation=int, required=False, default=10)}

Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].

This replaces Model.__fields__ from Pydantic V1.

phone: Optional[str]
recipient: Optional[EmailStr]
timeout: int
class gmailconnector.models.config.Encryption(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Enum wrapper for TLS and SSL encryption.

>>> Encryption
SSL: str = 'SSL'
TLS: str = 'TLS'
class gmailconnector.models.config.IngressConfig(_case_sensitive: bool | None = None, _env_prefix: str | None = None, _env_file: DotenvType | None = PosixPath('.'), _env_file_encoding: str | None = None, _env_nested_delimiter: str | None = None, _secrets_dir: str | Path | None = None, *, gmail_user: EmailStr, gmail_pass: str, folder: Folder = Folder.inbox, gmail_host: str = 'imap.gmail.com', timeout: Union[int, float] = 10, **values: Any)

Configure arguments for ReadEmail and validate using pydantic to share across modules.

>>> IngressConfig

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

__init__ uses __pydantic_self__ instead of the more common self for the first arg to allow self as a field name.

class Config

Environment variables configuration.

env_file = '.env'
env_prefix = ''
extra = 'allow'
folder: Folder
gmail_host: str
gmail_pass: str
gmail_user: EmailStr
model_config: ClassVar[SettingsConfigDict] = {'arbitrary_types_allowed': True, 'case_sensitive': False, 'env_file': '.env', 'env_file_encoding': None, 'env_nested_delimiter': None, 'env_prefix': '', 'extra': 'allow', 'protected_namespaces': ('model_', 'settings_'), 'secrets_dir': None, 'validate_default': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_fields: ClassVar[dict[str, FieldInfo]] = {'folder': FieldInfo(annotation=Folder, required=False, default=<Folder.inbox: 'inbox'>), 'gmail_host': FieldInfo(annotation=str, required=False, default='imap.gmail.com'), 'gmail_pass': FieldInfo(annotation=str, required=True), 'gmail_user': FieldInfo(annotation=EmailStr, required=True), 'timeout': FieldInfo(annotation=Union[int, float], required=False, default=10)}

Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].

This replaces Model.__fields__ from Pydantic V1.

timeout: Union[int, float]
class gmailconnector.models.config.SMSGatewayModel(*, att: str = 'mms.att.net', tmobile: str = 'tmomail.net', verizon: str = 'vtext.com', boost: str = 'smsmyboostmobile.com', cricket: str = 'sms.cricketwireless.net', uscellular: str = 'email.uscc.net')

Wrapper for SMS gateways.

>>> SMSGatewayModel

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

__init__ uses __pydantic_self__ instead of the more common self for the first arg to allow self as a field name.

att: str
boost: str
cricket: str
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_fields: ClassVar[dict[str, FieldInfo]] = {'att': FieldInfo(annotation=str, required=False, default='mms.att.net'), 'boost': FieldInfo(annotation=str, required=False, default='smsmyboostmobile.com'), 'cricket': FieldInfo(annotation=str, required=False, default='sms.cricketwireless.net'), 'tmobile': FieldInfo(annotation=str, required=False, default='tmomail.net'), 'uscellular': FieldInfo(annotation=str, required=False, default='email.uscc.net'), 'verizon': FieldInfo(annotation=str, required=False, default='vtext.com')}

Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo].

This replaces Model.__fields__ from Pydantic V1.

tmobile: str
uscellular: str
verizon: str

Models - Options

Options that can be included while reading emails.

class gmailconnector.models.options.Category

Wrapper for email category.

all: str = 'ALL'
flagged: str = 'FLAGGED'
not_deleted: str = 'NOT DELETED'
seen: str = 'SEEN'
unseen: str = 'UNSEEN'
class gmailconnector.models.options.Condition

Wrapper for conditions that can be passed to read email.

static since(since: Union[str, float, date])

Condition to retrieve emails since a given date.

static small(size: int)

Condition to retrieve emails smaller than the given size.

static subject(subject: str)

Condition to retrieve emails with a particular subject.

static text(text: str)

Condition to retrieve emails with the text present.

class gmailconnector.models.options.Folder(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Wrapper for folders to choose emails from.

all: str = '"[Gmail]/All Mail"'
drafts: str = '"[Gmail]/Drafts"'
important: str = '"[Gmail]/Important"'
inbox: str = 'inbox'
sent: str = '"[Gmail]/Sent Mail"'
spam: str = '"[Gmail]/Spam"'
starred: str = '"[Gmail]/Starred"'
trash: str = '"[Gmail]/Trash"'

Models - Responder

class gmailconnector.models.responder.Email(dictionary: dict)

Turns a dictionary into an Email object.

Creates an object and inserts the key value pairs as members of the class.

Parameters:

dictionary – Takes the dictionary to be converted as an argument.

class gmailconnector.models.responder.Response(dictionary: dict)

Class to format the response, so that it can be accessed as an object variable.

>>> Response

Extracts the properties ok, status and body from a dictionary.

Parameters:

dictionary – Takes a dictionary of key-value pairs as an argument.

property body: str

Returns the extracted class variable.

Returns:

Returns the message as received.

Return type:

str

property count: int

Takes the number of un-read emails and returns it in a class.

Returns:

Returns the number of emails.

Return type:

int

property extra: Any

Returns the extra information as a member of the class.

Returns:

Returns information as received.

Return type:

Any

json() dict

Returns a dictionary of the argument that was received during class initialization.

Returns:

Returns the dictionary received as arg.

Return type:

dict

property ok: bool

Returns the extracted class variable.

Returns:

True or False based on the arg value received.

Return type:

bool

property status: int

Returns the extracted class variable.

Returns:

HTTP status code as received.

Return type:

int

Indices and tables