Python.Modules.Email.SMTP #python #PythonModules #modules #email #Email #smtp #mime
Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending an e-mail and routing e-mail between mail servers.
Python provides smtplib module, which defines an SMTP client session object that can be used to send mails to any Internet machine with an SMTP or ESMTP listener daemon.
Here is a simple syntax to create one SMTP object, which can later be used to send an e-mail −
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
Here is the detail of the parameters −
host − This is the host running your SMTP server. You can specifiy IP address of the host or a domain name like tutorialspoint.com. This is an optional argument.
port − If you are providing host argument, then you need to specify a port, where SMTP server is listening. Usually this port would be 25.
local_hostname − If your SMTP server is running on your local machine, then you can specify just localhost the option.
An SMTP object has an instance method called sendmail, which is typically used to do the work of mailing a message. It takes three parameters −
The sender − A string with the address of the sender.
The receivers − A list of strings, one for each recipient.
The message − A message as a string formatted as specified in the various RFCs.
Example
Here is a simple way to send one e-mail using Python script. Try it once −
#!/usr/bin/python3
import smtplib
sender = 'from@fromdomain.com'
receivers = ['to@todomain.com']
message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
Here, you have placed a basic e-mail in message, using a triple quote, taking care to format the headers correctly. An e-mail requires a From, To, and a Subject header, separated from the body of the e-mail with a blank line.
To send the mail you use smtpObj to connect to the SMTP server on the local machine. Then use the sendmail method along with the message, the from address, and the destination address as parameters (even though the from and to addresses are within the e-mail itself, these are not always used to route the mail).
If you are not running an SMTP server on your local machine, you can the use smtplib client to communicate with a remote SMTP server. Unless you are using a webmail service (such as gmail or Yahoo! Mail), your e-mail provider must have provided you with the outgoing mail server details that you can supply them, as follows −
mail = smtplib.SMTP('smtp.gmail.com', 587)
Sending an HTML e-mail using Python
When you send a text message using Python, then all the content is treated as simple text. Even if you include HTML tags in a text message, it is displayed as simple text and HTML tags will not be formatted according to the HTML syntax. However, Python provides an option to send an HTML message as actual HTML message.
While sending an e-mail message, you can specify a Mime version, content type and the character set to send an HTML e-mail.
Example
Following is an example to send the HTML content as an e-mail. Try it once −
#!/usr/bin/python3
import smtplib
message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test
This is an e-mail message to be sent in HTML format
<b>This is HTML message.</b>
<h1>This is headline.</h1>
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
Sending Attachments as an E-mail
To send an e-mail with mixed content requires setting the Content-type header to multipart/mixed. Then, the text and the attachment sections can be specified within boundaries.
A boundary is started with two hyphens followed by a unique number, which cannot appear in the message part of the e-mail. A final boundary denoting the e-mail's final section must also end with two hyphens.
The attached files should be encoded with the pack("m") function to have base 64 encoding before transmission.
Example
Following is an example, which sends a file /tmp/test.txt as an attachment. Try it once −
#!/usr/bin/python3
import smtplib
import base64
filename = "/tmp/test.txt"
# Read a file and encode it into base64 format
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent) # base64
sender = 'webmaster@tutorialpoint.com'
reciever = 'amrood.admin@gmail.com'
marker = "AUNIQUEMARKER"
body ="""
This is a test email to send an attachement.
"""
# Define the main headers.
part1 = """From: From Person <me@fromdomain.net>
To: To Person <amrood.admin@gmail.com>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)
# Define the message action
part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit
%s
--%s
""" % (body,marker)
# Define the attachment section
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s
%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, reciever, message)
print "Successfully sent email"
except Exception:
print ("Error: unable to send email")
email: Examples
Here are a few examples of how to use the email package to read, write, and send simple email messages, as well as more complex MIME messages.
First, let’s see how to create and send a simple text message (both the text content and the addresses may contain unicode characters):
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.message import EmailMessage
# Open the plain text file whose name is in textfile for reading.
with open(textfile) as fp:
# Create a text/plain message
msg = EmailMessage()
msg.set_content(fp.read())
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()
Parsing RFC 822 headers can easily be done by the using the classes from the parser module:
# Import the email modules we'll need
from email.parser import BytesParser, Parser
from email.policy import default
# If the e-mail headers are in a file, uncomment these two lines:
# with open(messagefile, 'rb') as fp:
# headers = BytesParser(policy=default).parse(fp)
# Or for parsing headers in a string (this is an uncommon operation), use:
headers = Parser(policy=default).parsestr(
'From: Foo Bar <user@example.com>\n'
'To: <someone_else@example.com>\n'
'Subject: Test message\n'
'\n'
'Body would go here\n')
# Now the header items can be accessed as a dictionary:
print('To: {}'.format(headers['to']))
print('From: {}'.format(headers['from']))
print('Subject: {}'.format(headers['subject']))
# You can also access the parts of the addresses:
print('Recipient username: {}'.format(headers['to'].addresses[0].username))
print('Sender name: {}'.format(headers['from'].addresses[0].display_name))
Here’s an example of how to send a MIME message containing a bunch of family pictures that may be residing in a directory:
# Import smtplib for the actual sending function
import smtplib
# And imghdr to find the types of our images
import imghdr
# Here are the email package modules we'll need
from email.message import EmailMessage
# Create the container email message.
msg = EmailMessage()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = ', '.join(family)
msg.preamble = 'Our family reunion'
# Open the files in binary mode. Use imghdr to figure out the
# MIME subtype for each specific image.
for file in pngfiles:
with open(file, 'rb') as fp:
img_data = fp.read()
msg.add_attachment(img_data, maintype='image',
subtype=imghdr.what(None, img_data))
# Send the email via our own SMTP server.
with smtplib.SMTP('localhost') as s:
s.send_message(msg)
Here’s an example of how to send the entire contents of a directory as an email message: [1]
#!/usr/bin/env python3
"""Send the contents of a directory as a MIME message."""
import os
import smtplib
# For guessing MIME type based on file name extension
import mimetypes
from argparse import ArgumentParser
from email.message import EmailMessage
from email.policy import SMTP
def main():
parser = ArgumentParser(description="""\
Send the contents of a directory as a MIME message.
Unless the -o option is given, the email is sent by forwarding to your local
SMTP server, which then does the normal delivery process. Your local machine
must be running an SMTP server.
""")
parser.add_argument('-d', '--directory',
help="""Mail the contents of the specified directory,
otherwise use the current directory. Only the regular
files in the directory are sent, and we don't recurse to
subdirectories.""")
parser.add_argument('-o', '--output',
metavar='FILE',
help="""Print the composed message to FILE instead of
sending the message to the SMTP server.""")
parser.add_argument('-s', '--sender', required=True,
help='The value of the From: header (required)')
parser.add_argument('-r', '--recipient', required=True,
action='append', metavar='RECIPIENT',
default=[], dest='recipients',
help='A To: header value (at least one required)')
args = parser.parse_args()
directory = args.directory
if not directory:
directory = '.'
# Create the message
msg = EmailMessage()
msg['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
msg['To'] = ', '.join(args.recipients)
msg['From'] = args.sender
msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'
for filename in os.listdir(directory):
path = os.path.join(directory, filename)
if not os.path.isfile(path):
continue
# Guess the content type based on the file's extension. Encoding
# will be ignored, although we should check for simple things like
# gzip'd or compressed files.
ctype, encoding = mimetypes.guess_type(path)
if ctype is None or encoding is not None:
# No guess could be made, or the file is encoded (compressed), so
# use a generic bag-of-bits type.
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
with open(path, 'rb') as fp:
msg.add_attachment(fp.read(),
maintype=maintype,
subtype=subtype,
filename=filename)
# Now send or store the message
if args.output:
with open(args.output, 'wb') as fp:
fp.write(msg.as_bytes(policy=SMTP))
else:
with smtplib.SMTP('localhost') as s:
s.send_message(msg)
if __name__ == '__main__':
main()
Here’s an example of how to unpack a MIME message like the one above, into a directory of files:
#!/usr/bin/env python3
"""Unpack a MIME message into a directory of files."""
import os
import email
import mimetypes
from email.policy import default
from argparse import ArgumentParser
def main():
parser = ArgumentParser(description="""\
Unpack a MIME message into a directory of files.
""")
parser.add_argument('-d', '--directory', required=True,
help="""Unpack the MIME message into the named
directory, which will be created if it doesn't already
exist.""")
parser.add_argument('msgfile')
args = parser.parse_args()
with open(args.msgfile, 'rb') as fp:
msg = email.message_from_binary_file(fp, policy=default)
try:
os.mkdir(args.directory)
except FileExistsError:
pass
counter = 1
for part in msg.walk():
# multipart/* are just containers
if part.get_content_maintype() == 'multipart':
continue
# Applications should really sanitize the given filename so that an
# email message can't be used to overwrite important files
filename = part.get_filename()
if not filename:
ext = mimetypes.guess_extension(part.get_content_type())
if not ext:
# Use a generic bag-of-bits extension
ext = '.bin'
filename = 'part-%03d%s' % (counter, ext)
counter += 1
with open(os.path.join(args.directory, filename), 'wb') as fp:
fp.write(part.get_payload(decode=True))
if __name__ == '__main__':
main()
Here’s an example of how to create an HTML message with an alternative plain text version. To make things a bit more interesting, we include a related image in the html part, and we save a copy of what we are going to send to disk, as well as sending it.
#!/usr/bin/env python3
import smtplib
from email.message import EmailMessage
from email.headerregistry import Address
from email.utils import make_msgid
# Create the base text message.
msg = EmailMessage()
msg['Subject'] = "Ayons asperges pour le déjeuner"
msg['From'] = Address("Pepé Le Pew", "pepe", "example.com")
msg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"),
Address("Fabrette Pussycat", "fabrette", "example.com"))
msg.set_content("""\
Salut!
Cela ressemble à un excellent recipie[1] déjeuner.
[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718
--Pepé
""")
# Add the html version. This converts the message into a multipart/alternative
# container, with the original text message as the first part and the new html
# message as the second part.
asparagus_cid = make_msgid()
msg.add_alternative("""\
<html>
<head></head>
<body>
<p>Salut!</p>
<p>Cela ressemble à un excellent
<a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718">
recipie
</a> déjeuner.
</p>
<img src="cid:{asparagus_cid}" />
</body>
</html>
""".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')
# note that we needed to peel the <> off the msgid for use in the html.
# Now add the related image to the html part.
with open("roasted-asparagus.jpg", 'rb') as img:
msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
cid=asparagus_cid)
# Make a local copy of what we are going to send.
with open('outgoing.msg', 'wb') as f:
f.write(bytes(msg))
# Send the message via local SMTP server.
with smtplib.SMTP('localhost') as s:
s.send_message(msg)
If we were sent the message from the last example, here is one way we could process it:
import os
import sys
import tempfile
import mimetypes
import webbrowser
# Import the email modules we'll need
from email import policy
from email.parser import BytesParser
# An imaginary module that would make this work and be safe.
from imaginary import magic_html_parser
# In a real program you'd get the filename from the arguments.
with open('outgoing.msg', 'rb') as fp:
msg = BytesParser(policy=policy.default).parse(fp)
# Now the header items can be accessed as a dictionary, and any non-ASCII will
# be converted to unicode:
print('To:', msg['to'])
print('From:', msg['from'])
print('Subject:', msg['subject'])
# If we want to print a preview of the message content, we can extract whatever
# the least formatted payload is and print the first three lines. Of course,
# if the message has no plain text part printing the first three lines of html
# is probably useless, but this is just a conceptual example.
simplest = msg.get_body(preferencelist=('plain', 'html'))
print()
print(''.join(simplest.get_content().splitlines(keepends=True)[:3]))
ans = input("View full message?")
if ans.lower()[0] == 'n':
sys.exit()
# We can extract the richest alternative in order to display it:
richest = msg.get_body()
partfiles = {}
if richest['content-type'].maintype == 'text':
if richest['content-type'].subtype == 'plain':
for line in richest.get_content().splitlines():
print(line)
sys.exit()
elif richest['content-type'].subtype == 'html':
body = richest
else:
print("Don't know how to display {}".format(richest.get_content_type()))
sys.exit()
elif richest['content-type'].content_type == 'multipart/related':
body = richest.get_body(preferencelist=('html'))
for part in richest.iter_attachments():
fn = part.get_filename()
if fn:
extension = os.path.splitext(part.get_filename())[1]
else:
extension = mimetypes.guess_extension(part.get_content_type())
with tempfile.NamedTemporaryFile(suffix=extension, delete=False) as f:
f.write(part.get_content())
# again strip the <> to go from email form of cid to html form.
partfiles[part['content-id'][1:-1]] = f.name
else:
print("Don't know how to display {}".format(richest.get_content_type()))
sys.exit()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
# The magic_html_parser has to rewrite the href="cid:...." attributes to
# point to the filenames in partfiles. It also has to do a safety-sanitize
# of the html. It could be written using html.parser.
f.write(magic_html_parser(body.get_content(), partfiles))
webbrowser.open(f.name)
os.remove(f.name)
for fn in partfiles.values():
os.remove(fn)
# Of course, there are lots of email messages that could break this simple
# minded program, but it will handle the most common ones.
Up to the prompt, the output from the above is:
To: Penelope Pussycat <penelope@example.com>, Fabrette Pussycat <fabrette@example.com>
From: Pepé Le Pew <pepe@example.com>
Subject: Ayons asperges pour le déjeuner
Salut!
Cela ressemble à un excellent recipie[1] déjeuner.
import smtplib
# msg =
# smtpObj = smtplib.SMTP('holhub.intranet.dei.com.gr', 587)
# smtpObj.ehlo()
# smtpObj.starttls()
# smtpObj.login('p.doulgeridis', 'Doul2018#')
# smtpObj.sendmail('p.doulgeridis@dei.com.gr', 'doulgeridi@gmail.com', "Subject: Solong.\nDear Alice, so long and thanks for all the fish. Sincerely, Bob")
# smtpObj.quit()
#Coffee timer
import smtplib
from email.mime.text import MIMEText
#from email.MIMEMultipart import MIMEMultipart
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.base import MIMEBase
#from email.MIMEBase import MIMEBase
from email import encoders
from os.path import basename
print("Sending E-mail")
def send_mail(send_from: str, subject: str, text: str, send_to: list, send_cc: list, send_bcc: list, files= None):
send_to= default_address if not send_to else send_to
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = ', '.join(send_to)
msg['Subject'] = subject
msg['Cc'] = ', '.join(send_cc)
msg['Bcc'] = ', '.join(send_bcc)
msg.attach(MIMEText(text))
for f in files or []:
with open(f, "rb") as fil:
ext = f.split('.')[-1:]
attachedfile = MIMEApplication(fil.read(), _subtype = ext)
attachedfile.add_header(
'content-disposition', 'attachment', filename=basename(f) )
msg.attach(attachedfile)
smtp = smtplib.SMTP(host="holhub.intranet.dei.com.gr", port= 587)
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
username = 'p.doulgeridis'
password = 'Doul2018#'
#default_address = ['my-address2@gmail.com']
default_address = 'p.doulgeridis@dei.com.gr'
subject_in = 'ΣΤΑΤΙΣΤΙΚΑ HELP DESK '
msg2 = """
Καλημέρα Φωτεινή,
Στείλε μου σε παρακαλώ τα αρχεία των εγγραφων
του Help Desk, 1ου και 2ου επιπεδου, για την
προηγούμενη εβδομάδα.
Ευχαριστώ,
Παναγιώτης Δουλγερίδης
"""
send_mail(
send_from= default_address,
subject=subject_in,
text=msg2,
send_to= ['p.doulgeridis@dei.com.gr', 'p.doulgeridis@dei.com.gr', 'i.niarchos@dei.com.gr' ] ,
send_cc= ['p.doulgeridis@dei.com.gr', 'p.doulgeridis@dei.com.gr', 'd.tsolakos@dei.com.gr', 'i.niarchos@dei.com.gr' ] ,
send_bcc= ['p.doulgeridis@dei.com.gr', 'd.tsolakos@dei.com.gr' ] ,
files= [ 'C:\\Users\\p.doulgeridis\\Desktop\\testzdm.XLS' ]
)
#!/usr/bin/env python
# encoding: utf-8
"""
Mailer.py
Created by Robert Dempsey on 11/07/14.
Copyright (c) 2014 Robert Dempsey. All rights reserved.
"""
import sys
import os
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
COMMASPACE = ', '
class Mailer:
def __init__(self, **kwargs):
self.properties = kwargs
# Subject
@property
def subject(self):
return self.properties.get('subject', 'None')
@subject.setter
def subject(self, s):
self.properties['subject'] = s
@subject.deleter
def subject(self):
del self.properties['subject']
# Recipients
@property
def recipients(self):
return self.properties.get('recipients', 'None')
@recipients.setter
def recipients(self, r):
self.properties['recipients'] = r
@recipients.deleter
def recipients(self):
del self.properties['recipients']
# Send From
@property
def send_from(self):
return self.properties.get('send_from', 'None')
@send_from.setter
def send_from(self, s_from):
self.properties['send_from'] = s_from
@send_from.deleter
def send_from(self):
del self.properties['send_from']
# Gmail Password
@property
def gmail_password(self):
return self.properties.get('gmail_password', 'None')
@gmail_password.setter
def gmail_password(self, g_pass):
self.properties['gmail_password'] = g_pass
@gmail_password.deleter
def gmail_password(self):
del self.properties['gmail_password']
# Message
@property
def message(self):
return self.properties.get('message', 'None')
@message.setter
def message(self, m):
self.properties['message'] = m
@message.deleter
def message(self):
del self.properties['message']
# Attachments
@property
def attachments(self):
return self.properties.get('attachments', 'None')
@attachments.setter
def attachments(self, a):
self.properties['attachments'] = a
@attachments.deleter
def attachments(self):
del self.properties['attachments']
def send_email(self):
# Create the enclosing (outer) message
outer = MIMEMultipart('alternative')
outer['Subject'] = self.subject
outer['To'] = COMMASPACE.join(self.recipients)
outer['From'] = self.send_from
msg = MIMEBase('application', "octet-stream")
# Add the text of the email
email_body = MIMEText(self.message, 'plain')
outer.attach(email_body)
# Add the attachments
for file in self.attachments:
try:
with open(file, 'rb') as fp:
msg.set_payload(fp.read())
encoders.encode_base64(msg)
msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))
outer.attach(msg)
except:
print("Unable to open one of the attachments. Error: ", sys.exc_info()[0])
raise
composed = outer.as_string()
try:
with smtplib.SMTP('smtp.gmail.com', 587) as s:
s.ehlo()
s.starttls()
s.ehlo()
s.login(self.send_from, self.gmail_password)
s.sendmail(self.send_from, self.recipients, composed)
s.close()
print("Email sent!")
except:
print("Unable to send the email. Error: ", sys.exc_info()[0])
raise
def main():
pass
if __name__ == '__main__': main()
#!/usr/bin/env python
# encoding: utf-8
"""
python_3_email_with_attachment.py
Created by Robert Dempsey on 12/6/14.
Copyright (c) 2014 Robert Dempsey. Use at your own peril.
This script works with Python 3.x
NOTE: replace values in ALL CAPS with your own values
"""
import os
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
COMMASPACE = ', '
def main():
sender = 'YOUR GMAIL ADDRESS'
gmail_password = 'YOUR GMAIL PASSWORD'
recipients = ['EMAIL ADDRESSES HERE SEPARATED BY COMMAS']
# Create the enclosing (outer) message
outer = MIMEMultipart()
outer['Subject'] = 'EMAIL SUBJECT'
outer['To'] = COMMASPACE.join(recipients)
outer['From'] = sender
outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'
# List of attachments
attachments = ['FULL PATH TO ATTACHMENTS HERE']
# Add the attachments to the message
for file in attachments:
try:
with open(file, 'rb') as fp:
msg = MIMEBase('application', "octet-stream")
msg.set_payload(fp.read())
encoders.encode_base64(msg)
msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))
outer.attach(msg)
except:
print("Unable to open one of the attachments. Error: ", sys.exc_info()[0])
raise
composed = outer.as_string()
# Send the email
try:
with smtplib.SMTP('smtp.gmail.com', 587) as s:
s.ehlo()
s.starttls()
s.ehlo()
s.login(sender, gmail_password)
s.sendmail(sender, recipients, composed)
s.close()
print("Email sent!")
except:
print("Unable to send the email. Error: ", sys.exc_info()[0])
raise
if __name__ == '__main__':
main()
def send_mail(send_from: str, subject: str, text: str, send_to: list, send_cc: list, send_bcc: list, files= None, report="yes"):
# Reporting Funcs
def mail_report_beg():
print("Sender: " + str(send_from))
print("Recipients: " + str(send_to))
print("Cc Recipients: " + str(send_cc))
print("Bcc Recipients: " + str(send_bcc))
print("Attached files: " + str(files))
print("Sending....")
def mail_report_end():
print("Mail sent succesfully")
# Required libraries / modules
try:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.base import MIMEBase
from email import encoders
from os.path import basename
except:
return ("Failed to load necessary modules", 1)
# Deprecated calls
#from email.MIMEBase import MIMEBase
#from email.MIMEMultipart import MIMEMultipart
if report=="yes":
mail_report_beg()
# Fall back to default address if no send_to is empty
send_to= default_address if not send_to else send_to
# Instantiate new MIMEMultipart object
msg = MIMEMultipart()
# Assign Basic Parameters
msg['From'] = send_from
msg['To'] = ', '.join(send_to)
msg['Subject'] = subject
msg['Cc'] = ', '.join(send_cc)
msg['Bcc'] = ', '.join(send_bcc)
# Assign Body
msg.attach(MIMEText(text))
# Iterate over files and attach
for f in files or []:
with open(f, "rb") as fil:
ext = f.split('.')[-1:]
attachedfile = MIMEApplication(fil.read(), _subtype = ext)
attachedfile.add_header(
'content-disposition', 'attachment', filename=basename(f) )
msg.attach(attachedfile)
# Send Email
# Server connection info
smtp = smtplib.SMTP(host, port)
#smtp = smtplib.SMTP(host="holhub.intranet.dei.com.gr", port= 587)
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
if report=="yes":
mail_report_end()
# #########################################################
# #########################################################
# Control Panel: Server
host="holhub.intranet.dei.com.gr"
port= 587
username = 'p.doulgeridis'
password = 'Doul2018#'
#default_address = ['my-address2@gmail.com']
default_address = 'p.doulgeridis@dei.com.gr'
# #########################################################
# Control Panel: Email texts
# Note: Convert entire script to unicode.
# Subject:
subject_in = 'ΣΤΑΤΙΣΤΙΚΑ HELP DESK '
# Body:
# Note: Use the """ : """ syntax for multiline text
msg2 = """
Καλημέρα Φωτεινή,
Στείλε μου σε παρακαλώ τα αρχεία των εγγραφων
του Help Desk, 1ου και 2ου επιπεδου, για την
προηγούμενη εβδομάδα.
Ευχαριστώ,
Παναγιώτης Δουλγερίδης
"""
send_mail(
send_from= default_address,
subject=subject_in,
text=msg2,
#send_to= ['p.doulgeridis@dei.com.gr', 'p.doulgeridis@dei.com.gr', 'i.niarchos@dei.com.gr' ] ,
#send_cc= ['p.doulgeridis@dei.com.gr', 'p.doulgeridis@dei.com.gr', 'd.tsolakos@dei.com.gr', 'i.niarchos@dei.com.gr' ] ,
#send_bcc= ['p.doulgeridis@dei.com.gr', 'd.tsolakos@dei.com.gr' ] ,
#files= [ 'C:\\Users\\p.doulgeridis\\Desktop\\testzdm.XLS' ]
send_to= ['p.doulgeridis@dei.com.gr', 'p.doulgeridis@dei.com.gr'] ,
send_cc= ['p.doulgeridis@dei.com.gr', 'p.doulgeridis@dei.com.gr'] ,
send_bcc= ['p.doulgeridis@dei.com.gr'] ,
files= [ 'C:\\Users\\p.doulgeridis\\Desktop\\mtest.py', 'C:\\Users\\p.doulgeridis\\Desktop\\testzdm.XLS' ]
)
# ###############################################################
#
# single_mail_sender_param
#
# Author: p.doulgeridis
# ---------------------------------------------------------------
# Parameters: * <mail_out> -> Recipient email
# * <file_in> -> Attached file
# ---------------------------------------------------------------
# Output: None
#
# ---------------------------------------------------------------
# Required modules:
#
# import smtplib
# from email.mime.text import MIMEText
# from email.mime.multipart import MIMEMultipart
# from email.mime.application import MIMEApplication
# from email.mime.base import MIMEBase
# from email import encoders
# from os.path import basename
# import os
#
# ---------------------------------------------------------------
# Description: Single Function that sends email.
# All relevant info required are stored in Control
# Panel.
#
# * Make sure entire script is converted to utf8
#
#
# ---------------------------------------------------------------
# Instructions:
#
# L132 - > Edit server information and port
# * if ssl is required, this will need editting.
#
# L141 - > Edit email text information (make sure utf-8)
#
# L175 - > Edit cc/bcc list
#
# ###############################################################
import os
import sys
# Recipient mail - 1 mail
param_in= sys.argv[1]
file_in = sys.argv[2]
fixed_param = param_in.split()
fixed_file_in = file_in.split()
def send_mail(send_from: str, subject: str, text: str, send_to: list, send_cc: list, send_bcc: list, files= None, report="yes"):
# Reporting Funcs
def mail_report_beg():
print("Sender: " + str(send_from))
print("Recipients: " + str(send_to))
print("Cc Recipients: " + str(send_cc))
print("Bcc Recipients: " + str(send_bcc))
print("Attached files: " + str(files))
print("Sending....")
def mail_report_end():
print("Mail sent succesfully")
# Required libraries / modules
try:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.base import MIMEBase
from email import encoders
from os.path import basename
except:
return ("Failed to load necessary modules", 1)
# Deprecated calls
#from email.MIMEBase import MIMEBase
#from email.MIMEMultipart import MIMEMultipart
if report=="yes":
mail_report_beg()
# Fall back to default address if no send_to is empty
send_to= default_address if not send_to else send_to
# Instantiate new MIMEMultipart object
msg = MIMEMultipart()
# Assign Basic Parameters
msg['From'] = send_from
msg['To'] = ', '.join(send_to)
msg['Subject'] = subject
msg['Cc'] = ', '.join(send_cc)
msg['Bcc'] = ', '.join(send_bcc)
# Assign Body
msg.attach(MIMEText(text))
# Iterate over files and attach
for f in files or []:
with open(f, "rb") as fil:
ext = f.split('.')[-1:]
attachedfile = MIMEApplication(fil.read(), _subtype = ext)
attachedfile.add_header(
'content-disposition', 'attachment', filename=basename(f) )
msg.attach(attachedfile)
# Send Email
# Server connection info
smtp = smtplib.SMTP(host, port)
#smtp = smtplib.SMTP(host="holhub.intranet.dei.com.gr", port= 587)
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
if report=="yes":
mail_report_end()
# #########################################################
# #########################################################
# Control Panel: Server
host="holhub.intranet.dei.com.gr"
port= 587
username = 'p.doulgeridis'
password = 'Doul2018#'
#default_address = ['my-address2@gmail.com']
default_address = 'p.doulgeridis@dei.com.gr'
# #########################################################
# Control Panel: Email texts
# Note: Convert entire script to unicode.
# Subject:
subject_in = 'ΣΤΑΤΙΣΤΙΚΑ HELP DESK '
# Body:
# Note: Use the """ : """ syntax for multiline text
msg2 = """
Καλημέρα Φωτεινή,
Στείλε μου σε παρακαλώ τα αρχεία των εγγραφων
του Help Desk, 1ου και 2ου επιπεδου, για την
προηγούμενη εβδομάδα.
Ευχαριστώ,
Παναγιώτης Δουλγερίδης
"""
send_mail(
send_from= default_address,
subject=subject_in,
text=msg2,
#send_to= ['p.doulgeridis@dei.com.gr', 'p.doulgeridis@dei.com.gr', 'i.niarchos@dei.com.gr' ] ,
#send_cc= ['p.doulgeridis@dei.com.gr', 'p.doulgeridis@dei.com.gr', 'd.tsolakos@dei.com.gr', 'i.niarchos@dei.com.gr' ] ,
#send_bcc= ['p.doulgeridis@dei.com.gr', 'd.tsolakos@dei.com.gr' ] ,
#files= [ 'C:\\Users\\p.doulgeridis\\Desktop\\testzdm.XLS' ]
#send_to= ['p.doulgeridis@dei.com.gr', 'p.doulgeridis@dei.com.gr'] ,
send_to= fixed_param,
send_cc= ['p.doulgeridis@dei.com.gr', 'p.doulgeridis@dei.com.gr'] ,
send_bcc= ['p.doulgeridis@dei.com.gr'] ,
files= fixed_file_in
)
# ###############################################################
#
# single_mail_sender_param
#
# Author: p.doulgeridis
# ---------------------------------------------------------------
# Parameters: * <mail_out> -> Recipient email
#
# ---------------------------------------------------------------
# Output: None
#
# ---------------------------------------------------------------
# Required modules:
#
# import smtplib
# from email.mime.text import MIMEText
# from email.mime.multipart import MIMEMultipart
# from email.mime.application import MIMEApplication
# from email.mime.base import MIMEBase
# from email import encoders
# from os.path import basename
# import os
#
# ---------------------------------------------------------------
# Description: Single Function that sends email.
# All relevant info required are stored in Control
# Panel.
#
# * Make sure entire script is converted to utf8
#
#
# ---------------------------------------------------------------
# Instructions:
#
# L132 - > Edit server information and port
# * if ssl is required, this will need editting.
#
# L141 - > Edit email text information (make sure utf-8)
#
# L175 - > Edit cc/bcc list
#
# L180 - > Edit attached file.
# ###############################################################
import os
import sys
# Recipient mail - 1 mail
param_in= sys.argv[1]
fixed_param = param_in.split()
def send_mail(send_from: str, subject: str, text: str, send_to: list, send_cc: list, send_bcc: list, files= None, report="yes"):
# Reporting Funcs
def mail_report_beg():
print("Sender: " + str(send_from))
print("Recipients: " + str(send_to))
print("Cc Recipients: " + str(send_cc))
print("Bcc Recipients: " + str(send_bcc))
print("Attached files: " + str(files))
print("Sending....")
def mail_report_end():
print("Mail sent succesfully")
# Required libraries / modules
try:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.base import MIMEBase
from email import encoders
from os.path import basename
except:
return ("Failed to load necessary modules", 1)
# Deprecated calls
#from email.MIMEBase import MIMEBase
#from email.MIMEMultipart import MIMEMultipart
if report=="yes":
mail_report_beg()
# Fall back to default address if no send_to is empty
send_to= default_address if not send_to else send_to
# Instantiate new MIMEMultipart object
msg = MIMEMultipart()
# Assign Basic Parameters
msg['From'] = send_from
msg['To'] = ', '.join(send_to)
msg['Subject'] = subject
msg['Cc'] = ', '.join(send_cc)
msg['Bcc'] = ', '.join(send_bcc)
# Assign Body
msg.attach(MIMEText(text))
# Iterate over files and attach
for f in files or []:
with open(f, "rb") as fil:
ext = f.split('.')[-1:]
attachedfile = MIMEApplication(fil.read(), _subtype = ext)
attachedfile.add_header(
'content-disposition', 'attachment', filename=basename(f) )
msg.attach(attachedfile)
# Send Email
# Server connection info
smtp = smtplib.SMTP(host, port)
#smtp = smtplib.SMTP(host="holhub.intranet.dei.com.gr", port= 587)
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
if report=="yes":
mail_report_end()
# #########################################################
# #########################################################
# Control Panel: Server
host="holhub.intranet.dei.com.gr"
port= 587
username = 'p.doulgeridis'
password = 'Doul2018#'
#default_address = ['my-address2@gmail.com']
default_address = 'p.doulgeridis@dei.com.gr'
# #########################################################
# Control Panel: Email texts
# Note: Convert entire script to unicode.
# Subject:
subject_in = 'ΣΤΑΤΙΣΤΙΚΑ HELP DESK '
# Body:
# Note: Use the """ : """ syntax for multiline text
msg2 = """
Καλημέρα Φωτεινή,
Στείλε μου σε παρακαλώ τα αρχεία των εγγραφων
του Help Desk, 1ου και 2ου επιπεδου, για την
προηγούμενη εβδομάδα.
Ευχαριστώ,
Παναγιώτης Δουλγερίδης
"""
send_mail(
send_from= default_address,
subject=subject_in,
text=msg2,
#send_to= ['p.doulgeridis@dei.com.gr', 'p.doulgeridis@dei.com.gr', 'i.niarchos@dei.com.gr' ] ,
#send_cc= ['p.doulgeridis@dei.com.gr', 'p.doulgeridis@dei.com.gr', 'd.tsolakos@dei.com.gr', 'i.niarchos@dei.com.gr' ] ,
#send_bcc= ['p.doulgeridis@dei.com.gr', 'd.tsolakos@dei.com.gr' ] ,
#files= [ 'C:\\Users\\p.doulgeridis\\Desktop\\testzdm.XLS' ]
#send_to= ['p.doulgeridis@dei.com.gr', 'p.doulgeridis@dei.com.gr'] ,
send_to= fixed_param,
send_cc= ['p.doulgeridis@dei.com.gr', 'p.doulgeridis@dei.com.gr'] ,
send_bcc= ['p.doulgeridis@dei.com.gr'] ,
files= [ 'C:\\Users\\p.doulgeridis\\Desktop\\mtest.py', 'C:\\Users\\p.doulgeridis\\Desktop\\testzdm.XLS' ]
import os
import sys
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.base import MIMEBase
from email import encoders
from os.path import basename
def send_mail(send_from: str, subject: str, text: str, send_to: list, send_cc: list, send_bcc: list, files= None):
send_to= default_address if not send_to else send_to
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = ', '.join(send_to)
msg['Subject'] = subject
msg['Cc'] = ', '.join(send_cc)
msg['Bcc'] = ', '.join(send_bcc)
msg.attach(MIMEText(text))
for f in files or []:
with open(f, "rb") as fil:
ext = f.split('.')[-1:]
attachedfile = MIMEApplication(fil.read(), _subtype = ext)
attachedfile.add_header(
'content-disposition', 'attachment', filename=basename(f) )
msg.attach(attachedfile)
smtp = smtplib.SMTP(host="holhub.intranet.dei.com.gr", port= 587)
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
# ###############################################################
# Mail Zone
username = 'p.doulgeridis'
password = 'Doul2019'
default_address = 'p.doulgeridis@dei.com.gr'
subject_in = 'ΣΤΑΤΙΣΤΙΚΑ HELP DESK 2 '
msg2 = """
Καλησπερα,
Βρεθηκε μεγαλος αριθμος αρχειων στον φακελο ελεγχου.
Παρακαλω οπως αφαιρεσετε αρχεια: {0}
Ευχαριστώ,
Παναγιώτης Δουλγερίδης
""".format(len(lista))
try:
print("Sending email..")
send_mail(
send_from= default_address,
subject=subject_in,
text=msg2,
send_to= ['p.doulgeridis@dei.com.gr'] ,
send_cc= ['p.doulgeridis@dei.com.gr' ] ,
send_bcc= ['p.doulgeridis@dei.com.gr' ] ,
)
except BaseException as e:
print("Email failed to send: " + str(e))
else:
print("Email successfully sent")