Last active
April 11, 2019 18:13
-
-
Save ntrrg/8ae8c5c71690c878dd105ecf93b13665 to your computer and use it in GitHub Desktop.
Send emails with Python 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# mailpy | |
# Copyright (c) 2016 Miguel Angel Rivera Notararigo | |
# Licensed under The MIT License. | |
""" | |
Provides: | |
* ``Account``: email account interface. | |
""" | |
from email import encoders | |
from email.mime.base import MIMEBase | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
from smtplib import SMTP, SMTPException | |
class Account: | |
"""Creates email account interfaces.""" | |
def __init__(self, username, server="localhost"): | |
""" | |
``Account("<username>"[, "<server>[:<port>]"])`` | |
``username`` (string) | |
Username from the email account. | |
``server`` (string, optional) | |
SMTP server. By default this points to ``localhost`` | |
Servers list | |
============ | |
* **Gmail:** smtp.gmail.com:587 | |
If you use Gmail, less secure applications access is required, visit | |
https://www.google.com/settings/security/lesssecureapps. | |
Examples | |
======== | |
.. code:: python | |
Account("[email protected]") | |
.. code:: python | |
Account("[email protected]", "smtp.gmail.com:587") | |
""" | |
self.username = username | |
self.server = SMTP(server) | |
self.__emails = [] | |
def login(self, password): | |
""" | |
Logs in at the SMTP server. | |
``obj.login("<password>")`` | |
``password`` (string) | |
Password from the email account. | |
Example | |
======= | |
.. code:: python | |
me = Account("[email protected]") | |
# Raw password | |
me.login("12345678") | |
# From an envimonment variable | |
import os | |
me.login(os.getenv("EMAIL_PASSWD")) | |
# From a prompt | |
me.login(input("Type your email password: ")) | |
""" | |
try: | |
self.server.login(self.username, password) | |
except SMTPException: | |
self.server.starttls() | |
self.server.login(self.username, password) | |
def logout(self): | |
"""Logs out at the SMTP server.""" | |
self.server.quit() | |
def new_email(self, to, body="", attachments=(), mime_body="html", | |
**kwargs): | |
""" | |
Creates and prepares an email. | |
.. code:: text | |
obj.new_email( | |
"<email address>[, ...]" | |
[, body="<email body>"] | |
[, attachments=("<path>" | <file object>,[ ...])] | |
[, mime_body="<subtype>"] | |
[, <header>="<value>"[, ...]] | |
) | |
``to`` (string) | |
Comma separated list of receivers. | |
``body`` (string, optional) | |
Email body. | |
``attachments`` (tuple, optional) | |
List of attachments, any attachment may be either a path (string) or | |
a readable file object. | |
``mime_body`` (string, optional) | |
MIME subtype for the email body, usually it is either ``html`` or | |
``plain``. | |
``<header>`` | |
Other headers may be specified as extra keyword arguments, some | |
useful arguments are: ``subject``, ``cc``, ``reply-to``, ``sender``, | |
``keywords``. | |
return | |
``email.mime.multipart.MIMEMultipart`` - An email. | |
Example | |
======= | |
.. code:: python | |
me = Account("[email protected]") | |
me.login("12345678"); | |
# Common email | |
me.new_email("[email protected]", "Hi me!") | |
me.new_email("[email protected], [email protected]", "Hi me!") | |
# Extra headers | |
me.new_email( | |
"[email protected]", | |
"Hi me!", | |
subject="Testing my script" | |
) | |
# Plain text body | |
me.new_email("[email protected]", "Hi me!", mime_body="plain") | |
# Attachments | |
me.new_email("[email protected]", attachments=("file.txt",)) | |
me.new_email("[email protected]", attachments=( | |
"file.txt", | |
open("Doc.pdf", "rb"), | |
"/home/ntrrg/Public/NtWeb.jpg" | |
)) | |
me.logout() | |
""" | |
email = MIMEMultipart() | |
email["from"] = self.username | |
email["to"] = to | |
for key, value in kwargs.items(): | |
email[key] = value | |
email.attach(MIMEText(body, mime_body)) | |
for file in attachments: | |
attachment = MIMEBase('application', 'octet-stream') | |
if isinstance(file, str): | |
file = open(file, "rb") | |
attachment.set_payload(file.read()) | |
encoders.encode_base64(attachment) | |
attachment.add_header('Content-Disposition', 'file', | |
filename=file.name.split("/")[-1]) | |
email.attach(attachment) | |
file.close() | |
self.__emails.append(email) | |
return email | |
def send(self): | |
"""Send all prepared emails.""" | |
while self.__emails: | |
self.server.send_message(self.__emails.pop()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment