Created
June 24, 2020 18:44
-
-
Save OnePro/5d0a5bf30d5518aad6f7707b2b055720 to your computer and use it in GitHub Desktop.
Python Emailing examle
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
class Email: | |
def __init__(self, receivers, subject='', body='', files=None): | |
self.sender = EMAIL_SENDER | |
self.receivers = receivers | |
# Create the message | |
msg = EmailMessage() | |
msg['Subject'] = subject | |
msg['To'] = ', '.join(receivers) | |
msg['From'] = self.sender | |
msg.set_content(body) | |
for f in files or []: | |
with open(f, "rb") as fil: | |
ctype, encoding = mimetypes.guess_type(f) | |
if ctype is None or encoding is not None: | |
ctype = 'application/octet-stream' | |
maintype, subtype = ctype.split('/', 1) | |
msg.add_attachment(fil.read(), maintype=maintype, subtype=subtype, filename=basename(f)) | |
self.message = msg | |
def send_email(self): | |
try: | |
self.receivers = [DEV_TEAM_EMAIL] | |
with smtplib.SMTP('localhost') as ess: | |
ess.send_message(self.message) | |
except Exception as err: | |
print(f'Error: unable to send email. \n{err} ') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment