79 lines
2.7 KiB
Python
Executable File
79 lines
2.7 KiB
Python
Executable File
"""
|
|
Module for sending emails
|
|
"""
|
|
import os
|
|
|
|
from email import encoders
|
|
from email.mime.text import MIMEText
|
|
from email.mime.base import MIMEBase
|
|
from email.mime.multipart import MIMEMultipart
|
|
|
|
import types
|
|
import smtplib
|
|
|
|
|
|
SUPPORTED_TEXT_ATTACHMENTS = ['xml', 'ulog', 'txt', 'ms', 'py', 'ini']
|
|
SUPPORTED_IMAGE_ATTACHMENTS = ['png', 'tga', 'jpg', 'bmp']
|
|
SUPPORTED_ATTACHMENTS = SUPPORTED_TEXT_ATTACHMENTS + SUPPORTED_IMAGE_ATTACHMENTS
|
|
|
|
|
|
def Send(emailFrom, emailTo, emailSubject, emailBody, asHtml=False, attachments=[], exchangeServer=None):
|
|
"""
|
|
Sends an email using the exchange server found in the project module.
|
|
|
|
Arguments:
|
|
emailFrom (string): email address of the sender
|
|
emailTo (list): list of email addresses to send email to
|
|
emailSubject (string): the subject/title of the email
|
|
emailBody (string): the content of the email
|
|
asHtml (boolean): add the content of the email as html
|
|
attachments (list): list of paths to files to attach
|
|
exchangeServer (string): server to use for sending the email
|
|
"""
|
|
|
|
if not isinstance(emailTo, (types.ListType, types.TupleType)):
|
|
emailTo = [emailTo]
|
|
|
|
message = MIMEMultipart('alternative')
|
|
message['Subject'] = '{0}'.format(emailSubject)
|
|
message['To'] = ";".join(emailTo)
|
|
message['From'] = emailFrom
|
|
|
|
body = MIMEText(emailBody, ('plain', 'html')[asHtml])
|
|
|
|
message.attach(body)
|
|
|
|
for attachment in attachments:
|
|
if not os.path.isfile(attachment):
|
|
print 'Could not attach file ({0}) because it does not exist!'.format(attachment)
|
|
continue
|
|
|
|
fileType = os.path.splitext(attachment)[-1][1:].lower()
|
|
if fileType in SUPPORTED_ATTACHMENTS:
|
|
|
|
isImage = fileType in SUPPORTED_IMAGE_ATTACHMENTS
|
|
|
|
part = MIMEBase('application', 'octet-stream')
|
|
with open(attachment, 'rb'[:isImage + 1]) as attachmentFile:
|
|
part.set_payload(attachmentFile.read())
|
|
encoders.encode_base64(part)
|
|
part.add_header('Content-Disposition', 'attachment; filename={0}'.format(os.path.basename(attachment)))
|
|
message.attach(part)
|
|
|
|
continue
|
|
|
|
print ('The attachment file type ({0}) is not supported! '
|
|
' You will need to add the file type as a supported type to this module.'.format(fileType))
|
|
|
|
try:
|
|
if not exchangeServer:
|
|
from RS import Config
|
|
exchangeServer = Config.User.ExchangeServer
|
|
|
|
server = smtplib.SMTP(exchangeServer)
|
|
server.sendmail(emailFrom, emailTo, message.as_string())
|
|
server.quit()
|
|
|
|
except:
|
|
print 'Could not send the email!'
|