예제 #1
0
def send_mail(send_from, send_to, subject, text, files=[], html=None, server="localhost"):
  assert type(send_to)==list
  assert type(files)==list

  if html:
    msg = MIMEMultipart('alternative')
    textbody = dehtml(text)
    part1 = MIMEText(textbody, 'plain')
    part2 = MIMEText(text, 'html')
    msg.attach(part1)
    msg.attach(part2)
  else:  
    msg = MIMEMultipart()
    msg.attach( MIMEText(text) )

  msg['From'] = send_from
  msg['To'] = COMMASPACE.join(send_to)
  msg['Date'] = formatdate(localtime=True)
  msg['Subject'] = subject
  
  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.sendmail(send_from, send_to, msg.as_string())
  smtp.close()
예제 #2
0
def sendmail(subject):
    MAIL_FROM = '*****@*****.**'
    MAIL_TO = ['*****@*****.**']
    BAK_DIR = '/path/to/bak/folder'

    msg = MIMEMultipart()
    msg['From'] = MAIL_FROM
    msg['Subject'] = subject

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

    try:
        smtp = ExtendedSMTP()
        smtp.callback = callback
        smtp.connect('smtp.qq.com', 25)
        smtp.login('mymail', 'mypwd')
        smtp.sendmail(MAIL_FROM, MAIL_TO, msg.as_string())
        smtp.close()
        os.system('rm -f %s/*' % BAK_DIR)
    except Exception, e:
        print e
예제 #3
0
def send_email(to, name, file):
    import smtplib, os
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email.MIMEText import MIMEText
    from email.Utils import COMMASPACE, formatdate
    from email import Encoders

    msg = MIMEMultipart()
    msg["Subject"] = "Your task is processed"
    msg["From"] = "poddy.org"
    msg["To"] = to

    msg.attach(MIMEText("Dear %s, thank you for using SourceAnalyzer Web!" % name))
    msg.attach(MIMEText("See in attachment."))

    part = MIMEBase("application", "octet-stream")

    f = open(file, "rb")
    part.set_payload(f.read())
    f.close()

    Encoders.encode_base64(part)
    part.add_header("Content-Disposition", 'attachment; filename="%s"' % os.path.basename(file))
    msg.attach(part)

    s = smtplib.SMTP("localhost")
    s.sendmail("*****@*****.**", [to], msg.as_string())
    s.quit()
 def enviar_correos(self, pathfirma , partner, data):
     msg = MIMEMultipart()
     destinatario = ['%s <%s>' % (partner.name,partner.email) ] 
     msg['To'] = '%s' % partner.email
     msg['From'] = '*****@*****.**'        
     msg['Subject'] = 'factura numero %s' % str(data.number)                    
     name_file = 'DTE_PRUEBA_%s.xml'  % str(datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S"))
     msg.attach(MIMEText("""
     Estimado cliente adjunto factura N°<h3>%s</h3></br>
     sub total: %s</br>
     impuesto: %s</br>
     total: %s</br>"""%(str(data.number),str(data.amount_untaxed),str(data.amount_tax),str(data.amount_total))
     ,'html'))                
     adjunto = MIMEBase('multipart', 'mixed')                
     with open(pathfirma, 'r') as myfile:
         adjunto.set_payload(myfile.read())
         myfile.close()        
     encoders.encode_base64(adjunto)        
     adjunto.add_header('Content-Disposition', 'attachment', filename='factura.xml')        
     msg.attach(adjunto)                
     mailServer = smtplib.SMTP('mail.econube.cl', 26)        
     mailServer.set_debuglevel(1)
     mailServer.ehlo()
     mailServer.starttls()                        
     mailServer.login("*****@*****.**","dte2015")
     mailServer.sendmail("*****@*****.**", destinatario, msg.as_string())
     mailServer.quit()
예제 #5
0
파일: chaski.py 프로젝트: gercaceres/chaski
def mail(to, subject, text, attach):
   print '\nPlease enter password to connect with your Gmail account'
   password = getpass.getpass()
   msg = MIMEMultipart()

   msg['From'] = sender
   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(sender, password)
   mailServer.sendmail(sender, to, msg.as_string())
   mailServer.close()
예제 #6
0
def send_mail(send_from, send_to, subject, text, files=[], server="localhost",password=None,user=None):
  if type(send_to) in types.StringTypes: send_to = [send_to]
  if files is None: files = []
  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")
    content = open(f, 'rb').read()
    part.set_payload(content)
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
    msg.attach(part)

  smtp = smtplib.SMTP(server)
  if password:
    if not user: user = msg['From']
    smtp.starttls()  
    smtp.login(user,password)      
  smtp.sendmail(send_from, send_to, msg.as_string())
  smtp.close()
예제 #7
0
def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
    import smtplib
    import os
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email.MIMEText import MIMEText
    from email.Utils import COMMASPACE, formatdate
    from email import Encoders
    assert type(send_to)==list
    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.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
예제 #8
0
def mail(to, subject, text, attach):
    msg = MIMEMultipart()

    print gmail_user
    msg['From'] = gmail_user
    realToString=''
    for s in to:
        realToString = realToString + s + ","
#    print realToString,to, [gmail_user]+[]+to
    msg['To'] = gmail_user#realToString
    msg['Subject'] = subject

    msg.attach(MIMEText(text))


    #attach each file in the list
    for file in attach:
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(open(file, 'rb').read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition',
                'attachment; filename="%s"' % os.path.basename(file))
        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, [gmail_user]+[]+to, msg.as_string())
    # Should be mailServer.quit(), but that crashes...
    mailServer.close()
def sendEmail(to, subject, text, files=[]):
        assert type(to)==list
        assert type(files)==list

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

        msg.attach( MIMEText(text) )

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

                server = smtplib.SMTP('smtp.gmail.com:587')
                server.ehlo_or_helo_if_needed()
                server.starttls()
                server.ehlo_or_helo_if_needed()
                server.login(USERNAME,PASSWORD)
                server.sendmail(USERNAME, MAILTO, msg.as_string())
                server.quit()
예제 #10
0
파일: sendfile.py 프로젝트: gry/mailutils
def send_mail(send_from, send_to, subject, text, files=[], server="localhost", port=25):
    assert type(send_to)==list
    assert type(files)==list

    # We must choose the body charset manually
    for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
        try:
            text.encode(body_charset)
        except UnicodeError:
            pass
        else:
            break

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

    msg.attach( MIMEText(text.encode(body_charset), 'plain', body_charset) )

    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(host=server, port=port, local_hostname='cked.es')
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
예제 #11
0
파일: mail.py 프로젝트: wilatai/cyclone
    def attach(self, filename, mime=None, charset=None, content=None):
        base = os.path.basename(filename)
        if content is None:
            fd = open(filename)
            content = fd.read()
            fd.close()

        if not isinstance(content, types.StringType):
            raise TypeError("don't know how to handle content: %s" % type(content))
        
        part = MIMEBase("application", "octet-stream")
        part.set_payload(content)
        Encoders.encode_base64(part)
        part.add_header("Content-Disposition", "attachment; filename=\"%s\"" % base)
        
        if mime is not None:
            part.set_type(mime)

        if charset is not None:
            part.set_charset(charset)

        if self.msg is None:
            self.msg = MIMEMultipart()
            self.msg.attach(self.message)

        self.msg.attach(part)
예제 #12
0
def send_mail(send_to, subject, text, files=[], server='localhost',
        username=None, password=None):

    send_from = '*****@*****.**'

    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"' % basename(f))
        msg.attach(part)

    smtp = SMTP(server)
    if username is not None:
        smtp.login(str(username), str(password))

    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
예제 #13
0
    def get_mail_text(self, fields, request, **kwargs):
        """ Get header and body of e-amil as text (string)
            This will create both parts of the e-mail: text and the XML file
        """

        headerinfo, additional_headers, body = self.get_header_body_tuple(fields, request, **kwargs)
        body_xml = self.get_mail_text_in_xml(fields, request, **kwargs)

        self.safe_xml_in_filesystem(body_xml)

        mime_text = MIMEText(body, _subtype=self.body_type or 'html', _charset=self._site_encoding())
        attachments = self.get_attachments(fields, request)

        outer = MIMEMultipart()
        outer.attach(mime_text)

        # write header
        for key, value in headerinfo.items():
            outer[key] = value

        # write additional header
        for a in additional_headers:
            key, value = a.split(':', 1)
            outer.add_header(key, value.strip())

        for attachment in attachments:
            filename = attachment[0]
            ctype = attachment[1]
            encoding = attachment[2]
            content = attachment[3]

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

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

            if maintype == 'text':
                msg = MIMEText(content, _subtype=subtype)
            elif maintype == 'image':
                msg = MIMEImage(content, _subtype=subtype)
            elif maintype == 'audio':
                msg = MIMEAudio(content, _subtype=subtype)
            else:
                msg = MIMEBase(maintype, subtype)
                msg.set_payload(content)
                # Encode the payload using Base64
                Encoders.encode_base64(msg)

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

        ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        p = MIMEBase(maintype, subtype)
        p.set_payload(body_xml)
        p.add_header('content-disposition', 'attachment', filename='form.xml')
        Encoders.encode_base64(p)
        outer.attach(p)
        return outer.as_string()
예제 #14
0
    def attach(self, filename, mime=None, charset=None, content=None):
        """Attach files to this message.

        Example::

            msg.attach("me.png", mime="image/png")

        It also supports fake attachments::

            msg.attach("fake.txt", mime="text/plain", content="gotcha")
        """
        base = os.path.basename(filename)
        if content is None:
            fd = open(filename)
            content = fd.read()
            fd.close()
        elif not isinstance(content, types.StringType):
            raise TypeError("Don't know how to attach content: %s" % repr(content))

        part = MIMEBase("application", "octet-stream")
        part.set_payload(content)
        Encoders.encode_base64(part)
        part.add_header("Content-Disposition", "attachment", filename=base)

        if mime is not None:
            part.set_type(mime)

        if charset is not None:
            part.set_charset(charset)

        if self.msg is None:
            self.msg = MIMEMultipart()
            self.msg.attach(self.message)

        self.msg.attach(part)
예제 #15
0
파일: z2.py 프로젝트: MageCraft/pyfreecell
def send_email_csv_attach(toaddrs, mail, csv_fn, fromaddr=EMAIL_SENDER_ADDR):
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = toaddrs
    msg['Subject'] = 'please check attached csv file for cr status'
    msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'
    # To guarantee the message ends with a newline
    msg.epilogue = ''

    #body
    text = MIMEText(mail)
    msg.attach(text)

    #attachment
    csv = MIMEBase('text', 'x-comma-separated-values')
    fp = open(csv_fn, 'rb')
    csv.set_payload(fp.read())
    Encoders.encode_base64(csv)
    csv.add_header('Content-Disposition', 'attachment', filename=os.path.basename(csv_fn))
    msg.attach(csv)

    server = smtplib.SMTP('remotesmtp.mot.com')
    server.set_debuglevel(1)
    server.sendmail(fromaddr, toaddrs, msg.as_string())
    server.quit()
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))
   print os.path.basename
   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()
예제 #17
0
파일: send.py 프로젝트: Bobain/utils
def send_file_via_mail(file, subject, message, mail_to, mail_from, smtp_server, smtp_port, mail_password_env_name):
    msg = MIMEMultipart()

    msg['From'] = mail_from
    msg['To'] = mail_to
    msg['Subject'] = subject

    body = message

    msg.attach(MIMEText(body, 'plain'))

    filename = file
    attachment = open(filename, "rb")

    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

    msg.attach(part)

    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()
    server.login(mail_from, os.getenv(mail_password_env_name))
    text = msg.as_string()
    server.sendmail(mail_from, mail_to, text)
    server.quit()
예제 #18
0
def mail(to, frm, subject, text, attach, smtphost, smtpuser, smtppass):
   msg = MIMEMultipart()

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

   msg.attach(MIMEText(text))
	
   if attach:
     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(smtphost, 587)
   mailServer.ehlo()
   mailServer.starttls()
   mailServer.ehlo()
   mailServer.login(smtpuser, smtppass)
   mailServer.sendmail(smtpuser, to, msg.as_string())
   # todo, we should keep server open if we send a list of emails, do this on a to user bases for lists
   # Should be mailServer.quit(), but that crashes...
   mailServer.close()
예제 #19
0
    def sendEmailAlert(self):
        msg = MIMEMultipart()
        alert = "Found hit for {matches} in pastie {url}".format(matches=self.matchesToText(), url=self.url)
        # headers
        msg['Subject'] = yamlconfig['email']['subject'].format(subject=alert)
        msg['From'] = yamlconfig['email']['from']
        msg['To'] = yamlconfig['email']['to']
        # message body
        message = '''
I found a hit for a regular expression on one of the pastebin sites.

The site where the paste came from :        {site}
The original paste was located here:        {url}
And the regular expressions that matched:   {matches}
The paste has also been attached to this email.

# LATER below follows a small exerpt from the paste to give you direct context

        '''.format(site=self.site.name, url=self.url, matches=self.matchesToRegex())
        msg.attach(MIMEText(message))
        # original paste as attachment
        part = MIMEBase('application', "octet-stream")
        part.set_payload(self.pastie_content)
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s.txt"' % (self.id))
        msg.attach(part)
        # send out the mail
        try:
            s = smtplib.SMTP(yamlconfig['email']['server'], yamlconfig['email']['port'])
            if 'username' in yamlconfig['email'] and yamlconfig['email']['username']:
                s.login(yamlconfig['email']['username'], yamlconfig['email']['password'])
            s.sendmail(yamlconfig['email']['from'], yamlconfig['email']['to'], msg.as_string())
            s.close()
        except smtplib.SMTPException, e:
            logger.error("ERROR: unable to send email: {0}".format(e))
예제 #20
0
def mail(to, subject, text, attach=None):
   msg = MIMEMultipart()

   msg['From'] = email_settings.email_from_addr
   msg['To'] = to
   msg['Subject'] = subject

   msg.attach(MIMEText(text))
  
   if attach:
       print attach
       print os.path.normpath(attach)
       fp = open(attach, 'r')
       msg.attach(MIMEText(fp.read()))# Put the attachment in line also
       fp.close()

       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(email_settings.email_from_addr, email_settings.gmail_pwd)
   mailServer.sendmail(email_settings.email_from_addr, to, msg.as_string())
   # Should be mailServer.quit(), but that crashes...
   mailServer.close()
예제 #21
0
    def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
        assert type(send_to)==list
        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)

        #Set Email smtp parameters
        smtp = smtplib.SMTP('smtp.gmail.com:587')
        smtp.starttls()
        smtp.login('*****@*****.**', 'pythonheat1')
        smtp.sendmail(send_from, send_to, msg.as_string())
        smtp.close()
예제 #22
0
def send_mail(server, port, account, password, tls, _from, to, subject, message, files):
    conn = smtplib.SMTP(server, port, timeout=settings.SMTP_TIMEOUT)
    if tls:
        conn.starttls()
    
    if account and password:
        conn.login(account, password)
    
    email = MIMEMultipart()
    email['Subject'] = subject
    email['From'] = _from
    email['To'] = ', '.join(to)
    email.attach(MIMEText(message))
    
    for file in reversed(files):
        part = MIMEBase('image', 'jpeg')
        with open(file, 'rb') as f:
            part.set_payload(f.read())
        
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
        email.attach(part)
    
    if files:
        logging.debug('attached %d pictures' % len(files))

    logging.debug('sending email message')
    conn.sendmail(_from, to, email.as_string())
    conn.quit()
예제 #23
0
def send_mail(send_to, subject, text, file):

    msg = MIMEMultipart()
    msg['From'] = 'ITLand.Root <*****@*****.**>'
    msg['To'] = send_to
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(MIMEText(text))

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

    #server = smtplib.SMTP('smtp.gmail.com:587')
    #server.starttls()
    #server.login('jenko.kov', 'efi42dekut')
    #server.sendmail(send_from, send_to, msg.as_string())
    #server.quit()

    server = smtplib.SMTP('172.16.10.254:25')
    server.sendmail(send_from, send_to, msg.as_string())
    server.quit()
예제 #24
0
    def sendmail(self, destination, subject, message, attach = None):        
        try:
            msg = MIMEMultipart()

            msg['From'] = self.username
            msg['Reply-to'] = self.username
            msg['To'] = destination
            msg['Subject'] = subject

            msg.attach(MIMEText(message))

            if attach:
                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 = SMTP("smtp.gmail.com", 587)
            mailServer.ehlo()
            mailServer.starttls()
            mailServer.ehlo()
            try:
                mailServer.login(self.username, self.password)
                mailServer.sendmail(self.username, destination, msg.as_string())
            finally:
                mailServer.close()
        except Exception, exc:
            sys.exit("Failed to send mail; %s" % str(exc))
예제 #25
0
def send_mail(send_from, send_to, subject, text, files=[], server='smtp.typa.ru'):
	from smtplib import SMTP
	from os import path
	from email.MIMEMultipart import MIMEMultipart
	from email.MIMEBase import MIMEBase
	from email.MIMEText import MIMEText
	from email.Utils import COMMASPACE, formatdate
	from email import Encoders
	from email.header import Header

	assert type(send_to)==list
	assert type(files)==list
	msg = MIMEMultipart()
	msg['From'] = Header(send_from.decode("utf-8")).encode()
	msg['To'] = Header(COMMASPACE.join(send_to).decode("utf-8")).encode()
	msg['Date'] = formatdate(localtime=True)
	msg['Subject'] = Header(subject.decode("utf-8")).encode()
	msg.attach( MIMEText(text,'plain','UTF-8') )

	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"' % path.basename(f))
		msg.attach(part)
	smtp = SMTP(server, 25)
	smtp.sendmail(send_from, send_to, msg.as_string())
	smtp.close()		
예제 #26
0
def mail(to, cc, subject, text, attach):
    '''Sends email from [email protected]'''
    username = "******"
    password = "******"
    msg = MIMEMultipart()

    msg['From'] = username
    msg['To'] = ", ".join(to)
    msg['Subject'] = subject
    msg['Cc'] = ", ".join(cc)

    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.fordfound.org", 25)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(username, password)
    mailServer.sendmail(username, to+cc, msg.as_string())
    mailServer.close()
예제 #27
0
파일: common.py 프로젝트: LamCiuLoeng/vat
def sendEmail(send_from, send_to, subject, text, cc_to=[], files=[], server="192.168.42.13"):
    assert type(send_to)==list
    assert type(files)==list

    msg=MIMEMultipart()
    msg.set_charset("utf-8")
    msg['From']=send_from
    msg['To']=COMMASPACE.join(send_to)

    if cc_to:
        assert type(cc_to)==list
        msg['cc']=COMMASPACE.join(cc_to)
        send_to.extend(cc_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"'%Header(os.path.basename(f), 'utf-8'))
        msg.attach(part)

    smtp=smtplib.SMTP(server)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
예제 #28
0
def mail(To,From,Server='localhost',Subject='',Message='',Attachments=[]):
    import smtplib
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email.MIMEText import MIMEText
    from email.utils import COMMASPACE, formatdate
    from email import Encoders
    
    To = ','.join(To)
    msg = MIMEMultipart()
    msg['From'] = From
    msg['To'] = To
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = Subject
    
    msg.attach(MIMEText(Message))
    
    if Attachments:
        for file in Attachments:
            part = MIMEBase('application','octet-stream')
            part.set_payload(open(file,'rb').read())
            part.add_header('Content-Disposition','attachment; filename=%s' % os.path.basename(file))
            msg.attach(part)
    
    smtp = smtplib.SMTP(Server)
    smtp.sendmail(From,To,msg.as_string())
    smtp.close()
예제 #29
0
def SendEmail(fPaths, isAttachmt, body, toList, ccList, bccList, subject):
	
	HOST = "cormailgw.raleighnc.gov"
	#FROM = "*****@*****.**"
	FROM = "*****@*****.**"
	TO = toList
	CC = ccList
	BCC = bccList
	msg = MIMEMultipart()
	msg['FROM'] = FROM 
	msg['TO'] = TO
	msg['CC'] = CC
	msg['BCC'] = BCC
	msg['Date'] = formatdate(localtime = True)
	msg['Subject'] = subject
	msg.attach(MIMEText(body))
	if isAttachmt:
		for fPath in fPaths:
			part = MIMEBase('text/plain', 'octet-stream')
			part.set_payload(open(fPath, 'rb').read())
			Encoders.encode_base64(part)
			part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(fPath))
			msg.attach(part)
			print ("message attached")
	server = smtplib.SMTP(HOST)
	print ("Connected to server")
	server.sendmail(FROM, TO.split(",") + CC.split(",") + BCC.split(","), msg.as_string())
	print ("Sending Email...")
	server.close()
	for fPath in fPaths:
		os.remove(fPath)	
	print ("Email sent")
예제 #30
0
def load_attachment(file):
    part = MIMEBase("application", "octet-stream")
    part.set_payload(open(file, "rb").read())
    Encoders.encode_base64(part)
    part.add_header("Content-Disposition", 'attachment; filename="%s"' % os.path.basename(file))

    return part
예제 #31
0
            toaddrs = [email]
            subject = 'scalarizr report from hostname %s (role: %s , serverid: %s)' % (
                hostname, role_name, server_id)

            msg = MIMEMultipart()
            msg['From'] = fromaddr
            msg['To'] = email
            msg['Date'] = formatdate(localtime=True)
            msg['Subject'] = subject

            text_msg = MIMEText(subject)
            msg.attach(text_msg)

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

            for server in get_mx_records(email):
                try:
                    print 'Sending message to %s through %s' % (email, server)
                    smtp = smtplib.SMTP(server)
                    smtp.sendmail(fromaddr, toaddrs, msg.as_string())
                    break
                except (Exception, BaseException), e:
                    print e, '\nTrying next mx entry'
                finally:
예제 #32
0
print('Trying to send an email')
mailSender = '*****@*****.**'
mailReciever = '[email protected],[email protected]'
msg['Subject'] = 'The script finished successfully (ppBetaGA.py)'
msg['From'] = mailSender
msg['To'] = mailReciever
body = 'Script ppBetaGA has finished (%s). Attachments enclosed.' %datestamp
content = MIMEText(body)
# looking for latest output file to be attached
latestOutput = max(glob.glob('%s/*.txt' % MAILFILEPATH), key = os.path.getctime)
lOutputFile = latestOutput.replace('%s/' % MAILFILEPATH,"")
print('Latest output file found - %s' % lOutputFile)
# attaching output files
docs1 = MIMEBase('application', "octet-stream")
docs2 = MIMEBase('application', "octet-stream")
docs1.set_payload(open("%s/%s" % (MAILFILEPATH, lOutputFile), "rb").read())
docs2.set_payload(open("%s/mailto/mailto.txt" % MAILFILEPATH, "rb").read())
Encoders.encode_base64(docs1)
Encoders.encode_base64(docs2)

docs1.add_header('Content-Disposition', 'attachment; filename="Output.txt"')
docs2.add_header('Content-Disposition', 'attachment; filename="mail-info.txt"')
print('Files attached')
msg.attach(content)
msg.attach(docs1)
msg.attach(docs2)
# connecting to the server and sending the mail
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login('*****@*****.**','mattytestingmail')
server.sendmail(mailSender, mailReciever.split(','), msg.as_string())
예제 #33
0
    def build_email(self, email_from, email_to, subject, body, email_cc=None, email_bcc=None, reply_to=False,
               attachments=None, message_id=None, references=None, object_id=False, subtype='plain', headers=None,
               body_alternative=None, subtype_alternative='plain'):
        """Constructs an RFC2822 email.message.Message object based on the keyword arguments passed, and returns it.

           :param string email_from: sender email address
           :param list email_to: list of recipient addresses (to be joined with commas) 
           :param string subject: email subject (no pre-encoding/quoting necessary)
           :param string body: email body, of the type ``subtype`` (by default, plaintext).
                               If html subtype is used, the message will be automatically converted
                               to plaintext and wrapped in multipart/alternative, unless an explicit
                               ``body_alternative`` version is passed.
           :param string body_alternative: optional alternative body, of the type specified in ``subtype_alternative``
           :param string reply_to: optional value of Reply-To header
           :param string object_id: optional tracking identifier, to be included in the message-id for
                                    recognizing replies. Suggested format for object-id is "res_id-model",
                                    e.g. "12345-crm.lead".
           :param string subtype: optional mime subtype for the text body (usually 'plain' or 'html'),
                                  must match the format of the ``body`` parameter. Default is 'plain',
                                  making the content part of the mail "text/plain".
           :param string subtype_alternative: optional mime subtype of ``body_alternative`` (usually 'plain'
                                              or 'html'). Default is 'plain'.
           :param list attachments: list of (filename, filecontents) pairs, where filecontents is a string
                                    containing the bytes of the attachment
           :param list email_cc: optional list of string values for CC header (to be joined with commas)
           :param list email_bcc: optional list of string values for BCC header (to be joined with commas)
           :param dict headers: optional map of headers to set on the outgoing mail (may override the
                                other headers, including Subject, Reply-To, Message-Id, etc.)
           :rtype: email.message.Message (usually MIMEMultipart)
           :return: the new RFC2822 email message
        """
        email_from = email_from or tools.config.get('email_from')
        assert email_from, "You must either provide a sender address explicitly or configure "\
                           "a global sender address in the server configuration or with the "\
                           "--email-from startup parameter."

        # Note: we must force all strings to to 8-bit utf-8 when crafting message,
        #       or use encode_header() for headers, which does it automatically.

        headers = headers or {} # need valid dict later

        if not email_cc: email_cc = []
        if not email_bcc: email_bcc = []
        if not body: body = u''

        email_body_utf8 = ustr(body).encode('utf-8')
        email_text_part = MIMEText(email_body_utf8, _subtype=subtype, _charset='utf-8')
        msg = MIMEMultipart()

        if not message_id:
            if object_id:
                message_id = tools.generate_tracking_message_id(object_id)
            else:
                message_id = make_msgid()
        msg['Message-Id'] = encode_header(message_id)
        if references:
            msg['references'] = encode_header(references)
        msg['Subject'] = encode_header(subject)
        msg['From'] = encode_rfc2822_address_header(email_from)
        del msg['Reply-To']
        if reply_to:
            msg['Reply-To'] = encode_rfc2822_address_header(reply_to)
        else:
            msg['Reply-To'] = msg['From']
        msg['To'] = encode_rfc2822_address_header(COMMASPACE.join(email_to))
        if email_cc:
            msg['Cc'] = encode_rfc2822_address_header(COMMASPACE.join(email_cc))
        if email_bcc:
            msg['Bcc'] = encode_rfc2822_address_header(COMMASPACE.join(email_bcc))
        msg['Date'] = formatdate()
        # Custom headers may override normal headers or provide additional ones
        for key, value in headers.iteritems():
            msg[ustr(key).encode('utf-8')] = encode_header(value)

        if subtype == 'html' and not body_alternative and html2text:
            # Always provide alternative text body ourselves if possible.
            text_utf8 = tools.html2text(email_body_utf8.decode('utf-8')).encode('utf-8')
            alternative_part = MIMEMultipart(_subtype="alternative")
            alternative_part.attach(MIMEText(text_utf8, _charset='utf-8', _subtype='plain'))
            alternative_part.attach(email_text_part)
            msg.attach(alternative_part)
        elif body_alternative:
            # Include both alternatives, as specified, within a multipart/alternative part
            alternative_part = MIMEMultipart(_subtype="alternative")
            body_alternative_utf8 = ustr(body_alternative).encode('utf-8')
            alternative_body_part = MIMEText(body_alternative_utf8, _subtype=subtype_alternative, _charset='utf-8')
            alternative_part.attach(alternative_body_part)
            alternative_part.attach(email_text_part)
            msg.attach(alternative_part)
        else:
            msg.attach(email_text_part)

        if attachments:
            for (fname, fcontent) in attachments:
                filename_rfc2047 = encode_header_param(fname)
                part = MIMEBase('application', "octet-stream")

                # The default RFC2231 encoding of Message.add_header() works in Thunderbird but not GMail
                # so we fix it by using RFC2047 encoding for the filename instead.
                part.set_param('name', filename_rfc2047)
                part.add_header('Content-Disposition', 'attachment', filename=filename_rfc2047)

                part.set_payload(fcontent)
                Encoders.encode_base64(part)
                msg.attach(part)
        return msg
예제 #34
0
def _mail_recipient_html(sender_name='Humanitarian Data Exchange (HDX)',
                         sender_email='*****@*****.**',
                         recipients_list=None,
                         subject=None,
                         content_dict=None,
                         cc_recipients_list=None,
                         bcc_recipients_list=None,
                         footer=True,
                         headers={},
                         reply_wanted=False,
                         snippet='email/email.html',
                         file=None):

    if sender_email:
        mail_from = sender_email
    else:
        mail_from = config.get(
            'hdx_smtp.mail_from_please_reply') if reply_wanted else config.get(
                'smtp.mail_from')

    template_data = {
        'data': {
            'data': content_dict,
            'footer': footer,
            '_snippet': snippet
        },
    }
    body_html = mailer.render_jinja2('email/email.html', template_data)

    # msg = MIMEMultipart('alternative')
    msg = MIMEMultipart()
    for k, v in headers.items():
        msg[k] = v
    subject = Header(subject.encode('utf-8'), 'utf-8')
    msg['Subject'] = subject
    msg['From'] = _(u"%s <%s>") % (sender_name, mail_from)
    recipient_email_list = []
    recipients = None
    if recipients_list:
        for r in recipients_list:
            email = r.get('email')
            recipient_email_list.append(email)
            display_name = r.get('display_name')
            if display_name:
                recipient = u"%s <%s>" % (display_name, email)
            else:
                recipient = u"%s" % email
            # else:
            # no recipient list provided
            recipients = ', '.join([recipients, recipient
                                    ]) if recipients else recipient

    msg['To'] = Header(recipients, 'utf-8')
    if bcc_recipients_list:
        for r in bcc_recipients_list:
            recipient_email_list.append(r.get('email'))
    cc_recipients = None
    if cc_recipients_list:
        for r in cc_recipients_list:
            recipient_email_list.append(r.get('email'))
            cc_recipient = u"%s <%s>" % (r.get('display_name'), r.get('email'))
            cc_recipients = ', '.join([cc_recipients, cc_recipient
                                       ]) if cc_recipients else cc_recipient
        msg['Cc'] = cc_recipients if cc_recipients else ''

    msg['Date'] = Utils.formatdate(time())
    msg['X-Mailer'] = "CKAN %s" % ckan.__version__
    if sender_email:
        msg['Reply-To'] = Header((u"%s <%s>" % (sender_name, sender_email)),
                                 'utf-8')
    part = MIMEText(body_html, 'html', 'utf-8')
    msg.attach(part)

    if isinstance(file, cgi.FieldStorage):
        _part = MIMEBase('application', 'octet-stream')
        _part.set_payload(file.file.read())
        Encoders.encode_base64(_part)
        extension = file.filename.split('.')[-1]
        header_value = 'attachment; filename=attachment.{0}'.format(extension)
        _part.add_header('Content-Disposition', header_value)
        msg.attach(_part)

    # Send the email using Python's smtplib.
    smtp_connection = smtplib.SMTP()
    if 'smtp.test_server' in config:
        # If 'smtp.test_server' is configured we assume we're running tests,
        # and don't use the smtp.server, starttls, user, password etc. options.
        smtp_server = config['smtp.test_server']
        smtp_starttls = False
        smtp_user = None
        smtp_password = None
    else:
        smtp_server = config.get('smtp.server', 'localhost')
        smtp_starttls = paste.deploy.converters.asbool(
            config.get('smtp.starttls'))
        smtp_user = config.get('smtp.user')
        smtp_password = config.get('smtp.password')
    smtp_connection.connect(smtp_server)
    try:
        # smtp_connection.set_debuglevel(True)

        # Identify ourselves and prompt the server for supported features.
        smtp_connection.ehlo()

        # If 'smtp.starttls' is on in CKAN config, try to put the SMTP
        # connection into TLS mode.
        if smtp_starttls:
            if smtp_connection.has_extn('STARTTLS'):
                smtp_connection.starttls()
                # Re-identify ourselves over TLS connection.
                smtp_connection.ehlo()
            else:
                raise MailerException("SMTP server does not support STARTTLS")

        # If 'smtp.user' is in CKAN config, try to login to SMTP server.
        if smtp_user:
            assert smtp_password, ("If smtp.user is configured then "
                                   "smtp.password must be configured as well.")
            smtp_connection.login(smtp_user, smtp_password)

        smtp_connection.sendmail(mail_from, recipient_email_list,
                                 msg.as_string())
        log.info("Sent email to provided list of recipients")

    except smtplib.SMTPException, e:
        msg = '%r' % e
        log.exception(msg)
        raise MailerException(msg)
msg = MIMEMultipart('mixed')
msg['Reply-To'] = fro
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = "pyICSParser invite" + dtstart
msg['From'] = fro
msg['To'] = ",".join(attendees)
eml_body = "Email body visible in the invite of outlook and outlook.com but not google calendar"

# declare multipart structure and content info
msgAlternative = MIMEMultipart('alternative')
msg.attach(msgAlternative)

#	calendar content info
part_cal = MIMEText(ical, 'calendar;method=REQUEST')
ical_atch = MIMEBase('application/ics', ' ;name="%s"' % ("invite.ics"))
ical_atch.set_payload(ical)
Encoders.encode_base64(ical_atch)
ical_atch.add_header('Content-Disposition',
                     'attachment; filename="%s"' % ("invite.ics"))

#	email content info
part_email = MIMEText(eml_body, "html")
eml_atch = MIMEBase('text/plain', '')
Encoders.encode_base64(eml_atch)
eml_atch.add_header('Content-Transfer-Encoding', "")

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

# send the email calendar invite
mailServer = smtplib.SMTP('engr.orst.edu')
예제 #36
0
def send_mail(sendFrom,
              sendTo,
              subject,
              text,
              files=[],
              sendCc=[],
              sendBcc=[],
              authName=None,
              authPass=None):
    """
    quick and easy utility function to send email from any system
    via a python interface.
    """

    import mimetypes
    import smtplib
    import os

    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email.MIMEText import MIMEText
    from email.Utils import formatdate
    from email import Encoders

    import getpass
    assert type(sendTo) == list
    assert type(sendCc) == list
    assert type(sendBcc) == list
    assert type(files) == list

    addressEmailSuffix = initDefault.EMAIL_SUFFIX

    if '@' not in sendFrom:
        sendFrom += addressEmailSuffix

    for i in range(len(sendTo)):
        if '@' not in sendTo[i]:
            sendTo[i] += addressEmailSuffix

    for i in range(len(sendCc)):
        if '@' not in sendCc[i]:
            sendCc[i] += addressEmailSuffix

    for i in range(len(sendBcc)):
        if '@' not in sendBcc[i]:
            sendBcc[i] += addressEmailSuffix

    msg = MIMEMultipart()
    msg['From'] = sendFrom
    msg['To'] = ', '.join(sendTo)
    if len(sendCc) > 0:
        msg['Cc'] = ', '.join(sendCc)
    if len(sendBcc) > 0:
        msg['Bcc'] = ', '.join(sendBcc)
    msg['Date'] = formatdate(localtime=True)
    msg['Realname'] = getpass.getuser()
    msg['Subject'] = subject

    msg.attach(MIMEText(text))

    # attach files as mime parts
    for f in files:
        if DiskUtils.is_file_exist(f):
            ftxt = f.replace(".log", ".txt")
            mimeType = mimetypes.guess_type(ftxt)[0]
            mimeTuple = ('application', 'octet-stream')

            if mimeType is not None:
                mimeTuple = tuple(mimeType.split('/'))
                part = MIMEBase(mimeTuple[0], mimeTuple[1])
                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)

    log.debug("sending email from %s to %s" % (sendFrom, sendTo))

    smtp = smtplib.SMTP(initDefault.SERVER_EMAIL_NAME)
    if authName is not None and authPass is not None:
        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()
        smtp.login(authName, authPass)
    smtp.sendmail(sendFrom, sendTo + sendCc + sendBcc, msg.as_string())
    smtp.close()
예제 #37
0
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders

fromaddr = "*****@*****.**"
toaddr = "*****@*****.**"

msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "SUBJECT OF THE MAIL"
body = "YOUR MESSAGE HERE"
msg.attach(MIMEText(body, 'plain'))

filename = "Data_backend.txt"
attachment = open("Data_backend.txt", "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

msg.attach(part)

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "lapizamarillo")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
예제 #38
0
    def sendEmail(self, server):
        ''' sendEmail(host_server):
        This module is a simple interface to send emails (with attachments) using the gmail or cern SMTP servers. When calling the module the only thing that needs 
        to be specified is which server is to be used (cern or gmail). Just follow the prompt commands once launched. The "smtplib" is a low-level package interface 
        for the Simple Mail Transfer Protocol (SMTP) protocol. The "email" package assists with parsing (analyzing a sentence into its parts and describe their 
        syntactic roles) and  generating emails.
        '''

        # Import modules here
        import traceback
        import email
        from smtplib import SMTP
        from email.MIMEText import MIMEText
        from email.MIMEMultipart import MIMEMultipart
        from email.MIMEBase import MIMEBase
        from email import encoders
        import mimetypes
        import sys
        import datetime
        import getpass

        # Define SMTP port to use and decide which of the two servers to use
        smtpPort = 587  #or 25
        if server == "cern":
            smtpHost = "smtp.cern.ch"
            emailAddress = "@cern.ch"
            smtpUsername = "******"
        elif server == "gmail":
            smtpHost = "smtp.gmail.com"
            emailAddress = "@gmail.com"
            smtpUsername = "******"
        else:
            self.Cout(
                'ERROR! The server argument %s is invalid. Please select between "cern" and "gmail". Exiting python shell.'
            )
            print __doc__
            sys.exit(1)

        # Get SMTP authorisation details
        self.Cout("Please provide your login credentials for %s to continue:" %
                  (smtpUsername))
        sender = smtpUsername
        smtpPassword = getpass.getpass("\tPassword = "******"Attempting to connect to:\n\thost = %s\n\tport = %s" %
                  (smtpHost, smtpPort))
        connection = SMTP(host=smtpHost, port=smtpPort)
        connection.set_debuglevel(False)  #True
        if smtpUsername is not False:
            connection.ehlo()
            if smtpPort != 25:
                connection.starttls()
                connection.ehlo()
                if smtpUsername and smtpPassword:
                    connection.login(smtpUsername, smtpPassword)
                    self.Cout(
                        "Succesfully logged on to:\n\tusername = %s\n\tpassword = %s"
                        % (smtpUsername, self.obscureString(smtpPassword)))
                else:
                    self.Cout(
                        "Unsuccesfull login. False credentials provided:\n\tusername = %s\n\tpassword = %s"
                        % (smtpUsername, self.obscureString(smtpPassword)))
                    print __doc__
                    sys.exit(1)

        # Get user input regarding email details
        self.Cout("Please provide the email details:")
        recipients = raw_input("\tTo: ")
        Cc = raw_input("\tCc: ")
        Bcc = raw_input("\tBcc (self excluded): ")
        subject = raw_input("\tSubject: ")
        content = raw_input("\tContent: ")
        attachment = raw_input("\tAttachment: ")
        if attachment == "":
            self.Cout("Nothing to attach.")
            bAttach = False
        else:
            self.Cout("Attachment file:\n\t%s" % (attachment))
            bAttach = True

        # Define return value as success == 0,  failure == 1
        returnValue = 1
        # Take care of recipient lists
        if not (hasattr(recipients, "__iter__")):
            recipients = [recipients]
        if not (hasattr(Cc, "__iter__")):
            Cc = [Cc]
        if not (hasattr(Bcc, "__iter__")):
            Bcc = [Bcc]
            Bcc.append(smtpUsername)

        # Define message details, including attachments
        try:
            if bAttach == False:
                text_subtype = 'plain'
                mainMsg = MIMEText(content, text_subtype)
            else:
                mainMsg = MIMEMultipart()
                # Guess the type of a file based on its filename or URL, given by url.
                ctype, encoding = mimetypes.guess_type(attachment)
                print "ctype, encoding = %s, %s" % (ctype, encoding)
                maintype, subtype = ctype.split("/", 1)
                print "maintype, subtype = %s, %s" % (maintype, subtype)

            # The following do not depend on attachment
            mainMsg[
                'From'] = sender  # Some SMTP servers will do this automatically, but not all
            mainMsg['To'] = ", ".join(recipients)
            mainMsg['cc'] = ", ".join(Cc)
            mainMsg['Bcc'] = ", ".join(Bcc)
            mainMsg['Subject'] = subject

            # Send emails body and attachments
            self.Cout("Sending email to %s" % (recipients))
            try:
                if bAttach:
                    mainMsg.attach(subMsg)
                    fp = open(attachment,
                              "rb")  # open attachment in read/binary mode
                    subMsg = MIMEBase(maintype, subtype)
                    subMsg.set_payload(fp.read())
                    fp.close()
                    encoders.encode_base64(subMsg)
                    subMsg.add_header("Content-Disposition",
                                      "attachment",
                                      filename=attachment)
                    mainMsg.attach(MIMEText(content))
                # Connect to server and send complete email
                connection.sendmail(sender, recipients + Cc + Bcc,
                                    mainMsg.as_string())
                returnValue = 0  # (success)
            except Exception, e:
                self.Cout("Got %s %s.\n\tShowing traceback:\n%s" %
                          (type(e), e, traceback.format_exc()))
                returnValue = 1  # (failure)
                print __doc__
            finally:
                self.Cout("Closing connection.")
                connection.close()
예제 #39
0
username = '******'
password = '******'
textfile = 'message.txt'
attachment = 'something.pdf'

msg = MIMEMultipart()

msg['From'] = me
msg['To'] = you
msg['Subject'] = 'The contents of %s' % textfile

fp = open(textfile, 'rb')
msg.attach(MIMEText(fp.read()))
fp.close()

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

msg.attach(email_attachment)


server = smptlib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.ehlo()
server.login(username, password)
server.sendmail(me, [you], msg.as_string())
server.close()
def main():
    print "######################################"
    global bottom_tempc
    global top_tempc
    device = top_temp
    top_tempc = read_temp(device)
    top_tempf = top_tempc * 9.0 / 5.0 + 32.0
    device = bottom_temp
    bottom_tempc = read_temp(device)
    bottom_tempf = bottom_tempc * 9.0 / 5.0 + 32.0
    timenow = datetime.datetime.now()
    time_difference = timenow - starttime
    print "Time since start: ", time_difference
    time_on_in_minutes = int(((timenow - starttime).total_seconds()) / 60)
    time_on = time_on_in_minutes
    print "  TOP Celcius degrees: ", top_tempc, " Farenheit: ", top_tempf
    print "  BOTTOM Celcius degrees: ", bottom_tempc, " Farenheit: ", bottom_tempf
    print "  Time on in minutes: ", time_on
    #SAVE THE STARTING TEMP
    if config.starttemp == 1234567.999:
        config.starttemp = top_tempc

# email that kiln has started, notify of desired max
    if config.startmailsent == 0:
        config.startmailsent = 1
        toaddrs = config.recipients
        msg = MIMEMultipart()
        msg['From'] = config.fromaddr
        msg['Subject'] = "KILN MAIL, started firing."
        body = "\n".join([
            "Kiln just started..",
            " "
            "...starting temperature: %s\xb0C" % config.starttemp,
            "...desired maximum temperature: %s\xb0C" % config.desiredmax, " ",
            " ", "scriptfile attached. ", " ", " ", " "
        ])
        msg.attach(MIMEText(body, 'plain'))
        attachment = open(scriptnamewithpath, "rb")

        part = MIMEBase('application', 'octet-stream')
        part.set_payload((attachment).read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition',
                        "attachment; filename= %s" % scriptname)
        msg.attach(part)

        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(config.fromaddr, config.gmailpassword)
        text = msg.as_string()
        server.sendmail(config.fromaddr, toaddrs, text)
        server.quit()

    #SAVE THE MAX TEMP
    if config.maxtoptemp < top_tempc:
        config.maxtoptemp = top_tempc
    if config.maxbottomtemp < bottom_tempc:
        config.maxbottomtemp = bottom_tempc

    # SAVE THE TIME THE MAX IS REACHED
    if top_tempc > config.desiredmax and config.timemaxreached is None:
        config.timemaxreached = datetime.datetime.now()

    print "  Starting temp in Celcius: ", config.starttemp
    print "  MAX measured temp in Celcius: ", config.maxtoptemp
    if config.timemaxreached is not None:
        print "  Time max reached: ", config.timemaxreached
        timenow2 = datetime.datetime.now()
        time_diff = timenow2 - config.timemaxreached
        print "Time since max: ", time_diff
        config.minutessincemax = int(
            ((timenow2 - config.timemaxreached).total_seconds()) / 60)

    # LOG ONLY EVERY MINUTE
    #if time_on_in_minutes != config.lastloggedminute:
    config.lastloggedminute = time_on_in_minutes
    logthis = str(time_on) + "," + str(time_difference) + "," + str(
        top_tempc) + "," + str(bottom_tempc) + "," + str(
            config.holdc) + "," + str(config.starttemp) + "," + str(
                config.maxtoptemp) + "," + str(
                    config.maxbottomtemp) + "," + str(runtime)
    logger.info(logthis)

    # FIRE FIRE FIRE!
    if time_on < 30:
        config.holdc = 40
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 30 and time_on < 60 and config.maxtoptemp < config.desiredmax:
        config.holdc = 50
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 60 and time_on < 90 and config.maxtoptemp < config.desiredmax:
        config.holdc = 80
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 90 and time_on < 120 and config.maxtoptemp < config.desiredmax:
        config.holdc = 100
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 120 and time_on < 126 and config.maxtoptemp < config.desiredmax:
        config.holdc = 140
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 126 and time_on < 132 and config.maxtoptemp < config.desiredmax:
        config.holdc = 170
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 132 and time_on < 147 and config.maxtoptemp < config.desiredmax:
        config.holdc = 183
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 147 and time_on < 162 and config.maxtoptemp < config.desiredmax:
        config.holdc = 208
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 162 and time_on < 177 and config.maxtoptemp < config.desiredmax:
        config.holdc = 250
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 177 and time_on < 192 and config.maxtoptemp < config.desiredmax:
        config.holdc = 293
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 192 and time_on < 207 and config.maxtoptemp < config.desiredmax:
        config.holdc = 340
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 207 and time_on < 222 and config.maxtoptemp < config.desiredmax:
        config.holdc = 387
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 222 and time_on < 237 and config.maxtoptemp < config.desiredmax:
        config.holdc = 420
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 237 and time_on < 244 and config.maxtoptemp < config.desiredmax:
        config.holdc = 450
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 244 and time_on < 252 and config.maxtoptemp < config.desiredmax:
        config.holdc = 481
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 252 and time_on < 267 and config.maxtoptemp < config.desiredmax:
        config.holdc = 530
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 267 and time_on < 275 and config.maxtoptemp < config.desiredmax:
        config.holdc = 550
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 275 and time_on < 282 and config.maxtoptemp < config.desiredmax:
        config.holdc = 575
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 282 and time_on < 298 and config.maxtoptemp < config.desiredmax:
        config.holdc = 625
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 298 and time_on < 312 and config.maxtoptemp < config.desiredmax:
        config.holdc = 669
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 312 and time_on < 327 and config.maxtoptemp < config.desiredmax:
        config.holdc = 716
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 327 and time_on < 342 and config.maxtoptemp < config.desiredmax:
        config.holdc = 763
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 342 and time_on < 357 and config.maxtoptemp < config.desiredmax:
        config.holdc = 812
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 357 and time_on < 362 and config.maxtoptemp < config.desiredmax:
        config.holdc = 830
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 362 and time_on < 372 and config.maxtoptemp < config.desiredmax:
        config.holdc = 859
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 372 and time_on < 387 and config.maxtoptemp < config.desiredmax:
        config.holdc = 905
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 387 and time_on < 402 and config.maxtoptemp < config.desiredmax:
        config.holdc = 953
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 402 and time_on < 412 and config.maxtoptemp < config.desiredmax:
        config.holdc = 986
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 412 and time_on < 422 and config.maxtoptemp < config.desiredmax:
        config.holdc = 1016
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 422 and time_on < 432 and config.maxtoptemp < config.desiredmax:
        config.holdc = 1050
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 432 and time_on < 442 and config.maxtoptemp < config.desiredmax:
        config.holdc = 1080
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 442 and time_on < 452 and config.maxtoptemp < config.desiredmax:
        config.holdc = 1090
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 452 and time_on < 462 and config.maxtoptemp < config.desiredmax:
        config.holdc = 1110
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 462 and time_on < 472 and config.maxtoptemp < config.desiredmax:
        config.holdc = 11125
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 472 and time_on < 482 and config.maxtoptemp < config.desiredmax:
        config.holdc = 1135
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 482 and time_on < 492 and config.maxtoptemp < config.desiredmax:
        config.holdc = 1145
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    elif time_on >= 492 and time_on < 502 and config.maxtoptemp < config.desiredmax:
        config.holdc = 1148
        holdhere = config.holdc
        hold(holdhere, top_tempc)

# ATTAIN MAX (1150) - coyote constellation
    elif time_on >= 502 and time_on < 802 and config.maxtoptemp < config.desiredmax:
        config.holdc = 1150
        holdhere = config.holdc
        hold(holdhere, top_tempc)
    # MAX ATTAINED, HOLD and RAMP DOWN
    elif config.minutessincemax < 15 and config.maxtoptemp >= config.desiredmax:
        config.holdc = config.desiredmax
        holdhere = config.holdc
        print "Holding at max for 15 minutes: ", config.holdc
        hold(holdhere, top_tempc)
        # email that kiln has reached max temp, attach log so far
        if config.donemailsent == 0:
            config.donemailsent = 1
            toaddrs = config.recipients
            msg = MIMEMultipart()
            msg['From'] = config.fromaddr
            msg['Subject'] = "KILN MAIL, max reached."
            body = "\n".join([
                "Kiln just reached Maximum temperature!!!!!",
                " "
                "...maximum top temperature: %s\xb0C" % config.maxtoptemp,
                "...maximum bottom temperature: %s\xb0C" %
                config.maxbottomtemp,
                "...Total relay runtime: %s" % runtime,
                "...Time maximum temp was reached: %s" % config.timemaxreached,
                " ", " ", "Logfile attached. ", " ",
                "logfile format: MINUTES,CURRENT_TEMP_TOP, CURRENT_TEMP_BOTTOM, DESIRED TEMP, START TEMP, MAX TOP TEMP, MAX BOTTOM TEMP, RELAY ON TIME",
                " ", " ", " "
            ])
            msg.attach(MIMEText(body, 'plain'))
            attachment = open(filenamewithpath, "rb")

            part = MIMEBase('application', 'octet-stream')
            part.set_payload((attachment).read())
            encoders.encode_base64(part)
            part.add_header('Content-Disposition',
                            "attachment; filename= %s" % config.logfilename)
            msg.attach(part)

            server = smtplib.SMTP('smtp.gmail.com', 587)
            server.starttls()
            server.login(config.fromaddr, config.gmailpassword)
            text = msg.as_string()
            server.sendmail(config.fromaddr, toaddrs, text)
            server.quit()

    elif config.minutessincemax >= 15 and config.minutessincemax < 36 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 1124
        holdhere = config.holdc
        print "Holding at 1124 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 36 and config.minutessincemax < 46 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 1114
        holdhere = config.holdc
        print "Holding at 1114 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 46 and config.minutessincemax < 56 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 1104
        holdhere = config.holdc
        print "Holding at 1104 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 56 and config.minutessincemax < 66 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 1094
        holdhere = config.holdc
        print "Holding at 1094 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 66 and config.minutessincemax < 76 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 1084
        holdhere = config.holdc
        print "Holding at 1084 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 76 and config.minutessincemax < 86 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 1074
        holdhere = config.holdc
        print "Holding at 1074 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 86 and config.minutessincemax < 96 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 1064
        holdhere = config.holdc
        print "Holding at 1064 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 96 and config.minutessincemax < 106 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 1054
        holdhere = config.holdc
        print "Holding at 1054 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 106 and config.minutessincemax < 116 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 1044
        holdhere = config.holdc
        print "Holding at 1044 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 116 and config.minutessincemax < 126 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 1034
        holdhere = config.holdc
        print "Holding at 1034 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 126 and config.minutessincemax < 136 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 1024
        holdhere = config.holdc
        print "Holding at 1024 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 136 and config.minutessincemax < 146 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 1014
        holdhere = config.holdc
        print "Holding at 1014 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 146 and config.minutessincemax < 156 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 1004
        holdhere = config.holdc
        print "Holding at 1004 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 156 and config.minutessincemax < 166 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 994
        holdhere = config.holdc
        print "Holding at 994 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 166 and config.minutessincemax < 176 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 984
        holdhere = config.holdc
        print "Holding at 984 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 176 and config.minutessincemax < 186 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 974
        holdhere = config.holdc
        print "Holding at 974 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 186 and config.minutessincemax < 196 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 964
        holdhere = config.holdc
        print "Holding at 964 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 196 and config.minutessincemax < 206 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 954
        holdhere = config.holdc
        print "Holding at 954 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 206 and config.minutessincemax < 216 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 944
        holdhere = config.holdc
        print "Holding at 944 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 216 and config.minutessincemax < 226 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 934
        holdhere = config.holdc
        print "Holding at 934 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 226 and config.minutessincemax < 236 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 924
        holdhere = config.holdc
        print "Holding at 924 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 236 and config.minutessincemax < 246 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 914
        holdhere = config.holdc
        print "Holding at 914 for 10 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 246 and config.minutessincemax < 276 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 884
        holdhere = config.holdc
        print "Holding at 884 for 30 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 276 and config.minutessincemax < 306 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 854
        holdhere = config.holdc
        print "Holding at 854 for 30 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 306 and config.minutessincemax < 336 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 824
        holdhere = config.holdc
        print "Holding at 824 for 30 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 336 and config.minutessincemax < 366 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 794
        holdhere = config.holdc
        print "Holding at 794 for 30 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    elif config.minutessincemax >= 366 and config.minutessincemax < 396 and config.maxtoptemp >= config.desiredmax:
        config.holdc = 760
        holdhere = config.holdc
        print "Holding at 760 for 30 minutes: ", config.holdc
        hold(holdhere, top_tempc)
    else:
        config.holdc = 1
        holdhere = config.holdc
        print "TURNED OFF, Holding at: ", config.holdc
        hold(holdhere, top_tempc)
        GPIO.output(26, 0)

        #email that the kiln is off
        fromaddr = config.fromaddr
        recipients = config.recipients
        toaddrs = config.recipients
        msg = MIMEMultipart()
        msg['From'] = config.fromaddr
        msg['Subject'] = "KILN MAIL, kiln is off."

        body = "\n".join([
            "Maximum temperature reached, KILN IS OFF and cooling now, just a few more hours till Christmas!",
            " "
            "...maximum top temperature: %s\xb0C" % config.maxtoptemp,
            "...maximum bottom temperature: %s\xb0C" % config.maxbottomtemp,
            "...Total relay runtime: %s" % runtime,
            "...Time maximum temp was reached: %s" % config.timemaxreached,
            " ", " ", "Logfile and scriptfile attached. ", " ",
            "logfile format: MINUTES,CURRENT_TEMP_TOP, CURRENT_TEMP_BOTTOM, DESIRED TEMP, START TEMP, MAX TOP TEMP, MAX BOTTOM TEMP, RELAY ON TIME",
            " ", " ", " "
        ])

        msg.attach(MIMEText(body, 'plain'))
        attachment = open(filenamewithpath, "rb")

        part = MIMEBase('application', 'octet-stream')
        part.set_payload((attachment).read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition',
                        "attachment; filename= %s" % config.logfilename)
        msg.attach(part)

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

        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(config.fromaddr, config.gmailpassword)
        text = msg.as_string()
        server.sendmail(config.fromaddr, toaddrs, text)
        server.quit()
        quit()
예제 #41
0
import smtplib
import sys

from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Encoders

#toaddr = "*****@*****.**"
toaddr = "*****@*****.**"
#toaddr = "*****@*****.**"
fromaddr = "*****@*****.**"
attach = sys.argv[1]
subject = "www"

msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = subject

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

smtp = smtplib.SMTP("localhost")
smtp.sendmail(fromaddr, toaddr, msg.as_string() )
smtp.close()
예제 #42
0
    def sendmail(self,
                 email_addr,
                 type,
                 subject,
                 content,
                 file=None,
                 filename=None):
        """
        Send an email message. It creates a plain text or mime message
        depending on the request's type, set headers and content and
        finally send it.

        :param email_addr (str): email address of the recipient.
        :param type (str): type of message to create (help or mime).
        :param subject (str): subject of the message.
        :param content (str): content of the message.
        :param file (str): path to file to be attached (optional).
        :param filename (str): attachment's filename (optional).

        :return: deferred whose callback/errback will handle the SMTP
        execution details.
        """

        # Help requests are just text. Accounts requests attach a .ovpn
        # file, so they are MIME
        if type == "plain":
            log.debug("SMTP:: Creating plain text email")
            message = MIMEText(content)
        elif type == "mime":
            log.debug("SMTP:: Creating MIME email")
            message = MIMEMultipart()
            message.set_charset("utf-8")

        message['Subject'] = subject
        message['From'] = self.username
        message['To'] = email_addr

        if type == "mime":
            attach_content = MIMEText(content, 'plain')
            message.attach(attach_content)

            # Attach profile
            profile_attachment = MIMEBase('application', "octet-stream")
            profile_attachment.set_payload(open(file, "rb").read())
            Encoders.encode_base64(profile_attachment)
            profile_attachment.add_header("Content-Disposition",
                                          "attachment",
                                          filename=filename)
            message.attach(profile_attachment)

            # Attach mobile tutorial
            mobile_attachment = MIMEBase('application', "octet-stream")
            mobile_attachment.set_payload(
                open(self.path['mobile_tutorial'], "rb").read())
            Encoders.encode_base64(mobile_attachment)
            mobile_attachment.add_header(
                "Content-Disposition",
                "attachment",
                filename="EVPN_tutorial_mobile_devices.pdf")
            message.attach(mobile_attachment)

        # Create a list of email address so twisted.mail.smtp.sendmail
        # knows how to handle it
        if "," in email_addr:
            log.debug("SMTP:: Sending email to multiple recipients.")
            email_addr = email_addr.split(",")

        log.debug("SMTP:: Calling asynchronous sendmail.")
        return sendmail(self.host,
                        self.username,
                        email_addr,
                        message,
                        port=self.port,
                        username=self.username,
                        password=self.password,
                        requireAuthentication=True,
                        requireTransportSecurity=True).addCallback(
                            self.cb_smtp).addErrback(self.eb_smtp)
예제 #43
0
                        help='Email text content')
    parser.add_argument('-f', '--file', type=str, default=None, dest='sendfile',
                        help='Email file, attachment.')
    
    return parser.parse_args()

if __name__ == '__main__':
  args = parse_args()

  msg = MIMEMultipart()
  msg['Subject'] = 'This is an spam mail'
  msg['From'] = args.send_from
  msg['To'] = args.send_to

  if args.sendfile is not None:
    part = MIMEBase('application', "octet-stream")
    part.set_payload(open(args.sendfile, "rb").read())
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename=args.sendfile')
    msg.attach(part)

  if args.textfile is not None:
    fp = open(args.textfile, 'rb')
    text = fp.read()
    part = MIMEText(text, 'plain')
    msg.attach(part)
    fp.close()

  server = smtplib.SMTP('localhost')
  server.sendmail(args.send_from, args.send_to, msg.as_string())
예제 #44
0
#### Emailing details #####################################
fromaddr = "*****@*****.**"
toaddr = ['*****@*****.**', '*****@*****.**', '*****@*****.**']
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = ", ".join(toaddr)
msg['Subject'] = "Weekly Sales - " + datepart

body = "FYI,find attachment!"

msg.attach(MIMEText(body, 'plain'))

filename = "Weekly_Sales - " + datepart + ".csv"
attachment = open("/Users/ankitkumar/" + filename, "rb")

part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

msg.attach(part)

### send email############################################
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "apppassword")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
예제 #45
0
def SendEmail(RecipientAddress):

    UserName, Password = UserDetails.ObtainUserCredentials()
    ExcelFiles, Subject = CreateSubjectLine()

    if (ExcelFiles == [] or Subject == ''):
        print 'No Excel Files Found'
        return False

    print 'Subject Line Generated'

    msg = MIMEMultipart()

    msg['From'] = UserName
    msg['To'] = ",".join(RecipientAddress)
    msg['Subject'] = Subject

    print 'Recipient Address List Ready'

    body = " "

    msg.attach(MIMEText(body, 'plain'))

    for file in ExcelFiles:
        attachment = open(file, "rb")

        part = MIMEBase('application', 'octet-stream')
        part.set_payload((attachment).read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition',
                        "attachment; filename= %s" % file)

        msg.attach(part)
        attachment.close()

    Data = msg.as_string()

    print 'Attachment Ready'

    try:
        server = smtplib.SMTP('smtp.rediffmail.com', 25)
        server.starttls()
        server.ehlo()
        server.esmtp_features["auth"] = "LOGIN PLAIN"
        server.login(UserName, Password)
        print 'User Credentials Authenticated'
        Details = server.sendmail(UserName, RecipientAddress, Data)
        server.quit()

    except smtplib.SMTPAuthenticationError:
        print 'User Name / Password Incorrect. Please check details again'
    except smtplib.SMTPSenderRefused:
        print 'Sender Address is Incorrect'
    except smtplib.SMTPRecipientsRefused:
        print 'Recipient Address is Incorrect'
    except smtplib.SMTPDataError:
        print 'Message Creation Incorrect'
    except smtplib.SMTPConnectError:
        print 'Connection to the Server refused'
    except smtplib.SMTPException:
        print 'SMTP Error'
    except:
        print 'Error Except SMTP But While Sending E Mail'

    if (Details == {}):
        print 'Mail Sent Succesfully'

        CreateFolder('Sent')
        for file in ExcelFiles:
            shutil.copy2(file, 'Sent')
            UserDetails.deleteFile(file)

        print 'File Saved To Sent Folder'

        return True

    else:
        print 'Something Went Wrong While Sending The Mails'
        print Details
        return False
    for j,c in enumerate(cabeceras):
        if rc[j]:
            nHoja.write(nFila+i, j, rc[j])
    f.write(u"Linea añadida: " + str(i) + '\r\n')



f.write("Antes de guardar Excel "+ '\r\n')
nExcel.save(cadArchivo)
f.write("Guardando Excel "+ '\r\n')


archExcel = open(cadArchivo,'rb')
#adjunto = MIMEBase('multipart', 'encrypted')
adjunto = MIMEBase('application', "octet-stream")
adjunto.set_payload(archExcel.read())
archExcel.close()
encoders.encode_base64(adjunto)
adjunto.add_header('Content-Disposition', 'attachment', filename = cadTiempo + "_" + nombreExcel + ".xls")
mail.attach(adjunto)


try:
    servidor = smtplib.SMTP(servidorSMTP, 587)
    servidor.set_debuglevel(1)
    servidor.ehlo()
    servidor.starttls()
    servidor.ehlo()
    #servidor.esmtp_features['auth'] = 'LOGIN PLAIN'
    servidor.login(usuarioSMTP, passSMTP)
    servidor.sendmail(mail['From'], mail['To'], mail.as_string())
예제 #47
0
파일: watch.py 프로젝트: nkern/capo
            emailmsg += 'Too long between obs --> morph pings (%.1f min)\n\n' % (
                diffLast)
        else:
            emailmsg += 'Watchdog file %s does not exist' % (watchFile)
        from_addr = '*****@*****.**'
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login('*****@*****.**', '')

        msg = MIMEMultipart()
        msg['Subject'] = 'Watchdog bites'
        msg['From'] = '*****@*****.**'
        msg['To'] = cataddr(emails)
        msg.attach(MIMEText(emailmsg))
        part = MIMEBase('application', "octet-string")
        part.set_payload(open(watchFile, "rb").read())
        Encoders.encode_base64(part)
        part.add_header(
            'Content-disposition',
            'attachment; filename="%s"' % os.path.basename(watchFile))
        msg.attach(part)
        server.sendmail(msg['From'], emails, msg.as_string())
        server.quit()
else:
    ##----Get bandwidth info----##
    b = WatchAlert.Bandwidth('watchBand.dat', bandTransmitSize=150000000)
    b.getbw()
    b.addEntry()
예제 #48
0
파일: diffreport.py 프로젝트: trawor/gity
    from email import Encoders
    import os
except Exception, e:
    sys.stderr.write(str(e))
    exit(84)

try:
    exit(0)
    diff_file = diff_report_file()
    if not os.path.exists(diff_file): exit(0)
    msg = MIMEMultipart()
    msg['From'] = "*****@*****.**"
    msg['To'] = "*****@*****.**"
    msg['Subject'] = "GityBot: Diff Error Report"
    msg.attach(MIMEText(" "))
    part = MIMEBase('application', 'octet-stream')
    part.set_payload(open(diff_file, 'rb').read())
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition',
                    'attachment; filename="diff_report.html"')
    msg.attach(part)
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login('*****@*****.**', '')
    mailServer.sendmail('*****@*****.**', '*****@*****.**',
                        msg.as_string())
    mailServer.close()
except Exception, e:
    pass
예제 #49
0
 (encrypted_body, passphrase) = encrypt_body("/tmp/mail", sender)
 (encrypt_subject, passphrase) = encrypt_body("/tmp/subj", sender,
                                              passphrase)
 #Start making message
 msg = MIMEMultipart()
 msg["To"] = to
 msg["From"] = sender
 msg["Subject"] = encrypt_subject
 #Encrypt the password
 encrypt_pass(passphrase, to)
 #Attach the body
 msg.attach(MIMEText(encrypted_body, 'plain'))
 #The attachments are application octet-stream
 #The attachments for the password
 file_part = MIMEBase('application', "octet-stream")
 file_part.set_payload(open("/tmp/epass", "rb").read())
 encoders.encode_base64(file_part)
 file_part.add_header('Content-Disposition',
                      'attachment; filename="%s"' % "passphrase")
 msg.attach(file_part)
 #The attachments  for the digest
 file_part = MIMEBase('application', "octet-stream")
 file_part.set_payload(open("/tmp/digest", "rb").read())
 encoders.encode_base64(file_part)
 file_part.add_header('Content-Disposition',
                      'attachment; filename="%s"' % "digest")
 msg.attach(file_part)
 #Set up the smtp server
 smtpserver = set_up_smtp_link(sender)
 #Send the mail
 smtpserver.sendmail(sender, to, msg.as_string())
예제 #50
0
if namefilter is not None:
    namefilterencoded = namefilter.replace('*', '_').replace('?', '_')
    outfileName = 'soxReport-%s-%s.csv' % (cluster['name'], namefilterencoded)
    subject = 'Cohesity Sox Report (%s) %s' % (cluster['name'],
                                               namefilterencoded)
else:
    outfileName = 'soxReport-%s.csv' % cluster['name']
    subject = 'Cohesity Sox Report (%s)' % cluster['name']

print('saving report as %s' % outfileName)
f = codecs.open(outfileName, 'w', 'utf-8')
f.write(csv)
f.close()

# email report
if mailserver is not None:
    print('Sending report to %s...' % ', '.join(sendto))
    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From'] = sendfrom
    msg['To'] = ','.join(sendto)
    part = MIMEBase('application', "octet-stream")
    part.set_payload(open(outfileName, "rb").read())
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition',
                    'attachment; filename="%s"' % outfileName)
    msg.attach(part)
    smtpserver = smtplib.SMTP(mailserver, mailport)
    smtpserver.sendmail(sendfrom, sendto, msg.as_string())
    smtpserver.quit()
예제 #51
0
def gencsv(out):
	
	#new_data=str(out.replace("msg: all out "," ")) 
	#second op
	#new_data=str(out) uncomment if below command do not work
	new_data=re.sub("msg: all out","",str(out)) #put \" before  all, comment if not wrk
	#print(new_data)
	register=new_data.split("-")

	#-------------------clear sample.csv to empy file
	sample=open("sample.csv", "w")
	sample.write("")
	sample.close()
	
	#----------extract info block 
	try:
		with open("sample.csv", "a") as fl:
			data=csv.writer(fl, delimiter=",")
			data.writerow(["IP","HOSTNAME","OS VERSION","CPU USAGE","MEMORY USAGE","ANSIBLE VERSION","NGINX STATUS","DB STATUS"])
			print("Output:\n\tPlease check sample.csv file in your current dir\n")
			for rowReg in register:
				dt=open("raw-data.csv", "a")     
				dt.write(str(rowReg).replace(" ",""))
				dt.close()
			with open("raw-data.csv", "r") as fl:
				csv_data=csv.reader(fl,delimiter=",")
                        	for row in csv_data:
					data.writerow([str(row[0]).replace("Ip",""),str(row[1]).replace("hostnames",""),str(row[2]).replace("os_version","").replace(" ","No"),str(row[3]).replace("cpu",""),str(row[4]).replace("mem",""),str(row[5]).replace("ansible",""),str(row[6]).replace("nginx",""),str(row[7]).replace("db","")])
					#print([str(row[0]).replace("Ip",""),str(row[1]).replace("hostnames",""),str(row[2]).replace("os_version",""),str(row[3]).replace("cpu",""),str(row[4]).replace("mem",""),str(row[5]).replace("ansible",""),str(row[6]).replace("nginx",""),str(row[7]).replace("db","")])
	
	finally:
		subprocess.Popen("rm -rf raw-data.csv", shell=True, stdout=subprocess.PIPE) #remove temporary file 
	

	#replacing NaN value with No
        rData=pd.read_csv("sample.csv", index_col="IP")
        rData=rData.fillna("NO")
	rData["DB STATUS"].replace("\.0", "", regex=True, inplace=True)
	print(rData)
        rData.to_csv("sample.csv", sep=",", encoding="utf-8")
        
        
	#sed command -uncomment next two command if re.sub above do not work
	#subprocess.Popen("sed 's/msg:\"allout//' sample.csv > sample1.csv", shell=True, stdout=subprocess.PIPE) #remove msg:"allout 
	#subprocess.Popen("mv sample1.csv sample.csv", shell=True, stdout=subprocess.PIPE) 
	
	#--sending mail
	msg = MIMEMultipart()
	msg["From"] = "*****@*****.**"
	msg["To"] = "*****@*****.**"
	msg["Subject"] = "Report Ansible."

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

	part.add_header('Content-Disposition', 'attachment', filename="sample.csv")

	msg.attach(part)

	p =subprocess.Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=subprocess.PIPE)
	p.communicate(msg.as_string())
예제 #52
0
 def add_objet(self, _path):
     part = MIMEBase('application', 'octet_stream')
     part.set_payload(open(_path, 'rb').read())
     Encoders.encode_base64(part)
     part.add_header('Content-Disposition', 'attachment; filename=' + _path)
     (self.m).attach(part)
예제 #53
0
def bot():
    global args
    global base_path

    # -s
    HOST = "irc.freenode.net"
    if (args.server):
        HOST = args.server
# -p
    PORT = 6667
    if (args.port):
        PORT = args.port
# -n
    NICK = "IRC_Bot"
    if (args.nick):
        NICK = args.nick
# -i
    IDENT = "bot"
    if (args.ident):
        IDENT = args.ident
# -r
    REALNAME = "IRC Bot"
    if (args.real):
        REALNAME = args.real


# -c
    CHANNEL = "irclib"
    if (args.channel):
        CHANNEL = args.channel

    #server connect
    IRCsocket = socket.socket()
    IRCsocket.connect((HOST, PORT))
    IRCsocket.send("NICK %s\r\n" % NICK)
    IRCsocket.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))
    IRCsocket.send("JOIN #%s\r\n" % CHANNEL)

    database = os.path.dirname(base_path) + "log.db"
    db = use_plugin(args.plugin, os.path.dirname(base_path))

    if not isfile(database):
        db.create(database)

    buffer = ""
    online = set()
    while 1:
        buffer = buffer + IRCsocket.recv(1024)
        irc = string.split(buffer, "\n")
        buffer = irc.pop()

        for msg in irc:
            msg = string.rstrip(msg)
            msg = string.split(msg)

            print msg

            if (msg[0] == "PING"):
                IRCsocket.send("PONG %s\r\n" % msg[1])

            elif ((msg[1] == "PRIVMSG") & (msg[2] == NICK)):
                db.add(database, msg[1], msg[0].split("!")[0][1:],
                       " ".join(msg[3:]))

                if (msg[3][1:] == "mail"):
                    if args.m_address:
                        if args.m_server:
                            if len(msg) > 3:
                                mail = MIMEMultipart()
                                mail["From"] = args.m_address
                                mail["To"] = msg[4]
                                mail["Subject"] = "IRC Log"
                                mail['Date'] = formatdate(localtime=True)

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

                                server = smtplib.SMTP(args.m_server)
                                if args.m_username:
                                    if args.m_password:
                                        server.login(args.m_username,
                                                     args.m_password)

                                try:
                                    failed = server.sendmail(
                                        args.m_address, msg[4],
                                        mail.as_string())
                                    server.close()
                                except Exception, e:
                                    errorMsg = "Unable to send email. Error: %s" % str(
                                        e)

                elif (msg[3][1:] == "when"):
                    if len(msg) > 3:
                        if msg[4] in online:
                            IRCsocket.send("PRIVMSG %s :%s is now online\r\n" %
                                           (msg[0].split("!")[0][1:], msg[4]))
                        else:
                            IRCsocket.send(
                                "PRIVMSG %s :%s was last seen %s\r\n" %
                                (msg[0].split("!")[0][1:], msg[4],
                                 db.seen(database, msg[4])))

            elif (msg[1] == "JOIN"):
                db.add(database, msg[1], msg[0].split("!")[0][1:], msg[2])
                online.add(msg[0].split("!")[0][1:])
            elif (msg[1] == "PART"):
                db.add(database, msg[1], msg[0].split("!")[0][1:], msg[2])
                online.discard(msg[0].split("!")[0][1:])
예제 #54
0
    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': '******'.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)
예제 #55
0
def send_mail(send_from,
              send_to,
              subject,
              text,
              files=None,
              data_attachments=None,
              server="smtp.office365.com",
              port=587,
              tls=True,
              html=False,
              images=None,
              username=None,
              password=None,
              config_file=None,
              config=None):

    if files is None:
        files = []

    if images is None:
        images = []

    if data_attachments is None:
        data_attachments = []

    if config_file is not None:
        config = ConfigParser.ConfigParser()
        config.read(config_file)

    if config is not None:
        server = config.get('smtp', 'server')
        port = config.get('smtp', 'port')
        tls = config.get('smtp', 'tls').lower() in ('true', 'yes', 'y')
        username = config.get('smtp', 'username')
        password = config.get('smtp', 'password')

    msg = MIMEMultipart('related')
    msg['From'] = send_from
    msg['To'] = send_to if isinstance(send_to,
                                      basestring) else COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(MIMEText(text, 'html' if html else 'plain'))

    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)

    for f in data_attachments:
        part = MIMEBase('application', "octet-stream")
        part.set_payload(f['data'])
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition',
                        'attachment; filename="%s"' % f['filename'])
        msg.attach(part)

    for (n, i) in enumerate(images):
        fp = open(i, 'rb')
        msgImage = MIMEImage(fp.read())
        fp.close()
        msgImage.add_header('Content-ID', '<image{0}>'.format(str(n + 1)))
        msg.attach(msgImage)

    smtp = smtplib.SMTP(server, int(port))
    if tls:
        smtp.starttls()

    if username is not None:
        smtp.login(username, password)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
예제 #56
0
os.remove('C:\\Users\\Administrator\\Desktop\\巡检\\%s巡检比较.log'%today)
os.remove('C:\\Users\\Administrator\\Desktop\\巡检\\%s运行服务比较.log'%today)
#start to send email

#email seting
mail_to = ['收件箱1','收件箱2']
mail_from = '发件邮箱'
email_login_user = '******'
email_login_pass = '******'
mail_body = '%s'%today
subject = '%s巡检.zip'%today
msg=MIMEMultipart()
body=MIMEText(mail_body)
msg.attach(body)
part = MIMEBase('application', 'octet-stream')
part.set_payload(open('C:\\Users\\Administrator\\Desktop\\巡检\\%s巡检.zip'%today,'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename="%s巡检.zip"%today)
msg.attach(part)
msg['Subject']='这是%s的巡检文件'%today
msg['From']=mail_from
msg['To']=';'.join(mail_to)
#send emails three times
try:
    smtp=smtplib.SMTP()
    smtp.connect('smtp.163.com')
    smtp.login(email_login_user,email_login_pass)
    smtp.sendmail(mail_from,mail_to,msg.as_string())
    smtp.quit()
except:
    try:
예제 #57
0
def mailSend(recipient, subject, body, files):
    ###### To get the username automatically from the computer
    username = getpass.getuser()
    accountantEmail = str(keyring.get_password('coffee', 'email'))
    username = str(keyring.get_password('coffee', 'username'))
    password = str(keyring.get_password('coffee', 'password'))
    if username == 'None':
        username = str(
            raw_input("Please insert your logging name for the mail server: "))
        keyring.set_password('coffee', "username", username)
    if username == 'None':
        username = str(
            raw_input("Please insert your logging name for the mail server: "))
        keyring.set_password('coffee', "username", username)
    if str(password) == 'None':
        password = getpass.getpass(
            "Please insert your mail server password. It will be stored in your keyring:"
        )
        keyring.set_password('coffee', "password", password)

    ###### To get the first and sir name of sender automatically from the computer
#  MyName = getent.passwd(username).gecos[0:len(getent.passwd(username).gecos)-3]
###### The sender name of desire
    MyName = "Ti Coffee Team"
    ###### email domail
    domain = "ti.rwth-aachen.de"
    sender = username + "@" + domain
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = MyName + " <" + sender + ">"
    if recipient == "FFTIEmail":
        recipient = accountantEmail
    msg['To'] = recipient
    #msg.attach( MIMEText(body) )
    msg.attach(MIMEText(body.encode('utf-8'), 'plain', 'utf-8'))

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


#  s = smtplib.SMTP("mail.ti.rwth-aachen.de:25")
    s = smtplib.SMTP("mail.ti.rwth-aachen.de:587")
    s.ehlo()
    s.starttls()
    s.login(username, password)
    try:
        if subject != "test":
            s.sendmail(sender, recipient, msg.as_string())
    except:
        raw_input("Email was not sent to " + recipient +
                  ". Please check the email address!")
    s.quit()
예제 #58
0
    msg['To'] = toaddr
    msg['Subject'] = "End of {}".format(script_name)

    body = """Dear Felipe,
    the script {} is done.
    A review of the process can be seen in the following attachments.

    Best,
    Nara""".format(script_name)
    msg.attach(MIMEText(body, 'plain'))

    filename1 = "RNNLM_step.txt"
    attachment1 = open(cwd + '/' + filename1, "rb")

    part1 = MIMEBase('application', 'octet-stream')
    part1.set_payload((attachment1).read())
    encoders.encode_base64(part1)
    part1.add_header('Content-Disposition',
                     "attachment; filename= %s" % filename1)

    msg.attach(part1)

    filename2 = "RNNLM_step_pp.png"
    attachment2 = open(cwd + '/' + filename2, "rb")

    part2 = MIMEBase('application', 'octet-stream')
    part2.set_payload((attachment2).read())
    encoders.encode_base64(part2)
    part2.add_header('Content-Disposition',
                     "attachment; filename= %s" % filename2)
예제 #59
0
def send_mail(to,
              subject,
              text,
              attachments=[],
              cc=[],
              bcc=[],
              smtphost="",
              fromaddr=""):

    if sys.version_info[0] == 2:
        from email.MIMEMultipart import MIMEMultipart
        from email.MIMEBase import MIMEBase
        from email.MIMEText import MIMEText
        from email.Utils import COMMASPACE, formatdate
        from email import Encoders
    else:
        from email.mime.multipart import MIMEMultipart
        from email.mime.base import MIMEBase
        from email.mime.text import MIMEText
        from email.utils import COMMASPACE, formatdate
        from email import encoders as Encoders
    from string import Template
    import socket
    import smtplib

    if not isinstance(to, list):
        print("the 'to' parameter needs to be a list")
        return False
    if len(to) == 0:
        print("no 'to' email addresses")
        return False

    myhost = socket.getfqdn()

    if smtphost == '':
        smtphost = get_mx_from_email_or_fqdn(myhost)
    if not smtphost:
        sys.stderr.write('could not determine smtp mail host !\n')

    if fromaddr == '':
        fromaddr = os.path.basename(__file__) + '-no-reply@' + \
           '.'.join(myhost.split(".")[-2:]) #extract domain from host
    tc = 0
    for t in to:
        if '@' not in t:
            # if no email domain given use domain from local host
            to[tc] = t + '@' + '.'.join(myhost.split(".")[-2:])
        tc += 1

    message = MIMEMultipart()
    message['From'] = fromaddr
    message['To'] = COMMASPACE.join(to)
    message['Date'] = formatdate(localtime=True)
    message['Subject'] = subject
    message['Cc'] = COMMASPACE.join(cc)
    message['Bcc'] = COMMASPACE.join(bcc)

    body = Template('This is a notification message from $application, running on \n' + \
            'host $host. Please review the following message:\n\n' + \
            '$notify_text\n\nIf output is being captured, you may find additional\n' + \
            'information in your logs.\n'
            )
    host_name = socket.gethostname()
    full_body = body.substitute(host=host_name.upper(),
                                notify_text=text,
                                application=os.path.basename(__file__))

    message.attach(MIMEText(full_body))

    for f in attachments:
        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))
        message.attach(part)

    addresses = []
    for x in to:
        addresses.append(x)
    for x in cc:
        addresses.append(x)
    for x in bcc:
        addresses.append(x)

    smtp = smtplib.SMTP(smtphost)
    smtp.sendmail(fromaddr, addresses, message.as_string())
    smtp.close()

    return True
예제 #60
0
def httprequest(url, postdata={}, headers=None, ssl=False):
    """A urllib.urlopen() replacement for http://... that gets the
    content-type right for multipart POST requests.

    "url" is the http URL to open.
    "postdata" is a dictionary describing data to post. If the dict is
        empty (the default) a GET request is made, otherwise a POST
        request is made. Each postdata item maps a string name to
        either:
        - a string value; or
        - a file part specification of the form:
            {"filename": <filename>,    # file to load content from
             "content": <content>,      # (optional) file content
             "headers": <headers>}      # (optional) headers
          <filename> is used to load the content (can be overridden by
          <content>) and as the filename to report in the request.
          <headers> is a dictionary of headers to use for the part.
          Note: currently the file part content but be US-ASCII text.
    "headers" is an optional dictionary of headers to send with the
        request. Note that the "Content-Type" and "Content-Length"
        headers are automatically determined.

    The current urllib.urlopen() *always* uses:
        Content-Type: application/x-www-form-urlencoded
    for POST requests. This is incorrect if the postdata includes a file
    to upload. If a file is to be posted the post data is:
        Content-Type: multipart/form-data
    
    This returns the response content if the request was successfull
    (HTTP code 200). Otherwise an IOError is raised.

    For example, this invocation:
        url = 'http://www.perl.org/survey.cgi'
        postdata = {
            "name": "Gisle Aas",
            "email": "gisle at aas.no",
            "gender": "M",
            "born": "1964",
            "init": {"filename": "~/.profile"},
        }
   
    Inspiration: Perl's HTTP::Request module.
    http://aspn.activestate.com/ASPN/Reference/Products/ActivePerl/site/lib/HTTP/Request/Common.html
    """
    if not url.startswith("http://"):
        raise "Invalid URL, only http:// URLs are allow: url='%s'" % url

    if not headers:
        headers = {}

    if not postdata:
        method = "GET"
        body = None
    else:
        method = "POST"

        # Determine if require a multipart content-type: 'contentType'.
        for part in postdata.values():
            if isinstance(part, dict):
                contentType = "multipart/form-data"
                break
        else:
            contentType = "application/x-www-form-urlencoded"
        headers["Content-Type"] = contentType

        # Encode the post data: 'body'.
        if contentType == "application/x-www-form-urlencoded":
            body = urllib.urlencode(postdata)
        elif contentType == "multipart/form-data":
            message = MIMEMultipart(_subtype="form-data")
            for name, value in postdata.items():
                if isinstance(value, dict):
                    # Get content.
                    if "content" in value:
                        content = value["content"]
                    else:
                        fp = open(value["filename"], "rb")
                        content = fp.read()

                    part = MIMEBase('application', "octet-stream")
                    part.set_payload(content)
                    #                    Encoders.encode_base64(part)

                    # Add content-disposition header.
                    dispHeaders = value.get("headers", {})
                    if "Content-Disposition" not in dispHeaders:
                        #XXX Should be a case-INsensitive check.
                        part.add_header("Content-Disposition",
                                        "form-data",
                                        name=name,
                                        filename=value["filename"])
                    for dhName, dhValue in dispHeaders:
                        part.add_header(dhName, dhValue)
                else:
                    # Do not use ctor to set payload to avoid adding a
                    # trailing newline.
                    part = MIMEText(None)
                    part.set_payload(value, "us-ascii")
                    part.add_header("Content-Disposition",
                                    "form-data",
                                    name=name)
                message.attach(part)
            message.epilogue = ""  # Make sure body ends with a newline.
            # Split off the headers block from the .as_string() to get
            # just the message content. Also add the multipart Message's
            # headers (mainly to get the Content-Type header _with_ the
            # boundary attribute).
            headerBlock, body = message.as_string().split("\n\n", 1)
            for hName, hValue in message.items():
                headers[hName] = hValue
            #print "XXX ~~~~~~~~~~~~ multi-part body ~~~~~~~~~~~~~~~~~~~"
            #import sys
            #sys.stdout.write(body)
            #print "XXX ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
        else:
            raise "Invalid content-type: '%s'" % contentType

    # Make the HTTP request and get the response.
    # Precondition: 'url', 'method', 'headers', 'body' are all setup properly.
    scheme, netloc, path, parameters, query, fragment = urlparse.urlparse(url)
    if parameters or query or fragment:
        raise "Unexpected URL form: parameters, query or fragment parts "\
              "are not allowed: parameters=%r, query=%r, fragment=%r"\
              % (parameters, query, fragment)

    if ssl:
        conn = httplib.HTTPSConnection(netloc)
    else:
        conn = httplib.HTTPConnection(netloc)
    conn.request(method, path, body, headers)
    response = conn.getresponse()
    return response