def encrypt_email(self, plain_email):
		salt = binascii.hexlify(Crypto.Random.get_random_bytes(16))
		enc_email = MIMEMultipart()

		for header in self.TOKENIZE_HEADER_PART:
			IV = self._create_IV(header, salt)
			if header == 'Subject' and plain_email[header] != None:
				enc_email[header] = self.encrypt_and_tag(IV, plain_email[header]
					, self.TOKENIZE_BLANK_SPACES, 1)
			else:
				print header
				if plain_email[header] != None and plain_email[header] != '':
					enc_email[header] = self.encrypt_and_tag(IV
						, plain_email[header]
						, self.TOKENIZE_EMAIL_ADDRESSES, 0)

		for part in plain_email.walk():
			if (part.get_content_maintype() == 'multipart') and (
				part.get_content_subtype() != 'plain'):
				continue
			body = part.get_payload()
			if body == None:
				return
			IV = self._create_IV('Body', salt)
			enc_body = self.encrypt_and_tag(IV, body
				, self.TOKENIZE_BLANK_SPACES, 2)
			enc_email.attach(MIMEText(enc_body))

		
		print repr(enc_email['From'])
		print repr(salt)

		enc_email.replace_header('From', salt + '.' + enc_email['From'])
		
		return enc_email
Example #2
0
File: tasks.py Project: grv07/clat
def send_mail(html_part, to, subject = 'CLAT account registration email'):
    if html_part and to:
        try:
            import smtplib
            import codecs
            from email.MIMEMultipart import MIMEMultipart
            from email.MIMEText import MIMEText
            server = smtplib.SMTP('smtp.gmail.com', 587)

            #Next, log in to the server
            server.ehlo()
            server.starttls()
            server.ehlo()
            server.login("*****@*****.**", '9999504540')
            msg = MIMEMultipart('alternative')
            msg['Subject'] = subject
            msg['From'] = '*****@*****.**'
            msg['To'] = str(to)
            if html_part:
               part2 = MIMEText(html_part, 'html')
               msg.attach(part2)
            BODY = msg.as_string()
            # msg = "\nHello!" # The /n separates the message from the headers
            print server.sendmail("*****@*****.**", str(to), BODY)
            server.quit()
        except Exception as e:
            # logger.error('under edx_lms.tasks.send_mail '+str(e.args))
            print '/Exception in sendng email',e.args
            # send_mail.retry(countdown = 2, exc = e, max_retries = 2)
    else:
        print 'E-Mail Body not define'
Example #3
0
	def emailPerson(self,person,message=""):
		#send an email with all information of due items, account info, and overdue items
		self.items=items()
		if not type(person)==type({}): raise TypeError("You MUST send in a person dict")
		message="MIRL CHECKOUT SYSTEM UPDATE EMAIL\nPlease read over the information for correctness\n\n"+person['name']+' - '+person["room"]+'\n'+message+'\n'
		message+="Due Items:\n"
		cost=0
		for x in self.dueItems(person):
			date=x[1][:10] #get a sensible date from the item
			message+="    due "+date+"  --  cost: "+self.items.getitem(x[0])['price']+"  --  "+x[0]+'\n'
			cost+=float(self.items.getitem(x[0])['price'])
		message+='\nCharges Due If Not Returned: '+str(cost)
		message+="\n\nPlease contact [email protected] for any questions or concerns\n\n"

		fullMessage=MIMEMultipart()
		fullMessage['From']="*****@*****.**"
		fullMessage["To"]=person['email']
		fullMessage["Subject"]="MIRL TOOLS UPDATE"
		fullMessage.attach(MIMEText(message,'plain'))

		try:
			server=smtplib.SMTP()
			server.connect('smtp.gmail.com',587)
			server.starttls()
			server.login("*****@*****.**","labmanager232")
			server.sendmail("*****@*****.**",person['email'],fullMessage.as_string()) #from,to,message
		except Exception,r:
			print "UNABLE TO SEND EMAIL!!!!"
			print r
	def decrypt_email(self, enc_email):
		salt = enc_email['From'][:32]
		enc_email.replace_header('From', enc_email['From'][33:])
		plain_email = MIMEMultipart()

		for header in self.TOKENIZE_HEADER_PART:
			IV = SHA256.new(salt+ header).digest()[:16]
			if header == 'Subject':
				plain_email[header] = self.decrypt(IV, enc_email[header][
					66:enc_email[header].find('.', 99)+1])
			else:
				if enc_email[header] != None:
					plain_email[header] = self.decrypt(IV, enc_email[header])

		for part in enc_email.walk():
			if (part.get_content_maintype() == 'multipart') and (
				part.get_content_subtype() != 'plain'):
				continue
			body = part.get_payload()
			if body == None or body == '':
				return plain_email
			IV = SHA256.new(salt + 'Body').digest()[:16]
			plain_body = self.decrypt(IV, body[98:body.find('.', 131)+1])
			plain_email.attach(MIMEText(plain_body))
		return plain_email
    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()
Example #6
0
def send_email(en, email_server, to):
    """ Send out an email copy of the note with the issues extracted"""
    from_name = "*****@*****.**"
    body = ""
    msg = MIMEMultipart("alternative")
    msg["Subject"] = "Exploratory Test Session on %s" % en.title.strip()
    msg["From"] = from_name
    msg["To"] = to
    issues = []
    for val in en.activity:
        if val[2].upper() == "I":
            issues.append(val[1])
    if len(issues) > 0:
        body = "<p>The following issues where identified during the test session</p>"
        body += "<ul>"
        for issue in issues:
            body += "<li>%s</li>" % issue
        body += "</ul>"
    body = body.encode("ascii", "ignore")
    en_string = en.tostring().decode("utf8")
    en_string = en_string.encode("ascii", "ignore")
    msg_body = MIMEText(body + en_string, "html")
    msg.attach(msg_body)
    # SEND THE MAIL
    s = smtplib.SMTP(email_server)
    s.sendmail(from_name, to, msg.as_string())
    s.quit()
def send_email(event):

    email_headers = MIMEMultipart()
    email_headers['From'] = ''
    email_headers['To'] = ''
    
    if (event == 'start'):
        
        email_headers['Subject'] = "DEV AWS: Instance has been started"
        
    elif (event == 'stop'):
        
        email_headers['Subject'] = "DEV AWS: Instance has been stopped"
        
    email_body = "This email was generated automatically by Infra team" 
    email_headers.attach(MIMEText(email_body, 'plain'))   
    
    smtp = smtplib.SMTP('outlook.office365.com', '587')
    smtp.starttls()  
    smtp.login('', '')
    
    email = email_headers.as_string()
    
    smtp.sendmail(email_headers['From'], email_headers['To'], email)
    smtp.quit()
Example #8
0
def mail(to, subject, text):
    try:

        user = read_config("SMTP_USERNAME")
        pwd = read_config("SMTP_PASSWORD")
        smtp_address = read_config("SMTP_ADDRESS")
        # port we use, default is 25
        smtp_port = int(read_config("SMTP_PORT"))
        smtp_from = read_config("SMTP_FROM")
        msg = MIMEMultipart()
        msg['From'] = smtp_from
        msg['To'] = to
        msg['Subject'] = subject
        msg.attach(MIMEText(text))
        # prep the smtp server
        mailServer = smtplib.SMTP("%s" % (smtp_address), smtp_port)
        # send ehlo
        mailServer.ehlo()
	# if we aren't using open relays
	if user != "":
	        # tls support?
        	mailServer.starttls()
       		# some servers require ehlo again
        	mailServer.ehlo()
	        mailServer.login(user, pwd)

	# send the mail
        mailServer.sendmail(smtp_from, to, msg.as_string())
        mailServer.close()

    except:
        write_log("[!] %s: Error, Artillery was unable to log into the mail server" % (grab_time()))
Example #9
0
    def __sendMail(self, sToEMail, sSubject, sContent, sFromTitle):
        """
            发送邮件
            :param sToEMail: 目标email,多个email可以采用英文分号分开
            :param sSubject: 邮件主题,utf-8编码
            :param sContent: 邮件内容,utf-8编码
            :param sFromTitle: 发件人名称,utf-8编码
            :return: 无
        """
        # print 'sFromTitle', sFromTitle
        msg = MIMEMultipart()
        msg['From'] = sFromTitle.decode('utf-8').encode("gbk","ignore") + "<%s>" % (self.sAccoutFull) #
        sSubject = sSubject.decode('utf-8').encode("gbk","ignore")
        sContent = sContent.decode('utf-8').encode("gbk","ignore")
        msg['Subject'] = sSubject #.encode("gbk","ignore")
        txt = MIMEText(sContent,'html','gbk')
        msg.attach(txt)

        # send email
        if self.sMailHost.upper() in ['QQ.COM']: #QQ邮箱要采用SSL登录
            smtp = smtplib.SMTP_SSL('smtp.qq.com', timeout=30)#连接smtp邮件服务器,端口默认是25
        else:
            smtp = smtplib.SMTP(self.sSMTPHost)
        # smtp.set_debuglevel(1) #会打印邮件发送日志
        smtp.login(self.sAccout,self.sPassword)
        for sTo in sToEMail.split(';'):
            if sTo:
              smtp.sendmail(self.sAccoutFull, sTo, msg.as_string())
        smtp.quit()
        PrintTimeMsg('SendMail.sToEMail(%s) successfully!' % sToEMail)
Example #10
0
    def repr_mimemessage(self):
        from email.MIMEMultipart  import MIMEMultipart
        from email.MIMEText  import MIMEText

        outer = MIMEMultipart()
        items = self._headers.items()
        items.sort()
        reprs = {}
        for name, value in items:
            assert ':' not in name
            chars = map(ord, name)
            assert min(chars) >= 33 and max(chars) <= 126
            outer[name] = str(value)
            if not isinstance(value, str):
                typename = type(value).__name__
                assert typename in vars(py.std.__builtin__)
                reprs[name] = typename

        outer['_reprs'] = repr(reprs)

        for name in self._blocknames:
            text = self._blocks[name]
            m = MIMEText(text)
            m.add_header('Content-Disposition', 'attachment', filename=name)
            outer.attach(m)
        return outer
def send_email(subject,message,reciver):
    from_email = "*****@*****.**"

    server = "smtp.gmail.com"
    port = "25"
    user_name = "*****@*****.**"
    user_passwd = '264eba9a86c5e3107310ae07757bdc2b'


    # формирование сообщения
    msg = MIMEMultipart('mixed')
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = ', '.join(reciver)
    
    # Формируем письмо
    part1 = MIMEText(message, 'html','utf-8')
    msg.attach(part1)
    
    # отправка
    s = smtplib.SMTP(server, port)
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login(user_name, user_passwd)
    s.sendmail(from_email, msg['To'], msg.as_string())
    s.quit()
Example #12
0
 def flush(self,Nmin):
     res=[]
     with locker.lock('accumulating_notifcations'):
         for key in self.cache.keys():
             (subject,sender,addressee)=key
             if self.cache[key]['N'] <= Nmin: 
                 ## flush only above a certain amount of messages
                 continue
             destination = addressee.split(COMMASPACE)
             text = self.cache[key]['Text']
             msg = MIMEMultipart()
             
             msg['From'] = sender
             msg['To'] = addressee
             msg['Date'] = formatdate(localtime=True)
             new_msg_ID = make_msgid()  
             msg['Message-ID'] = new_msg_ID 
             msg['Subject'] = subject
             
             ## add a signature automatically
             text += '\n\n'
             text += 'McM Announcing service'
             #self.logger.log('Sending a message from cache \n%s'% (text))
             try:
                 msg.attach(MIMEText(text))
                 smtpObj = smtplib.SMTP()
                 smtpObj.connect()
                 smtpObj.sendmail(sender, destination, msg.as_string())
                 smtpObj.quit()
                 self.cache.pop(key)
                 res.append( subject )
             except Exception as e:
                 print "Error: unable to send email", e.__class__
         return res
Example #13
0
    def send_mail(self, subject, body):
        c = self.config['gmail']
        recipients = c['recipients']

        mmsg = MIMEMultipart()

        if isinstance(recipients, list):
            mmsg['To'] = ", ".join(recipients)
        else:
            mmsg['To'] = recipients
            recipients = [recipients]

        mmsg['From'] = c['email']
        mmsg['Subject'] = subject
        mmsg.attach(MIMEText(body, 'plain'))
        try:
            conn = smtplib.SMTP(c['server'], c['port'])
            conn.starttls()
            conn.login(c['email'], c['password'])
            conn.sendmail(c['email'], recipients, mmsg.as_string())
            conn.quit()
            msg = "Successfully sent email: {0}"
            logging.info(msg.format(mmsg['Subject']))
        except smtplib.SMTPException as e:
            msg = "Error sending email: {0} {1}"
            logging.info(msg.format(mmsg['Subject']), e)
            return False

        return True
def sendMail(body):

	mailConfig = getMailConfig()

	msg = MIMEMultipart('alternative')
	msg['From'] = mailConfig["from"]
	msg['To'] = mailConfig["to"]
	msg['Subject'] = "Playstation Network Price Drop"

	if (sys.version_info[0] == 2):
		sendBody = body.encode('utf-8')
	else:
		sendBody = body

	htmlMail = MIMEText(sendBody, 'html')
	msg.attach(htmlMail)

	mailServer = smtplib.SMTP(mailConfig["server"])
	mailServer.ehlo()
	mailServer.starttls()
	mailServer.ehlo()
	mailServer.login(mailConfig["username"],mailConfig["password"])
	mailServer.sendmail(mailConfig["from"], msg['To'], msg.as_string())

	mailServer.quit()
    def send_mail(self, user, password, recipient, subject, message): 
        """Method for seding mail from a a gmail account."""
        server = None

        # MIME data
        msg = MIMEMultipart()
        msg['From'] = user
        msg['To'] = recipient
        msg['Subject'] = subject
        msg.attach(MIMEText(message))
    
        # Server connection and sending email
        try:
           server = smtplib.SMTP('smtp.gmail.com', 587)
           server.ehlo() # Not really necesary but just in case
           server.starttls()
           server.ehlo()
           server.login(user, password)
           server.sendmail(user, recipient, msg.as_string())
        except:
           print("/!\ We got an error here, see the traceback below for more info!")
           print(traceback.format_exc())
        else:
           print("The message have been successfully sent to gmail adress %s!" % recipient)
        finally:
           if server: server.close()
Example #16
0
class notifier():
	def __init__(self):
		# Credentials
		self.username = '******'
		self.fromaddr = '*****@*****.**'
		#uses base64 to provide an illusion of security
		self.password = base64.b64decode("Mzk3ODY2UzEyRDUy")
		self.toaddrs = ''
		self.subject = ''
		self.body = ''
	# sets the email's recepients, should be in form ['*****@*****.**','*****@*****.**']
	def set_recepients(self,toaddrs):
		self.toaddrs = toaddrs
	def set_content(self,subject, body):
		self.subject = subject
		self.body = body
	def send(self):
		#sends the email
		self.msg = MIMEMultipart()
		self.msg['From'] = self.fromaddr
		self.msg['To'] = COMMASPACE.join(self.toaddrs)
		self.msg['Subject'] = self.subject
		self.msg.attach(MIMEText(self.body, 'plain'))
		self.server = smtplib.SMTP('smtp.gmail.com:587')
		self.server.ehlo()
		self.server.starttls()
		self.server.ehlo()
		self.server.login(self.username,self.password)
		self.server.sendmail(self.fromaddr, self.toaddrs, self.msg.as_string())
		print self.msg.as_string()
		self.server.quit()
	def __del__(self):
		pass
Example #17
0
def SMTPServer(title, sender, to, content):
	server = 'mail.pegatroncorp.com'
	username = "******"
	password = "******"

	try:
		#//might need to switch to STARTTLS authentication.
		smt = smtplib.SMTP(server,587)
		smt.set_debuglevel(0)
		smt.ehlo()
		smt.starttls()
		smt.ehlo
		#//loging
		smt.login(username,password)
   
		try:
			#//Mail_content
			strMessage = MIMEMultipart()
			strMessage['Subject'] = title
			strMessage['From'] = sender
			strMessage['To'] = ", ".join(to)#print ", ".join(to)#strMessage['To'] = to
      #strMessage['To'] = ", ".join(to) ##//multiple recipints
			strMessage.attach(MIMEText(content, 'html'))
		
		except Exception, e:
			print("strMessage failed: \n{0}".format(e))
			return e.args

		#//mail content
		smt.sendmail(sender,to,strMessage.as_string())
		smt.close()
Example #18
0
File: mail.py Project: algby/ietfdb
def copy_email(msg, to, toUser=False, originalBcc=None):
    '''
    Send a copy of the given email message to the given recipient.
    '''
    add_headers(msg)
    new = MIMEMultipart()
    # get info for first part.
    # Mode: if it's production, then "copy of a message", otherwise
    #  "this is a message that would have been sent from"
    # hostname?
    # django settings if debugging?
    # Should this be a template?
    if settings.SERVER_MODE == 'production':
	explanation = "This is a copy of a message sent from the I-D tracker."
    elif settings.SERVER_MODE == 'test' and toUser:
	explanation = "The attached message was generated by an instance of the tracker\nin test mode.  It is being sent to you because you, or someone acting\non your behalf, is testing the system.  If you do not recognize\nthis action, please accept our apologies and do not be concerned as\nthe action is being taken in a test context."
    else:
	explanation = "The attached message would have been sent, but the tracker is in %s mode.\nIt was not sent to anybody." % settings.SERVER_MODE
        if originalBcc:
          explanation += ("\nIn addition to the destinations derived from the header below, the message would have been sent Bcc to %s" % originalBcc)
    new.attach(MIMEText(explanation + "\n\n"))
    new.attach(MIMEMessage(msg))
    # Overwrite the From: header, so that the copy from a development or
    # test server doesn't look like spam.
    new['From'] = settings.DEFAULT_FROM_EMAIL
    new['Subject'] = '[Django %s] %s' % (settings.SERVER_MODE, msg.get('Subject', '[no subject]'))
    new['To'] = to
    send_smtp(new)
Example #19
0
    def test_unicode_complex_message(self):
        charset = 'utf-8'
        p1 = MIMEText(u'''По оживлённым берегам
Громады стройные теснятся
Дворцов и башен; корабли
Толпой со всех концов земли
К богатым пристаням стремятся;'''.encode(charset),
                        'plain',
                        charset)
        p2 = MIMEText(u'''<p>По оживлённым берегам
Громады стройные теснятся
Дворцов и башен; корабли
Толпой со всех концов земли
К богатым пристаням стремятся;</p>'''.encode(charset),
                        'plain',
                        charset)
        msg1 = MIMEMultipart()
        msg1['Message-ID'] = '<*****@*****.**>'
        msg1.attach(p1)
        msg1.attach(p2)
        s_msg = msg1.as_string()
        msg2 = parse_message(s_msg)
        for part in msg2['parts']:
            if part['payload'] is None: continue
            assert isinstance(part['payload'], unicode)
Example #20
0
    def email(self, message, to):
        print 'send mail'

        if not 'subject' in message.keys():
            print "please define a email subject"
            return 
        if not 'message' in message.keys():
            print "please define a email text"
            return 

        import smtplib
        from email.MIMEMultipart import MIMEMultipart
        from email.MIMEText import MIMEText

        mail_usr = self.serviceconfig.mail['usermail']
        mail_pwd = self.serviceconfig.mail['password']

        msg = MIMEMultipart('alternative')
        msg['Subject'] = message['subject']
        msg['From'] = mail_usr
        msg['To'] = to

        part = MIMEText(message['message'], 'plain')
        msg.attach(part)

        mailServer = smtplib.SMTP("smtp.gmail.com", 587)
        mailServer.ehlo()
        mailServer.starttls()
        mailServer.ehlo()
        mailServer.login(mail_usr, mail_pwd)
        mailServer.sendmail(mail_usr, to, msg.as_string())
        mailServer.quit()
Example #21
0
 def NewMessage(self, receiver, subject, body):
   msg = MIMEMultipart()
   msg['From'] = self.sender
   msg['To'] = receiver
   msg['Subject']  = subject
   msg.attach(MIMEText(body,'plain'))
   return msg
Example #22
0
def sendPasswordRecoveryEmail(username, email, fullName):

    bitterEmail = "*****@*****.**"
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(bitterEmail, "bitter2041")

    url = "http://cgi.cse.unsw.edu.au/~z3461601/ass2/bitter.cgi?operation=resetPasswordView&user="******"html/emailRecoverPassword.html")
    emailContent = htmlFile.read()
    htmlFile.close()
    emailContent = emailContent % {"fullName": fullName, "url": url, "username": username}

    msg = MIMEMultipart()
    msg["From"] = bitterEmail
    msg["To"] = email
    msg["Subject"] = "Bitter Verification"

    msg.attach(MIMEText(emailContent, "html"))

    mailServer.sendmail(bitterEmail, email, msg.as_string())
    mailServer.quit()
def send_mail(plain_text, subject):

#    s = smtplib.SMTP(config.smtp_server_name, config.smtp_server_port)
    s = smtplib.SMTP(config.smtp_server_name, config.smtp_server_port)
    if not config.simple_email_auth:
        s.ehlo()
        s.starttls()
        s.ehlo()
        s.login(config.email_sender, config.email_password)

    timestamp = strftime("%Y-%m-%d", config.now)
    msg = MIMEMultipart()

    msg['Subject'] = subject
    msg['From'] = config.email_sender
    msg['To'] = ','.join(config.email_to)

    message = MIMEText(plain_text, 'plain', "utf-8")

    msg.attach(message)

    #print msg.as_string()

    s.sendmail(config.email_sender, config.email_to, msg.as_string())
    s.close()
Example #24
0
    def forgotten_password(self):
        email = self.prm('email')
        db_user = meta.Session.query(User).filter(User.email==email).first()
        if (db_user is None):
            return h.toJSON({ 'status': 'NOK', 'message': _(u'No se ha encontrado un usuario con ese correo electrónico.') })
        else:
            # Create and save the new password
            size = 9
            new_password = ''.join([choice(string.letters + string.digits) for i in range(size)])
            db_user.password = hashlib.md5(new_password).hexdigest()
            meta.Session.commit()
            
            # Send the email
            try:
                gmail_user = '******' # REFACTOR: [JUANJO] Moverlo a algun sitio de configuracion
                gmail_pwd = '9G*rY2Vrr'

                msg = MIMEMultipart()
                msg['From'] = gmail_user
                msg['To'] = db_user.email
                msg['Subject'] = _(u'Nueva contraseña de Feelicity')
                msg.attach(MIMEText(_(u'Nuevo password: '******'utf-8')))

                mailServer = smtplib.SMTP('smtp.gmail.com', 587)
                mailServer.ehlo()
                mailServer.starttls()
                mailServer.ehlo()
                mailServer.login(gmail_user, gmail_pwd)
                mailServer.sendmail(gmail_user, db_user.email, msg.as_string())
                mailServer.close()
            except SMTPRecipientsRefused:
                return h.toJSON( { 'status': 'NOK', 'message': _(u'No se ha podido enviar el correo electrónico a la dirección indicada. Intentelo de nuevo más tarde.') } )
   
            return h.toJSON({ 'status': 'OK'})
def email_alert(siginfo, to_addrs):
    smtp_host    = get_config('email','smtp_host')
    smtp_port    = get_config('email','smtp_port', int)
    from_address = get_config('email','from_address')

    from_user, from_domain = parse_email_addr(from_address)
    if from_user is None:
        from_user = "******"
    if from_domain is None:
        from_domain = get_hostname()
    from_address = '%s@%s' % (from_user, from_domain)

    log_debug("alert smtp=%s:%d  -> %s" % (smtp_host, smtp_port, ','.join(to_addrs)))

    siginfo.update_derived_template_substitutions()
    summary = siginfo.substitute(siginfo.summary())
    subject = '[%s] %s' % (get_config('email','subject'), summary)
    text = siginfo.format_text() + siginfo.format_details() 

    email_msg            = MIMEMultipart('alternative')
    email_msg['Subject'] = subject
    email_msg['From']    = from_address
    email_msg['To']      = ', '.join(to_addrs)
    email_msg['Date']    = formatdate()

    email_msg.attach(MIMEText(text))

    import smtplib
    try:
        smtp = smtplib.SMTP(smtp_host, smtp_port)
        smtp.sendmail(from_address, to_addrs, email_msg.as_string())
        smtp.quit()
    except smtplib.SMTPException, e:
        syslog.syslog(syslog.LOG_ERR, "email failed: %s" % e)
Example #26
0
def handle_contact_form():
    print request.form
    from_address = config.server_email
    to_address = config.contact_email
    msg = MIMEMultipart()
    msg['From'] = from_address
    msg['To'] = to_address
    msg['Subject'] = "A new client for Academic Tours"
    body = """
           Mr. Boden,

           {name} just contacted you via your website contact form.

           You can reach them at {email} or {phone}.

           They said their dream vacation was:

           {vacation}
           """.format(name=request.form["name"],
                      email=request.form["email"],
                      phone=request.form["phone"],
                      vacation=request.form["destination"])
    msg.attach(MIMEText(body, 'plain'))

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(config.smtp_username, config.smtp_password)
    text = msg.as_string()
    server.sendmail(from_address, to_address, text)
    return render_template("thankyou.html",
                           referral=get_referral(),
                           layout="thankyou",
                           name=request.form["name"])
Example #27
0
    def contact(self):
        email = self.prm('email')
        name = self.prm('name')
        content = self.prm('content')

        try:
            gmail_user = '******' # REFACTOR: [JUANJO] Moverlo a algun sitio de configuracion
            gmail_pwd = '9G*rY2Vrr'

            msg = MIMEMultipart()
            msg['From'] = email
            msg['To'] = gmail_user
            msg['Subject'] = name + '<' + email + '>'
            msg.attach(MIMEText(content))
            
            mailServer = smtplib.SMTP('smtp.gmail.com', 587)
            mailServer.ehlo()
            mailServer.starttls()
            mailServer.ehlo()
            mailServer.login(gmail_user, gmail_pwd)
            mailServer.sendmail(email, gmail_user, msg.as_string())
            mailServer.close()
        except SMTPRecipientsRefused:
            return h.toJSON( { 'status': 'NOK', 'message': _(u'No se ha podido enviar el mensaje correctamente. Intentelo de nuevo más tarde.') } )
        
        return h.toJSON({ 'status': 'OK', 'message': _(u'Mensaje enviado correctamente. Nos pondremos en contacto contigo lo antes posible.') })
Example #28
0
def mail(to, subject, text):
    import smtplib
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email.MIMEText import MIMEText
    import os

    gmail_user = os.environ['GMAIL_USER']
    gmail_pwd = os.environ['GMAIL_PASSWORD']

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

    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())
    mailServer.close()
Example #29
0
def send_email(email_text, subject="Simulation Finished"):
# -----------------------------------------------------------------------------
    """
    Sends me email. Used for notifications that the simulations have finished.
    """
    import smtplib
    from email.MIMEText import MIMEText
    from email.MIMEMultipart import MIMEMultipart

    gmailUser = '******'
    gmailPassword = '******'
    recipient = '*****@*****.**'
    msg = MIMEMultipart()
    msg['From'] = gmailUser
    msg['To'] = recipient
    msg['Subject'] = subject
    msg.attach(MIMEText(email_text))
    mailServer = smtplib.SMTP('smtp.gmail.com', 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(gmailUser, gmailPassword)
    mailServer.sendmail(gmailUser, recipient, msg.as_string())
    mailServer.close()
    print('Sent email to %s' % recipient)
Example #30
0
 def send(self, email_to, email_subject, email_content, is_dry=False):
     """
         is_dry为true时,不执行,仅仅sleep
     """
     if is_dry:
         time.sleep(10)
     else:
         msg = MIMEMultipart()
         at = email_to.find("@")
         if at <= 0: return
         domain = email_to[at+1:].strip()
         if domain not in NOT_SUPPORT_UTF8_DOMAIN:
             enc = "utf-8"
         else:
             enc = "gb18030"
         if enc.lower() != "utf-8":
             print enc
             self.email_from = self.ignore_encode(self.email_from, enc) 
             email_to = self.ignore_encode(email_to, enc)
             email_content = self.ignore_encode(email_content, enc)
             email_subject = self.ignore_encode(email_subject, enc)
         #msg = MIMEMultipart()
         msg = MIMEText(email_content, _subtype="plain",  _charset=enc)
         msg['Subject'] = Header(email_subject, enc) 
         fname = str(Header(self.email_from, enc))
         msg['From'] = formataddr((fname, self.email_from))
         tname = str(Header(email_to, enc))
         msg['To'] = formataddr((tname, email_to))
         print (self.email_from, email_to, msg)
         errs = ""
         errs = self.sendSvr.sendmail(self.email_from, email_to, msg.as_string())
         assert len(errs) == 0
Example #31
0
def main(argv):
    
    reportdir = str(argv[1])
    outputxmlfilepath = 'C:\\MM_Results\\' + reportdir + '\\output.xml'
    textdatafilepath = 'C:\\Mentoring_Minds\\mysatori-qa\\Wizard_Interface\\Automation_Testsuites\\Test.txt'
    SUITENAME = 'TestDataCreation'

    xmldoc = parse(outputxmlfilepath)
    
    #Read all the test suites from output.xml file
    itemlist = xmldoc.getElementsByTagName('suite')
    print itemlist
    starttiming = ''
    endtiming = ''

    for suite in range(0,len(itemlist)-1) :
        #Read the test suite names
        suitename= itemlist[suite].attributes['name'].value
        print suitename
        #Read the starttime and end time of the given suite
        if(suitename == SUITENAME): 
            statusTgList = itemlist[suite].getElementsByTagName('status')
            starttiming = statusTgList[suite].attributes['starttime'].value
            print starttiming
            
            for val in range (0,len(statusTgList)-1):
                endtiming = statusTgList[val].attributes['endtime'].value
            print endtiming
            break

    datetimeobject = datetime.strptime(starttiming,'%Y%m%d %H:%M:%S.%f')
    startdate = datetimeobject.strftime('%m-%d-%y')
    starttime = datetimeobject.strftime('%H:%M')
    datetimeobject = datetime.strptime(endtiming,'%Y%m%d %H:%M:%S.%f')
    enddate = datetimeobject.strftime('%m-%d-%y')
    endtime = datetimeobject.strftime('%H:%M')

    print startdate
    print starttime
    print enddate
    print endtime
    
    #Read the execution time from output.xml file.

    timevalue1 = starttiming
    timevalue2 = endtiming

    print timevalue1
    print timevalue2
    
    #diffval = timevalue2 - timevalue1
    #print "diffval:"+str(diffval)
    #diffvalList = str(diffval).split(".")
    #executiontime = diffvalList[0]

    filePath = textdatafilepath
    f = open(filePath,"r");
    contents = f.read()
    schoolDct = {}
    for row in contents.split("\n"):
        if len(row.strip())>0:
            print row
            rowvalues = row.split(" = ")
            schoolDct[str(rowvalues[0])]= str(rowvalues[1])
    print schoolDct

    if(schoolDct['NewSchoolsAdded']!='True'):
        return False

        
    with open("mailText.txt", "w") as myfile:

        print schoolDct['schoolName']
        string1 = str(schoolDct['schoolName'])
        if 'School' in string1 :
            schoolnamelist = string1.split("School")
            schoolDct['schoolName'] = schoolnamelist[0]
        print schoolDct['schoolName']
        
        URL = 'http://v4.tomo.zone/mysdb_m3_sales/_design/mys/mmloginw.html#customerid:'
        
        myfile.write(schoolDct['schoolName']+' school setup completed at '+ endtime +' on '+ enddate +'.\n')
        myfile.write('\n')
        
        myfile.write('It can now be accessed here:\n')
        myfile.write(URL+schoolDct['password']+'\n')
        myfile.write('\n')
        myfile.write('Zip code:'+schoolDct['zip']+'\n')
        myfile.write('\n')
        myfile.close()

    textfile = 'mailText.txt'
    fp = open(textfile, 'r') 
    body = fp.read()
    fp.close()

    if(schoolDct['Teststatus'] == 'FAIL'):
        return False

    msg = MIMEMultipart()

    # recipients email ids
    recipients = ['*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**'] 
    
    # Sender email details
    me = '*****@*****.**'
    Password = "******"

    #SMTP server details
    smtpservername = 'smtp.gmail.com'
    
    subject = 'Sandbox complete for '+schoolDct['schoolName']+' School at Zip Code ['+schoolDct['zip']+']'
    msg['From'] = me
    msg['To'] = COMMASPACE.join(recipients)
    msg['Date'] = formatdate(localtime = True)

    # Send the message via the Gmail server.
    msg['Subject'] = subject
    msg.attach(MIMEText(body))
    smtp = smtplib.SMTP('smtp.gmail.com',587)
      
    smtp.ehlo()
    smtp.starttls()
    smtp.ehlo
    
    smtp.login(me,Password)

    smtp.sendmail(me, recipients, msg.as_string().replace("\\",""))
    smtp.close()
    print('The email subject is "' + msg['Subject'] +'"')
Example #32
0
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import time
import RPi.GPIO as GPIO
# Pines sensor IR
GPIO.setmode(GPIO.BOARD)
GPIO.setup(40, GPIO.IN)
# Datos de envio
SourceAdress = "*******"
DestinyAdress = "*******"

server = stmplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(SourceAdress, "*******")

msg = MIMEMultipart()
msg['From'] = SourceAdress
msg['To'] = DestinyAdress
msg['Subject'] = "Alerta de seguridad"

mensaje = "ALERTA! Se ha detectado una presencia en la camara numero 1."
msg.attach(MIMEText(mensaje, 'plain'))
Texto = msg.as_string()

if GPIO.input(40) == 1:
    print "Enviando correo de alerta"
    server.sendmail(SourceAdress, DestinyAdress, Texto)
    time.sleep(5)

else:
    print "No se detecto ninguna presencia"
Example #33
0
def _sendMail(to, fro, subject, text, server="localhost"):
    assert type(to) == list

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

    msg.attach(MIMEText(text))
    print "_sendMail:msg", msg

    status = False
    username = get_config_param('database.ini', 'Email', 'username')
    password = get_config_param('database.ini', 'Email', 'password')
    port = int(get_config_param('database.ini', 'Email', 'port'))
    if port == False:
        print "parameter port is not set"
        return False

    smtp = None
    try:
        smtp = smtplib.SMTP(server, port)
        status = True
    except Exception as e:
        print(e)
        status = False
    finally:
        if status == False:
            print "error in smtp connection"
            return status

    try:
        #smtp = smtplib.SMTP(server,port)
        #if not smtp:
        #  print "smtp is not defined"
        #  return
        print "set debug level for smtp"
        smtp.set_debuglevel(True)

        # identify yourself, and get supported features
        smtp.ehlo()

        # start tls for security
        if smtp.has_extn('STARTTLS'):
            print "TLS Supported"
            #starttls and check if it succeeded
            if smtp.starttls()[0] == 220:
                print "starttls succeeded"
            #return in case starttls is supported and fails
            else:
                print "starttls failed"
                status = False
                return
            smtp.ehlo()  # re-identify ourselves over TLS connection

        if username != False and password != False:
            smtp.login(username, password)
        sendStatus = smtp.sendmail(fro, to, msg.as_string())
        print "sendStatus=", sendStatus
        if sendStatus:
            print "Receipient refused"
            status = False
            return
        print "send email succeeded"
        status = True
    #except:
    except Exception as e:
        print(e)
        print "failed to send mail"
        status = False
        return
    finally:
        if smtp is not None:
            smtp.quit()
        return status
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders

fromaddr = "*****@*****.**"
password = ""
toaddr = "*****@*****.**"
subject = "SUBJECT OF THE EMAIL"
body = "TEXT YOU WANT TO SEND"
filename_list = [
    "bittrex_USDT-OMG_hour.png", "output.png", "Bittrex_API_document.docx"
]

msg = MIMEMultipart()

msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = subject

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

for filename in filename_list:
    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)
Example #35
0
def mail(to, subject, prioflag1, prioflag2, text):

    msg = MIMEMultipart()
    msg['From'] = str(
        Header(from_displayname, 'UTF-8').encode() + ' <' + from_address +
        '> ')
    msg['To'] = to
    msg['X-Priority'] = prioflag1
    msg['X-MSMail-Priority'] = prioflag2
    msg['Subject'] = Header(subject, 'UTF-8').encode()

    body_type = MIMEText(text, "%s" % (message_flag), 'UTF-8')
    msg.attach(body_type)

    # now attach the file
    if file_format != "":
        fileMsg = email.mime.base.MIMEBase('application', '')
        fileMsg.set_payload(file(file_format).read())
        email.encoders.encode_base64(fileMsg)
        fileMsg.add_header(
            'Content-Disposition',
            'attachment; filename="%s"' % os.path.basename(file_format))
        msg.attach(fileMsg)

    for inline_file in inline_files:
        if inline_file != "":
            fileMsg = email.mime.base.MIMEBase('application', '')
            fileMsg.set_payload(file(inline_file).read())
            email.encoders.encode_base64(fileMsg)
            fileMsg.add_header(
                'Content-Disposition',
                'inline; filename="%s"' % os.path.basename(inline_file))
            fileMsg.add_header("Content-ID",
                               "<%s>" % os.path.basename(inline_file))
            msg.attach(fileMsg)

    mailServer = smtplib.SMTP(smtp, port)

    io = StringIO()
    msggen = Generator(io, False)
    msggen.flatten(msg)

    if sendmail == 0:

        if email_provider == "gmail" or email_provider == "yahoo" or email_provider == "hotmail":
            try:
                mailServer.starttls()
            except:
                pass
                mailServer.ehlo()

            else:
                mailServer.ehlo()

    try:
        if provideruser != "" or pwd != "":
            mailServer.login(provideruser, pwd)
            mailServer.sendmail(from_address, to, io.getvalue())
        else:
            mailServer.sendmail(from_address, to, io.getvalue())
    except:
        # try logging in with base64 encoding here
        import base64
        try:
            mailServer.docmd("AUTH LOGIN", base64.b64encode(provideruser))
            mailServer.docmd(base64.b64encode(pwd), "")

# CUSTOM PATH FOR AUTHENTICATION ERROR

        except:
            try:
                #py3 compatability
                mailServer.docmd(
                    "AUTH LOGIN",
                    base64.b64encode(provideruser.encode('utf-8')))
                mailServer.docmd(base64.b64encode(pwd.encode('utf-8')), "")
            # except exceptions and print incorrect password
            except Exception as e:
                print_warning(
                    "It appears your password was incorrect.\nPrinting response: "
                    + (str(e)))
                return_continue()

    if sendmail == 1:
        mailServer.sendmail(from_address, to, io.getvalue())
Example #36
0
def sendMultipartMail(context,
                      from_,
                      to,
                      cc=[],
                      bcc=[],
                      subject="",
                      text="",
                      charset="utf-8"):
    """
    """
    mail = MIMEMultipart("alternative")

    mail['From'] = from_
    mail['To'] = to
    mail['Bcc'] = "".join(cc)
    mail['Bcc'] = "".join(bcc)
    mail['Subject'] = subject
    mail.epilogue = ''

    # create & attach text part
    text = text.encode("utf-8")
    text_part = MIMEText(text, "plain", charset)
    mail.attach(text_part)

    # create & attach html part with images
    html_part = MIMEMultipart("related")
    html_code = MIMEText(text, "html", charset)
    html_part.attach(html_code)
    mail.attach(html_part)

    context.MailHost.send(mail.as_string())
Example #37
0
def forge_email(fromaddr,
                toaddr,
                subject,
                content,
                html_content='',
                html_images=None,
                usebcc=False,
                header=None,
                footer=None,
                html_header=None,
                html_footer=None,
                ln=CFG_SITE_LANG,
                charset=None):
    """Prepare email. Add header and footer if needed.
    @param fromaddr: [string] sender
    @param toaddr: [string or list-of-strings] list of receivers (if string, then
                   receivers are separated by ',')
    @param usebcc: [bool] True for using Bcc in place of To
    @param subject: [string] subject of the email
    @param content: [string] content of the email
    @param html_content: [string] html version of the email
    @param html_images: [dict] dictionary of image id, image path
    @param header: [string] None for the default header
    @param footer: [string] None for the default footer
    @param ln: language
    @charset: [string] the content charset. By default is None which means
    to try to encode the email as ascii, then latin1 then utf-8.
    @return: forged email as a string"""

    if html_images is None:
        html_images = {}

    if header is None:
        content = email_header(ln) + content
    else:
        content = header + content
    if footer is None:
        content += email_footer(ln)
    else:
        content += footer

    if charset is None:
        (content, content_charset) = guess_minimum_encoding(content)
    else:
        content_charset = charset

    try:
        subject = subject.encode('ascii')
    except (UnicodeEncodeError, UnicodeDecodeError):
        subject = Header(subject, 'utf-8')

    try:
        fromaddr = fromaddr.encode('ascii')
    except (UnicodeEncodeError, UnicodeDecodeError):
        fromaddr = Header(fromaddr, 'utf-8')

    if type(toaddr) is not str:
        toaddr = ','.join(toaddr)
    try:
        toaddr = toaddr.encode('ascii')
    except (UnicodeEncodeError, UnicodeDecodeError):
        toaddr = Header(toaddr, 'utf-8')

    if html_content:
        if html_header is None:
            html_content = email_html_header(ln) + html_content
        else:
            html_content = html_header + html_content
        if html_footer is None:
            html_content += email_html_footer(ln)
        else:
            html_content += html_footer

        if charset is None:
            (html_content,
             html_content_charset) = guess_minimum_encoding(html_content)
        else:
            html_content_charset = charset

        msg_root = MIMEMultipart('alternative')
        msg_root['Subject'] = subject
        msg_root['From'] = fromaddr
        if usebcc:
            msg_root['Bcc'] = toaddr
            msg_root['To'] = 'Undisclosed.Recipients:'
        else:
            msg_root['To'] = toaddr
        msg_root.preamble = 'This is a multi-part message in MIME format.'

        msg_text = MIMEText(content, _charset=content_charset)
        msg_root.attach(msg_text)

        msg_text = MIMEText(html_content,
                            'html',
                            _charset=html_content_charset)
        if not html_images:
            # No image? Attach the HTML to the root
            msg_root.attach(msg_text)
        else:
            # Image(s)? Attach the HTML and image(s) as children of a
            # "related" block
            msg_related = MIMEMultipart('related')
            msg_related.attach(msg_text)
            for image_id, image_path in html_images.iteritems():
                msg_image = MIMEImage(open(image_path, 'rb').read())
                msg_image.add_header('Content-ID', '<%s>' % image_id)
                msg_image.add_header('Content-Disposition',
                                     'attachment',
                                     filename=os.path.split(image_path)[1])
                msg_related.attach(msg_image)
            msg_root.attach(msg_related)
    else:
        msg_root = MIMEText(content, _charset=content_charset)
        msg_root['From'] = fromaddr
        if usebcc:
            msg_root['Bcc'] = toaddr
            msg_root['To'] = 'Undisclosed.Recipients:'
        else:
            msg_root['To'] = toaddr
        msg_root['Subject'] = subject
    msg_root['User-Agent'] = 'Invenio %s at %s' % (CFG_VERSION, CFG_SITE_URL)
    return msg_root.as_string()
    def send(self, recipients=[]):
        """Sends the newsletter.
           An optional list of dicts (keys=fullname|mail) can be passed in
           for sending a newsletter out addresses != subscribers.
        """

        # preparations
        request = self.REQUEST

        # get hold of the parent Newsletter object#
        enl = self.getNewsletter()

        # get sender name
        sender_name = request.get("sender_name", "")
        if sender_name == "":
            sender_name = enl.getSenderName()
        # don't use Header() with a str and a charset arg, even if it is correct
        # this would generate a encoded header and mail server may not support utf-8 encoded header
        from_header = Header(safe_unicode(sender_name))

        # get sender e-mail
        sender_email = request.get("sender_email", "")
        if sender_email == "":
            sender_email = enl.getSenderEmail()
        from_header.append('<%s>' % safe_unicode(sender_email))

        # get subject
        subject = request.get("subject", "")
        if subject == "":
            subject = self.Title()
        subject_header = Header(safe_unicode(subject))

        # determine MailHost first (build-in vs. external)
        deliveryServiceName = enl.getDeliveryService()
        if deliveryServiceName == 'mailhost':
            MailHost = getToolByName(enl, 'MailHost')
        else:
            MailHost = getUtility(IMailHost, name=deliveryServiceName)
        log.info('Using mail delivery service "%r"' % MailHost)

        send_counter = 0
        send_error_counter = 0

        receivers = self._send_recipients(recipients)
        output_html = self._render_output_html()
        rendered_newsletter = self._exchange_relative_urls(output_html)
        text = rendered_newsletter['html']
        text_plain = rendered_newsletter['plain']
        image_urls = rendered_newsletter['images']
        props = getToolByName(self, "portal_properties").site_properties
        charset = props.getProperty("default_charset")
        portal = getSite()
        for receiver in receivers:
            # create multipart mail
            outer = MIMEMultipart('alternative')

            if hasattr(request, "test"):
                outer['To'] = Header('<%s>' % safe_unicode(receiver['email']))

                fullname = receiver['fullname']
                salutation = receiver['salutation']
                personal_text = text.replace("[[SUBSCRIBER_SALUTATION]]", "")
                personal_text_plain = text_plain.replace(
                    "[[SUBSCRIBER_SALUTATION]]", "")
                personal_text = text.replace("[[UNSUBSCRIBE]]", "")
                personal_text_plain = text_plain.replace("[[UNSUBSCRIBE]]", "")
            else:
                if 'uid' in receiver:
                    try:
                        unsubscribe_text = enl.getUnsubscribe_string()
                    except AttributeError:
                        unsubscribe_text = "Click here to unsubscribe"
                    unsubscribe_link = enl.absolute_url(
                    ) + "/unsubscribe?subscriber=" + receiver['uid']
                    personal_text = text.replace(
                        "[[UNSUBSCRIBE]]", """<a href="%s">%s.</a>""" %
                        (unsubscribe_link, unsubscribe_text))
                    personal_text_plain = text_plain.replace(
                        "[[UNSUBSCRIBE]]",
                        """\n%s: %s""" % (unsubscribe_text, unsubscribe_link))
                else:
                    personal_text = text.replace("[[UNSUBSCRIBE]]", "")
                    personal_text_plain = text_plain.replace(
                        "[[UNSUBSCRIBE]]", "")
                if 'salutation' in receiver:
                    salutation = receiver["salutation"]
                else:
                    salutation = ''
                fullname = receiver['fullname']
                if not fullname:
                    try:
                        fullname = enl.getFullname_fallback()
                    except AttributeError:
                        fullname = "Sir or Madam"
                outer['To'] = Header('<%s>' % safe_unicode(receiver['email']))

            subscriber_salutation = safe_portal_encoding(
                salutation) + ' ' + safe_portal_encoding(fullname)
            personal_text = personal_text.replace("[[SUBSCRIBER_SALUTATION]]",
                                                  str(subscriber_salutation))
            personal_text_plain = personal_text_plain.replace(
                "[[SUBSCRIBER_SALUTATION]]", str(subscriber_salutation))

            outer['From'] = from_header
            outer['Subject'] = subject_header
            outer.epilogue = ''

            # Attach text part
            text_part = MIMEText(personal_text_plain, "plain", charset)

            # Attach html part with images
            html_part = MIMEMultipart("related")
            html_text = MIMEText(personal_text, "html", charset)
            html_part.attach(html_text)

            # Add images to the message
            image_number = 0
            reference_tool = getToolByName(self, 'reference_catalog')
            for image_url in image_urls:
                try:
                    image_url = urlparse(image_url)[2]
                    if 'resolveuid' in image_url:
                        urlparts = image_url.split('/')[1:]
                        uuid = urlparts.pop(0)
                        o = reference_tool.lookupObject(uuid)
                        if o and urlparts:
                            # get thumb
                            o = o.restrictedTraverse(urlparts[0])
                    elif "@@images" in image_url:
                        image_url_base, image_scale_params = image_url.split(
                            "@@images")
                        image_scale = image_scale_params.split("/")[-1]
                        scales = self.restrictedTraverse(
                            urllib.unquote(
                                image_url_base.strip('/') + '/@@images'))
                        o = scales.scale('image', scale=image_scale)
                    else:
                        o = self.restrictedTraverse(urllib.unquote(image_url))
                except Exception, e:
                    log.error("Could not resolve the image \"%s\": %s" %
                              (image_url, e))
                else:
                    if hasattr(o, "_data"):  # file-based
                        image = MIMEImage(o._data)
                    elif hasattr(o, "data"):
                        image = MIMEImage(o.data)  # zodb-based
                    elif hasattr(o, "GET"):
                        image = MIMEImage(o.GET())  # z3 resource image
                    else:
                        log.error(
                            "Could not get the image data from image object!")
                    image["Content-ID"] = "<image_%s>" % image_number
                    image_number += 1
                    # attach images only to html parts
                    html_part.attach(image)
            outer.attach(text_part)
            outer.attach(html_part)

            try:
                #MailHost.send(msg)
                MailHost.send(outer.as_string())
                log.info("Send newsletter to \"%s\"" % receiver['email'])
                send_counter += 1
            except AttributeError:  # Plone3.3.x
                MailHost.send(msg.as_string())
                log.info("Send newsletter to \"%s\"" % receiver['email'])
                send_counter += 1
            except Exception, e:
                log.info(
                    "Sending newsletter to \"%s\" failed, with error \"%s\"!" %
                    (receiver['email'], e))
                send_error_counter += 1
Example #39
0
    def _send_raw_email(self):
        self.queue[self.current]['starttime'] = datetime.now()
        self.UIqueue[self.current]['formStarttime'] = self.queue[
            self.current]['starttime']
        # self.queue[self.current]['status'] = STAT_STARTED
        self.UIqueue[self.current]['stat'] = STAT_STARTED
        obj = self.queue[self.current]
        # create MIME message
        msg = MIMEMultipart()
        msg['Subject'] = self.queue[self.current]['subject']
        msg['Message-Id'] = make_msgid('calibre-web')
        msg['Date'] = formatdate(localtime=True)
        text = self.queue[self.current]['text']
        msg.attach(MIMEText(text.encode('UTF-8'), 'plain', 'UTF-8'))
        if obj['attachment']:
            result = get_attachment(obj['filepath'], obj['attachment'])
            if result:
                msg.attach(result)
            else:
                self._handleError(u"Attachment not found")
                return

        msg['From'] = obj['settings']["mail_from"]
        msg['To'] = obj['recipent']

        use_ssl = int(obj['settings'].get('mail_use_ssl', 0))
        try:
            # convert MIME message to string
            fp = StringIO()
            gen = Generator(fp, mangle_from_=False)
            gen.flatten(msg)
            msg = fp.getvalue()

            # send email
            timeout = 600  # set timeout to 5mins

            org_stderr = sys.stderr
            sys.stderr = StderrLogger()

            if use_ssl == 2:
                self.asyncSMTP = email_SSL(obj['settings']["mail_server"],
                                           obj['settings']["mail_port"],
                                           timeout)
            else:
                self.asyncSMTP = email(obj['settings']["mail_server"],
                                       obj['settings']["mail_port"], timeout)

            # link to logginglevel
            if web.ub.config.config_log_level != logging.DEBUG:
                self.asyncSMTP.set_debuglevel(0)
            else:
                self.asyncSMTP.set_debuglevel(1)
            if use_ssl == 1:
                self.asyncSMTP.starttls()
            if obj['settings']["mail_password"]:
                self.asyncSMTP.login(str(obj['settings']["mail_login"]),
                                     str(obj['settings']["mail_password"]))
            self.asyncSMTP.sendmail(obj['settings']["mail_from"],
                                    obj['recipent'], msg)
            self.asyncSMTP.quit()
            self._handleSuccess()
            sys.stderr = org_stderr

        except (MemoryError) as e:
            self._handleError(u'Error sending email: ' + e.message)
            return None
        except (smtplib.SMTPException, smtplib.SMTPAuthenticationError) as e:
            if hasattr(e, "smtp_error"):
                text = e.smtp_error.decode('utf-8').replace("\n", '. ')
            elif hasattr(e, "message"):
                text = e.message
            else:
                text = ''
            self._handleError(u'Error sending email: ' + text)
            return None
        except (socket.error) as e:
            self._handleError(u'Error sending email: ' + e.strerror)
            return None
        #attachment from Reports
        for rpt in reports:
            if len(rpt) == 3:
                rpt_file = createReport(cr, uid, rpt[0], rpt[1], rpt[2])
            elif len(rpt) == 2:
                rpt_file = createReport(cr, uid, rpt[0], rpt[1])
            attachments += rpt_file
        
        if isinstance(emailto, str) or isinstance(emailto, unicode):
            emailto = [emailto]

        ir_pool = self.pool.get('ir.attachment')

        for to in emailto:
            msg = MIMEMultipart()
            msg['Subject'] = tools.ustr(subject) 
            msg['To'] =  to
            msg['From'] = context.get('email_from', smtp_server.from_email)
            
            if body == False:
                body = ''
                            
            if smtp_server.disclaimers:
                body = body + "\n" + smtp_server.disclaimers
                
            try:
                msg.attach(MIMEText(body.encode(charset) or '', _charset=charset, _subtype="html"))
            except:
                msg.attach(MIMEText(body or '', _charset=charset, _subtype="html"))    
            
def start_photobooth():
    ################################# Begin Step 1 #################################
    print "Get Ready"
    camera = picamera.PiCamera()
    camera.resolution = (
        500, 375
    )  #use a smaller size to process faster, and tumblr will only take up to 500 pixels wide for animated gifs
    camera.vflip = True
    camera.hflip = True
    camera.saturation = -100
    camera.start_preview()
    i = 1  #iterate the blink of the light in prep, also gives a little time for the camera to warm up
    while i < prep_delay:
        GPIO.output(led1_pin, True)
        sleep(.5)
        GPIO.output(led1_pin, False)
        sleep(.5)
        i += 1
    ################################# Begin Step 2 #################################
    print "Taking pics"
    now = time.strftime(
        "%Y%m%d%H%M%S"
    )  #get the current date and time for the start of the filename
    try:  #take the photos
        for i, filename in enumerate(
                camera.capture_continuous(file_path + now + '-' +
                                          '{counter:02d}.jpg')):
            GPIO.output(led2_pin, True)  #turn on the LED
            print(filename)
            sleep(0.25)  #pause the LED on for just a bit
            GPIO.output(led2_pin, False)  #turn off the LED
            sleep(capture_delay)  # pause in-between shots
            if i == total_pics - 1:
                break
    finally:
        camera.stop_preview()
        camera.close()
    ########################### Begin Step 3 #################################
    print "Creating an animated gif"
    GPIO.output(led3_pin, True)  #turn on the LED
    graphicsmagick = "gm convert -delay " + str(
        gif_delay
    ) + " " + file_path + now + "*.jpg " + file_path + now + ".gif"
    os.system(graphicsmagick)  #make the .gif
    print "Uploading to tumblr. Please check " + tumblr_blog + " soon."
    connected = is_connected(
    )  #check to see if you have an internet connection
    while connected:
        try:
            msg = MIMEMultipart()
            msg['Subject'] = "Photo Booth " + now
            msg['From'] = addr_from
            msg['To'] = addr_to
            file_to_upload = file_path + now + ".gif"
            print file_to_upload
            fp = open(file_to_upload, 'rb')
            part = MIMEBase('image', 'gif')
            part.set_payload(fp.read())
            Encoders.encode_base64(part)
            part.add_header(
                'Content-Disposition',
                'attachment; filename="%s"' % os.path.basename(file_to_upload))
            fp.close()
            msg.attach(part)
            server = smtplib.SMTP('smtp.gmail.com:587')
            server.starttls()
            server.login(user_name, password)
            server.sendmail(msg['From'], msg['To'], msg.as_string())
            server.quit()
            break
        except ValueError:
            print "Oops. No internect connection. Upload later."
            try:  #make a text file as a note to upload the .gif later
                file = open(file_path + now + "-FILENOTUPLOADED.txt",
                            'w')  # Trying to create a new file or open one
                file.close()
            except:
                print('Something went wrong. Could not write file.')
                sys.exit(0)  # quit Python
    GPIO.output(led3_pin, False)  #turn off the LED
    ########################### Begin Step 4 #################################
    GPIO.output(led4_pin, True)  #turn on the LED
    try:
        display_pics(now)
    except Exception, e:
        tb = sys.exc_info()[2]
        traceback.print_exception(e.__class__, e, tb)
Example #42
0
def alert_smtp(alert, metric, context):
    """
    Called by :func:`~trigger_alert` and sends an alert via smtp to the
    recipients that are configured for the metric.

    """
    LOCAL_DEBUG = False
    logger = logging.getLogger(skyline_app_logger)
    if settings.ENABLE_DEBUG or LOCAL_DEBUG:
        logger.info('debug :: alert_smtp - sending smtp alert')
        logger.info('debug :: alert_smtp - Memory usage at start: %s (kb)' %
                    resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)

    # FULL_DURATION to hours so that analyzer surfaces the relevant timeseries data
    # in the graph
    full_duration_in_hours = int(settings.FULL_DURATION) / 3600

    # @added 20161229 - Feature #1830: Ionosphere alerts
    # Added Ionosphere variables
    base_name = str(metric[1]).replace(settings.FULL_NAMESPACE, '', 1)
    if settings.IONOSPHERE_ENABLED:
        timeseries_dir = base_name.replace('.', '/')
        training_data_dir = '%s/%s/%s' % (settings.IONOSPHERE_DATA_FOLDER,
                                          str(int(metric[2])), timeseries_dir)
        graphite_image_file = '%s/%s.%s.graphite.%sh.png' % (
            training_data_dir, base_name, skyline_app,
            str(int(full_duration_in_hours)))
        json_file = '%s/%s.%s.redis.%sh.json' % (
            training_data_dir, base_name, skyline_app,
            str(int(full_duration_in_hours)))
        training_data_redis_image = '%s/%s.%s.redis.plot.%sh.png' % (
            training_data_dir, base_name, skyline_app,
            str(int(full_duration_in_hours)))

    # For backwards compatibility
    if '@' in alert[1]:
        sender = settings.ALERT_SENDER
        recipient = alert[1]
    else:
        sender = settings.SMTP_OPTS['sender']
        # @modified 20160806 - Added default_recipient
        try:
            recipients = settings.SMTP_OPTS['recipients'][alert[0]]
            use_default_recipient = False
        except:
            use_default_recipient = True
        if use_default_recipient:
            try:
                recipients = settings.SMTP_OPTS['default_recipient']
                logger.info(
                    'alert_smtp - using default_recipient as no recipients are configured for %s'
                    % str(alert[0]))
            except:
                logger.error(
                    'error :: alert_smtp - no known recipient for %s' %
                    str(alert[0]))
                return False

    # Backwards compatibility
    if type(recipients) is str:
        recipients = [recipients]

    # @modified 20161229 - Feature #1830: Ionosphere alerts
    # Ionosphere alerts
    unencoded_graph_title = 'Skyline %s - ALERT at %s hours - %s' % (
        context, str(int(full_duration_in_hours)), str(metric[0]))
    # @modified 20170603 - Feature #2034: analyse_derivatives
    # Added deriative functions to convert the values of metrics strictly
    # increasing monotonically to their deriative products in alert graphs and
    # specify it in the graph_title
    known_derivative_metric = False
    try:
        REDIS_ALERTER_CONN = redis.StrictRedis(
            unix_socket_path=settings.REDIS_SOCKET_PATH)
    except:
        logger.error('error :: alert_smtp - redis connection failed')
    try:
        derivative_metrics = list(
            REDIS_ALERTER_CONN.smembers('derivative_metrics'))
    except:
        derivative_metrics = []
    redis_metric_name = '%s%s' % (settings.FULL_NAMESPACE, str(base_name))
    if redis_metric_name in derivative_metrics:
        known_derivative_metric = True
    if known_derivative_metric:
        try:
            non_derivative_monotonic_metrics = settings.NON_DERIVATIVE_MONOTONIC_METRICS
        except:
            non_derivative_monotonic_metrics = []
        skip_derivative = in_list(redis_metric_name,
                                  non_derivative_monotonic_metrics)
        if skip_derivative:
            known_derivative_metric = False
    if known_derivative_metric:
        unencoded_graph_title = 'Skyline %s - ALERT at %s hours - derivative graph - %s' % (
            context, str(int(full_duration_in_hours)), str(metric[0]))

    if settings.ENABLE_DEBUG or LOCAL_DEBUG:
        logger.info('debug :: alert_smtp - unencoded_graph_title: %s' %
                    unencoded_graph_title)
    graph_title_string = quote(unencoded_graph_title, safe='')
    graph_title = '&title=%s' % graph_title_string

    graphite_port = '80'
    if settings.GRAPHITE_PORT != '':
        graphite_port = str(settings.GRAPHITE_PORT)

    link = '%s://%s:%s/render/?from=-%shours&target=cactiStyle(%s)%s%s&colorList=orange' % (
        settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, graphite_port,
        str(int(full_duration_in_hours)), metric[1],
        settings.GRAPHITE_GRAPH_SETTINGS, graph_title)
    # @added 20170603 - Feature #2034: analyse_derivatives
    if known_derivative_metric:
        link = '%s://%s:%s/render/?from=-%shours&target=cactiStyle(nonNegativeDerivative(%s))%s%s&colorList=orange' % (
            settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, graphite_port,
            str(int(full_duration_in_hours)), metric[1],
            settings.GRAPHITE_GRAPH_SETTINGS, graph_title)

    content_id = metric[1]
    image_data = None
    if settings.SMTP_OPTS.get('embed-images'):
        # @added 20161229 - Feature #1830: Ionosphere alerts
        # Use existing data if files exist
        if os.path.isfile(graphite_image_file):
            try:
                with open(graphite_image_file, 'r') as f:
                    image_data = f.read()
                logger.info('alert_smtp - using existing png - %s' %
                            graphite_image_file)
            except:
                logger.error(traceback.format_exc())
                logger.error(
                    'error :: alert_smtp - failed to read image data from existing png - %s'
                    % graphite_image_file)
                logger.error('error :: alert_smtp - %s' % str(link))
                image_data = None

        if image_data is None:
            try:
                # @modified 20170913 - Task #2160: Test skyline with bandit
                # Added nosec to exclude from bandit tests
                image_data = urllib2.urlopen(link).read()  # nosec
                if settings.ENABLE_DEBUG or LOCAL_DEBUG:
                    logger.info('debug :: alert_smtp - image data OK')
            except urllib2.URLError:
                logger.error(traceback.format_exc())
                logger.error('error :: alert_smtp - failed to get image graph')
                logger.error('error :: alert_smtp - %s' % str(link))
                image_data = None
                if settings.ENABLE_DEBUG or LOCAL_DEBUG:
                    logger.info('debug :: alert_smtp - image data None')

    if LOCAL_DEBUG:
        logger.info(
            'debug :: alert_smtp - Memory usage after image_data: %s (kb)' %
            resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)

    # If we failed to get the image or if it was explicitly disabled,
    # use the image URL instead of the content.
    if image_data is None:
        img_tag = '<img src="%s"/>' % link
    else:
        img_tag = '<img src="cid:%s"/>' % content_id
        if settings.ENABLE_DEBUG or LOCAL_DEBUG:
            logger.info('debug :: alert_smtp - img_tag: %s' % img_tag)

        if settings.IONOSPHERE_ENABLED:
            # Create Ionosphere Graphite image
            # @modified 20161229 - Feature #1830: Ionosphere alerts
            # Only write the data to the file if it does not exist
            if not os.path.isfile(graphite_image_file):
                try:
                    write_data_to_file(skyline_app, graphite_image_file, 'w',
                                       image_data)
                    logger.info('added %s Ionosphere Graphite image :: %s' %
                                (skyline_app, graphite_image_file))
                except:
                    logger.info(traceback.format_exc())
                    logger.error(
                        'error :: failed to add %s Ionosphere Graphite image' %
                        (skyline_app, graphite_image_file))
            else:
                logger.info(
                    '%s Ionosphere Graphite image already exists :: %s' %
                    (skyline_app, graphite_image_file))

    redis_image_data = None
    try:
        plot_redis_data = settings.PLOT_REDIS_DATA
    except:
        plot_redis_data = False

    if settings.SMTP_OPTS.get('embed-images') and plot_redis_data:
        # Create graph from Redis data
        redis_metric_key = '%s%s' % (settings.FULL_NAMESPACE, metric[1])
        try:
            raw_series = REDIS_ALERTER_CONN.get(redis_metric_key)
            if settings.ENABLE_DEBUG or LOCAL_DEBUG:
                logger.info('debug :: alert_smtp - raw_series: %s' % 'OK')
        except:
            if settings.ENABLE_DEBUG or LOCAL_DEBUG:
                logger.info('debug :: alert_smtp - raw_series: %s' % 'FAIL')

        try:
            if LOCAL_DEBUG:
                logger.info(
                    'debug :: alert_smtp - Memory usage before get Redis timeseries data: %s (kb)'
                    % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
            unpacker = Unpacker(use_list=True)
            unpacker.feed(raw_series)
            timeseries_x = [float(item[0]) for item in unpacker]
            unpacker = Unpacker(use_list=True)
            unpacker.feed(raw_series)
            timeseries_y = [item[1] for item in unpacker]

            unpacker = Unpacker(use_list=False)
            unpacker.feed(raw_series)
            timeseries = list(unpacker)
            if LOCAL_DEBUG:
                logger.info(
                    'debug :: alert_smtp - Memory usage after get Redis timeseries data: %s (kb)'
                    % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
        except:
            logger.error('error :: alert_smtp - unpack timeseries failed')
            timeseries = None

        if settings.IONOSPHERE_ENABLED and timeseries:
            '''
            .. todo: this is possibly to be used to allow the user to submit the
                FULL_DURATION duration data set for the features profile to be
                created against IF it is a Mirage metric.  This would allow for
                additional granularity in Mirage metrics, thereby maintaining
                their seasonality, but allow user and Skyline to analyze the
                anomaly at a FULL_DURATION resolution as well.  Not sure how to
                code that in Ionosphere context yet but could just be additonal
                flag in the Ionosphere record.  In the Ionosphere frontend, the
                user would be given an option to either create the features
                profile on the Mirage timeseries or the redis FULL_DURATION
                timeseries.  It is a little complicated, but doable.
                # @modified 20161229 - Feature #1828: ionosphere - mirage Redis data features
                However that ^^ is UNDESIRABLE in the Mirage/Ionosphere context
                at the moment.  Ionosphere must only profile SECOND_ORDER_RESOLUTION_HOURS
                currently so as to not pollute the seasonality aspect of Mirage
            '''
            # Create Ionosphere redis timeseries json if is does not exist
            # @modified 20161229 - Feature #1830: Ionosphere alerts
            # Only write the data to the file if it does not exist and replace
            # the timeseries object if a json file exists

            # @added 20170920 - Bug #2168: Strange Redis derivative graph
            using_original_redis_json = False

            if not os.path.isfile(json_file):
                timeseries_json = str(timeseries).replace('[', '(').replace(
                    ']', ')')
                try:
                    write_data_to_file(skyline_app, json_file, 'w',
                                       timeseries_json)
                    logger.info(
                        'added %s Ionosphere Redis data timeseries json file :: %s'
                        % (skyline_app, json_file))
                except:
                    logger.info(traceback.format_exc())
                    logger.error(
                        'error :: failed to add %s Ionosphere Redis data timeseries json file'
                        % (skyline_app, json_file))
            else:
                # Replace the timeseries object
                logger.info(
                    '%s Ionosphere Redis data timeseries json file already exists, using :: %s'
                    % (skyline_app, json_file))
                anomaly_json = json_file
                try:
                    # Read the timeseries json file
                    with open(anomaly_json, 'r') as f:
                        raw_timeseries = f.read()
                    timeseries_array_str = str(raw_timeseries).replace(
                        '(', '[').replace(')', ']')
                    timeseries = literal_eval(timeseries_array_str)
                    logger.info(
                        '%s Redis timeseries replaced with timeseries from :: %s'
                        % (skyline_app, anomaly_json))
                    timeseries_x = [float(item[0]) for item in timeseries]
                    timeseries_y = [item[1] for item in timeseries]
                    # @added 20170920 - Bug #2168: Strange Redis derivative graph
                    # This already has nonNegativeDerivative applied to it
                    using_original_redis_json = True
                except:
                    logger.error(traceback.format_exc())
                    logger.error(
                        'error :: %s failed to read timeseries data from %s' %
                        (skyline_app, anomaly_json))
                    timeseries = None

        # @added 20170603 - Feature #2034: analyse_derivatives
        if known_derivative_metric:

            # @added 20170920 - Bug #2168: Strange Redis derivative graph
            # If this is the Mirage Redis json it already has
            # nonNegativeDerivative applied to it
            if not using_original_redis_json:
                logger.info('alert_smtp - nonNegativeDerivative being applied')

                try:
                    derivative_timeseries = nonNegativeDerivative(timeseries)
                    timeseries = derivative_timeseries
                    # @added 20170920 - Bug #2168: Strange Redis derivative graph
                    logger.info('alert_smtp - nonNegativeDerivative applied')
                except:
                    logger.error(
                        'error :: alert_smtp - nonNegativeDerivative failed')
            else:
                logger.info(
                    'alert_smtp - nonNegativeDerivative not being applied, as it will have been applied in the original json'
                )

        # @added 21070726 - Bug #2068: Analyzer smtp alert error on Redis plot with derivative metrics
        # If the nonNegativeDerivative has been calculated we need to reset the
        # x and y as nonNegativeDerivative has to discard the first value as it
        # has no delta for it so the timeseries is 1 item less.
        timeseries_x = [float(item[0]) for item in timeseries]
        timeseries_y = [item[1] for item in timeseries]

        pd_series_values = None
        if timeseries:
            try:
                if LOCAL_DEBUG:
                    logger.info(
                        'debug :: alert_smtp - Memory usage before pd.Series: %s (kb)'
                        % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
                values = pd.Series([x[1] for x in timeseries])
                # Because the truth value of a Series is ambiguous
                pd_series_values = True
                if LOCAL_DEBUG:
                    logger.info(
                        'debug :: alert_smtp - Memory usage after pd.Series: %s (kb)'
                        % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
            except:
                logger.error(
                    'error :: alert_smtp - pandas value series on timeseries failed'
                )

        if pd_series_values:
            try:
                array_median = np.median(values)
                if settings.ENABLE_DEBUG or LOCAL_DEBUG:
                    logger.info('debug :: alert_smtp - values median: %s' %
                                str(array_median))

                array_amax = np.amax(values)
                if settings.ENABLE_DEBUG or LOCAL_DEBUG:
                    logger.info('debug :: alert_smtp - array_amax: %s' %
                                str(array_amax))
                array_amin = np.amin(values)
                if settings.ENABLE_DEBUG or LOCAL_DEBUG:
                    logger.info('debug :: alert_smtp - array_amin: %s' %
                                str(array_amin))
                mean = values.mean()
                if settings.ENABLE_DEBUG or LOCAL_DEBUG:
                    logger.info('debug :: alert_smtp - mean: %s' % str(mean))
                stdDev = values.std()
                if settings.ENABLE_DEBUG or LOCAL_DEBUG:
                    logger.info('debug :: alert_smtp - stdDev: %s' %
                                str(stdDev))

                sigma3 = 3 * stdDev
                if settings.ENABLE_DEBUG or LOCAL_DEBUG:
                    logger.info('debug :: alert_smtp - sigma3: %s' %
                                str(sigma3))

                # sigma3_series = [sigma3] * len(values)

                sigma3_upper_bound = mean + sigma3
                try:
                    sigma3_lower_bound = mean - sigma3
                except:
                    sigma3_lower_bound = 0

                sigma3_upper_series = [sigma3_upper_bound] * len(values)
                sigma3_lower_series = [sigma3_lower_bound] * len(values)
                amax_series = [array_amax] * len(values)
                amin_series = [array_amin] * len(values)
                mean_series = [mean] * len(values)
            except:
                logger.error(
                    'error :: alert_smtp - numpy ops on series failed')
                mean_series = None

        if mean_series:
            graph_title = 'Skyline %s - ALERT - at %s hours - Redis data\n%s - anomalous value: %s' % (
                context, str(
                    int(full_duration_in_hours)), metric[1], str(metric[0]))
            # @added 20170603 - Feature #2034: analyse_derivatives
            if known_derivative_metric:
                graph_title = 'Skyline %s - ALERT - at %s hours - Redis data (derivative graph)\n%s - anomalous value: %s' % (
                    context, str(int(full_duration_in_hours)), metric[1],
                    str(metric[0]))

            # @modified 20160814 - Bug #1558: Memory leak in Analyzer
            # I think the buf is causing a memory leak, trying a file
            # if python_version == 3:
            #     buf = io.StringIO()
            # else:
            #     buf = io.BytesIO()
            buf = '%s/%s.%s.%s.png' % (settings.SKYLINE_TMP_DIR, skyline_app,
                                       str(int(metric[2])), metric[1])

            if LOCAL_DEBUG:
                logger.info(
                    'debug :: alert_smtp - Memory usage before plot Redis data: %s (kb)'
                    % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)

            # Too big
            # rcParams['figure.figsize'] = 12, 6
            rcParams['figure.figsize'] = 8, 4
            try:
                # fig = plt.figure()
                fig = plt.figure(frameon=False)
                ax = fig.add_subplot(111)
                ax.set_title(graph_title, fontsize='small')
                ax.set_axis_bgcolor('black')
                try:
                    datetimes = [
                        dt.datetime.utcfromtimestamp(ts) for ts in timeseries_x
                    ]
                    if settings.ENABLE_DEBUG or LOCAL_DEBUG:
                        logger.info('debug :: alert_smtp - datetimes: %s' %
                                    'OK')
                except:
                    logger.error('error :: alert_smtp - datetimes: %s' %
                                 'FAIL')

                plt.xticks(rotation=0, horizontalalignment='center')
                xfmt = DateFormatter('%a %H:%M')
                plt.gca().xaxis.set_major_formatter(xfmt)

                ax.xaxis.set_major_formatter(xfmt)

                ax.plot(datetimes,
                        timeseries_y,
                        color='orange',
                        lw=0.6,
                        zorder=3)
                ax.tick_params(axis='both', labelsize='xx-small')

                max_value_label = 'max - %s' % str(array_amax)
                ax.plot(datetimes,
                        amax_series,
                        lw=1,
                        label=max_value_label,
                        color='m',
                        ls='--',
                        zorder=4)
                min_value_label = 'min - %s' % str(array_amin)
                ax.plot(datetimes,
                        amin_series,
                        lw=1,
                        label=min_value_label,
                        color='b',
                        ls='--',
                        zorder=4)
                mean_value_label = 'mean - %s' % str(mean)
                ax.plot(datetimes,
                        mean_series,
                        lw=1.5,
                        label=mean_value_label,
                        color='g',
                        ls='--',
                        zorder=4)

                sigma3_text = (r'3$\sigma$')
                # sigma3_label = '%s - %s' % (str(sigma3_text), str(sigma3))

                sigma3_upper_label = '%s upper - %s' % (
                    str(sigma3_text), str(sigma3_upper_bound))
                ax.plot(datetimes,
                        sigma3_upper_series,
                        lw=1,
                        label=sigma3_upper_label,
                        color='r',
                        ls='solid',
                        zorder=4)

                if sigma3_lower_bound > 0:
                    sigma3_lower_label = '%s lower - %s' % (
                        str(sigma3_text), str(sigma3_lower_bound))
                    ax.plot(datetimes,
                            sigma3_lower_series,
                            lw=1,
                            label=sigma3_lower_label,
                            color='r',
                            ls='solid',
                            zorder=4)

                ax.get_yaxis().get_major_formatter().set_useOffset(False)
                ax.get_yaxis().get_major_formatter().set_scientific(False)

                # Shrink current axis's height by 10% on the bottom
                box = ax.get_position()
                ax.set_position([
                    box.x0, box.y0 + box.height * 0.1, box.width,
                    box.height * 0.9
                ])

                # Put a legend below current axis
                ax.legend(loc='upper center',
                          bbox_to_anchor=(0.5, -0.05),
                          fancybox=True,
                          shadow=True,
                          ncol=4,
                          fontsize='x-small')
                plt.rc('lines', lw=2, color='w')

                plt.grid(True)

                ax.grid(b=True,
                        which='both',
                        axis='both',
                        color='lightgray',
                        linestyle='solid',
                        alpha=0.5,
                        linewidth=0.6)
                ax.set_axis_bgcolor('black')

                rcParams['xtick.direction'] = 'out'
                rcParams['ytick.direction'] = 'out'
                ax.margins(y=.02, x=.03)
                # tight_layout removes the legend box
                # fig.tight_layout()
                try:
                    if LOCAL_DEBUG:
                        logger.info(
                            'debug :: alert_smtp - Memory usage before plt.savefig: %s (kb)'
                            %
                            resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
                    plt.savefig(buf, format='png')

                    if settings.IONOSPHERE_ENABLED:
                        if not os.path.exists(training_data_dir):
                            mkdir_p(training_data_dir)
                            logger.info('created dir - %s' % training_data_dir)

                        if not os.path.isfile(training_data_redis_image):
                            try:
                                plt.savefig(training_data_redis_image,
                                            format='png')
                                logger.info(
                                    'alert_smtp - save Redis training data image - %s'
                                    % (training_data_redis_image))
                            except:
                                logger.info(traceback.format_exc())
                                logger.error(
                                    'error :: alert_smtp - could not save - %s'
                                    % (training_data_redis_image))
                        else:
                            logger.info(
                                'alert_smtp - Redis training data image already exists - %s'
                                % (training_data_redis_image))

                    # @added 20160814 - Bug #1558: Memory leak in Analyzer
                    # As per http://www.mail-archive.com/[email protected]/msg13222.html
                    # savefig in the parent process was causing the memory leak
                    # the below fig.clf() and plt.close() did not resolve this
                    # however spawing a multiprocessing process for alert_smtp
                    # does solve this as issue as all memory is freed when the
                    # process terminates.
                    fig.clf()
                    plt.close(fig)
                    redis_graph_content_id = 'redis.%s' % metric[1]
                    redis_image_data = True
                    if settings.ENABLE_DEBUG or LOCAL_DEBUG:
                        logger.info('debug :: alert_smtp - savefig: %s' % 'OK')
                        logger.info(
                            'debug :: alert_smtp - Memory usage after plt.savefig: %s (kb)'
                            %
                            resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
                except:
                    logger.info(traceback.format_exc())
                    logger.error('error :: alert_smtp - plt.savefig: %s' %
                                 'FAIL')
            except:
                logger.error(traceback.format_exc())
                logger.error('error :: alert_smtp - could not build plot')

    if LOCAL_DEBUG:
        logger.info(
            'debug :: alert_smtp - Memory usage before email: %s (kb)' %
            resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)

    if redis_image_data:
        redis_img_tag = '<img src="cid:%s"/>' % redis_graph_content_id
        if settings.ENABLE_DEBUG or LOCAL_DEBUG:
            logger.info('debug :: alert_smtp - redis_img_tag: %s' %
                        str(redis_img_tag))
    else:
        # @modified 20161229 - Feature #1830: Ionosphere alerts
        # @modified 20170108 - Feature #1852: Ionosphere - features_profile matched graphite graphs
        # Restored the previous redis_img_tag method as some smtp alerts were
        # coming without a Redis graph, not all but some and for some reason,
        # I am pretty certain retrospectively that it was done that way from
        # testing I just wanted to try and be cleaner.
        # The redis_img_tag was changed at
        # https://github.com/earthgecko/skyline/commit/31bcacf3f90f0953ebed0d57260cb937e01f887c#diff-520bf2a218f65074ffead4d8184c138dR489
        redis_img_tag = '<img src="%s"/>' % 'none'
        # redis_img_tag = '<img src="none"/>'

    # @added 20170806 - Feature #1830: Ionosphere alerts
    # Show a human date in alerts
    alerted_at = str(dt.datetime.utcfromtimestamp(int(metric[2])))

    try:
        body = '<h3><font color="#dd3023">Sky</font><font color="#6698FF">line</font><font color="black"> %s alert</font></h3><br>' % context
        body += '<font color="black">metric: <b>%s</b></font><br>' % metric[1]
        body += '<font color="black">Anomalous value: %s</font><br>' % str(
            metric[0])
        body += '<font color="black">Anomaly timestamp: %s</font><br>' % str(
            int(metric[2]))
        # @added 20170806 - Feature #1830: Ionosphere alerts
        # Show a human date in alerts
        body += '<font color="black">Anomalous at: %s</font><br>' % alerted_at
        body += '<font color="black">At hours: %s</font><br>' % str(
            int(full_duration_in_hours))
        body += '<font color="black">Next alert in: %s seconds</font><br>' % str(
            alert[2])
        # @added 20170603 - Feature #2034: analyse_derivatives
        if known_derivative_metric:
            body += '<font color="black">Derivative graph: True</font><br>'

        more_body = ''
        if settings.IONOSPHERE_ENABLED:
            # @modified 20170823 - Bug #2142: 7bit SMTP encoding breaking long urls
            # Broke body into body and more_body to workaround the 990 character
            # limit per line for SMTP
            more_body += '<h3><font color="#dd3023">Ionosphere :: </font><font color="#6698FF">training data</font><font color="black"></font></h3>'
            ionosphere_link = '%s/ionosphere?timestamp=%s&metric=%s' % (
                settings.SKYLINE_URL, str(int(metric[2])), str(metric[1]))
            more_body += '<font color="black">To use this timeseries to train Skyline that this is not anomalous manage this training data at:<br>'
            more_body += '<a href="%s">%s</a></font>' % (ionosphere_link,
                                                         ionosphere_link)
        if redis_image_data:
            more_body += '<font color="black">min: %s  | max: %s   | mean: %s <br>' % (
                str(array_amin), str(array_amax), str(mean))
            more_body += '3-sigma: %s <br>' % str(sigma3)
            more_body += '3-sigma upper bound: %s   | 3-sigma lower bound: %s <br></font>' % (
                str(sigma3_upper_bound), str(sigma3_lower_bound))
            more_body += '<h3><font color="black">Redis data at FULL_DURATION</font></h3><br>'
            more_body += '<div dir="ltr">:%s<br></div>' % redis_img_tag
        if image_data:
            more_body += '<h3><font color="black">Graphite data at FULL_DURATION (may be aggregated)</font></h3>'
            more_body += '<div dir="ltr"><a href="%s">%s</a><br></div><br>' % (
                link, img_tag)
            more_body += '<font color="black">Clicking on the above graph will open to the Graphite graph with current data</font><br>'
        if redis_image_data:
            more_body += '<font color="black">To disable the Redis data graph view, set PLOT_REDIS_DATA to False in your settings.py, if the Graphite graph is sufficient for you,<br>'
            more_body += 'however do note that will remove the 3-sigma and mean value too.</font>'
        more_body += '<br>'
        more_body += '<div dir="ltr" align="right"><font color="#dd3023">Sky</font><font color="#6698FF">line</font><font color="black"> version :: %s</font></div><br>' % str(
            skyline_version)
    except:
        logger.error('error :: alert_smtp - could not build body')
        logger.info(traceback.format_exc())

    for recipient in recipients:
        try:
            # @modified 20170823 - Bug #2142: 7bit SMTP encoding breaking long urls
            # Broke body into body and more_body to workaround the 990 character
            # limit per line for SMTP, using mixed as alternative indicates that
            # the client should select one of the parts for display and ignore
            # the rest (tripleee - https://stackoverflow.com/a/35115938)
            # msg = MIMEMultipart('alternative')
            msg = MIMEMultipart('mixed')

            # @added 20170812 - Bug #2142: 7bit SMTP encoding breaking long urls
            # set email charset and email encodings
            cs_ = charset.Charset('utf-8')
            cs_.header_encoding = charset.QP
            cs_.body_encoding = charset.QP
            msg.set_charset(cs_)

            msg['Subject'] = '[Skyline alert] - %s ALERT - %s' % (context,
                                                                  metric[1])
            msg['From'] = sender
            msg['To'] = recipient

            msg.attach(MIMEText(body, 'html'))
            # @added 20170823 - Bug #2142: 7bit SMTP encoding breaking long urls
            # Broke body into body and more_body to workaround the 990 character
            # limit per line for SMTP
            msg.replace_header('content-transfer-encoding', 'quoted-printable')
            msg.attach(MIMEText(more_body, 'html'))

            if redis_image_data:
                try:
                    # @modified 20160814 - Bug #1558: Memory leak in Analyzer
                    # I think the buf is causing a memory leak, trying a file
                    # buf.seek(0)
                    # msg_plot_attachment = MIMEImage(buf.read())
                    # msg_plot_attachment = MIMEImage(buf.read())
                    try:
                        with open(buf, 'r') as f:
                            plot_image_data = f.read()
                        try:
                            os.remove(buf)
                        except OSError:
                            logger.error(
                                'error :: alert_smtp - failed to remove file - %s'
                                % buf)
                            logger.info(traceback.format_exc())
                            pass
                    except:
                        logger.error('error :: failed to read plot file - %s' %
                                     buf)
                        plot_image_data = None

                    # @added 20161124 - Branch #922: ionosphere
                    msg_plot_attachment = MIMEImage(plot_image_data)
                    msg_plot_attachment.add_header(
                        'Content-ID', '<%s>' % redis_graph_content_id)
                    msg.attach(msg_plot_attachment)
                    if settings.ENABLE_DEBUG or LOCAL_DEBUG:
                        logger.info(
                            'debug :: alert_smtp - msg_plot_attachment - redis data done'
                        )
                except:
                    logger.error('error :: alert_smtp - msg_plot_attachment')
                    logger.info(traceback.format_exc())

            if image_data is not None:
                try:
                    msg_attachment = MIMEImage(image_data)
                    msg_attachment.add_header('Content-ID',
                                              '<%s>' % content_id)
                    msg.attach(msg_attachment)
                    if settings.ENABLE_DEBUG or LOCAL_DEBUG:
                        logger.info(
                            'debug :: alert_smtp - msg_attachment - Graphite img source done'
                        )
                except:
                    logger.error('error :: alert_smtp - msg_attachment')
                    logger.info(traceback.format_exc())
        except:
            logger.error('error :: alert_smtp - could not attach')
            logger.info(traceback.format_exc())

        s = SMTP('127.0.0.1')
        try:
            s.sendmail(sender, recipient, msg.as_string())
            if settings.ENABLE_DEBUG or LOCAL_DEBUG:
                logger.info('debug :: alert_smtp - message sent to %s OK' %
                            str(recipient))
        except:
            logger.error('error :: alert_smtp - could not send email to %s' %
                         str(recipient))
            logger.info(traceback.format_exc())

        s.quit()

        if LOCAL_DEBUG:
            logger.info(
                'debug :: alert_smtp - Memory usage after email: %s (kb)' %
                resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)

        if redis_image_data:
            # buf.seek(0)
            # buf.write('none')
            if LOCAL_DEBUG:
                logger.info(
                    'debug :: alert_smtp - Memory usage before del redis_image_data objects: %s (kb)'
                    % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
            del raw_series
            del unpacker
            del timeseries[:]
            del timeseries_x[:]
            del timeseries_y[:]
            del values
            del datetimes[:]
            del msg_plot_attachment
            del redis_image_data
            # We del all variables that are floats as they become unique objects and
            # can result in what appears to be a memory leak, but is not, it is
            # just the way Python handles floats
            del mean
            del array_amin
            del array_amax
            del stdDev
            del sigma3
            if LOCAL_DEBUG:
                logger.info(
                    'debug :: alert_smtp - Memory usage after del redis_image_data objects: %s (kb)'
                    % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
            if LOCAL_DEBUG:
                logger.info(
                    'debug :: alert_smtp - Memory usage before del fig object: %s (kb)'
                    % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
            # @added 20160814 - Bug #1558: Memory leak in Analyzer
            #                   Issue #21 Memory leak in Analyzer - https://github.com/earthgecko/skyline/issues/21
            # As per http://www.mail-archive.com/[email protected]/msg13222.html
            fig.clf()
            plt.close(fig)
            del fig
            if LOCAL_DEBUG:
                logger.info(
                    'debug :: alert_smtp - Memory usage after del fig object: %s (kb)'
                    % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)

        if LOCAL_DEBUG:
            logger.info(
                'debug :: alert_smtp - Memory usage before del other objects: %s (kb)'
                % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
        del recipients[:]
        del body
        del msg
        del image_data
        del msg_attachment
        if LOCAL_DEBUG:
            logger.info(
                'debug :: alert_smtp - Memory usage after del other objects: %s (kb)'
                % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
        return
Example #43
0
 def __setitem__(self, name, val):
     name, val = forbid_multi_line_headers(name, val, self.encoding)
     MIMEMultipart.__setitem__(self, name, val)
Example #44
0
def welcome_email(user_email, wallet, uuid):
    if user_email is not None:
        msg = MIMEMultipart('alternative')
        msg['From'] = email_from
        msg['To'] = user_email
        msg['Subject'] = "Welcome to Omniwallet"

        text = (
            'Welcome To Omniwallet!\n'
            '\n'
            'Thank you for creating a new wallet and choosing to join the exciting world of cryptocurrency.\n'
            'While we know you are eager to get started, this email contains important information about your new Omniwallet.\n'
            'So please take a moment to read through it completely.\n'
            '\n'
            'Your Wallet Login Details'
            'This is your Wallet ID: ' + str(uuid) + '\n'
            'Never share your Wallet ID or Password with anyone. Be sure to keep them safe and stored separately for security.\n\n'
            'This is your unique Login Link: https://' + str(email_domain) +
            '/login/' + str(uuid) + '\n'
            'Bookmark this, you can use it to login directly to your Omniwallet with your password.\n'
            '\n'
            'Omniwallet NEVER STORES Your Password.\n'
            'This means you need your password to access your wallet and the private keys within.\n'
            'If you lose or forget your password there is nothing we can do to recover it.\n'
            'This may result in the loss of funds in any wallet addresses which have not been Backed Up!\n\n'
            'Please, Please, Please Keep Your Password Safe!\n'
            '\n'
            'Important Information On Backing Up Your Wallet'
            'If you lose or forget your password the only thing you can use to recover your funds is a Wallet Backup.\n'
            'You should create a new backup any time you make a change to your wallet (add/remove an address).\n'
            'Remove the old backup only after you have confirmed the contents of the new backup are complete.\n'
            'On the "My Addresses" page you can export a backup of your wallet under the "Wallet Options" button.\n'
            'This backup file contains every address and private key (if known) for the addresses in your wallet at the time of backup.\n'
            'Store your backup file in a secure place. Anyone with access to this file has access to your funds.'
            '\n'
            'Thank you for taking the time to read this introduction. \n'
            'This as well as many more questions/answers are available on our FAQ Page: https://'
            + str(email_domain) + '/about/faq \n'
            'If you have any questions please feel free to reach out to us using the information on our Contact Us page: https://'
            + str(email_domain) + '/about/contact \n'
            '\n'
            'Sincerely, \n The Omniwallet Team')

        html = (
            '<html><head></head><body style="background-color:rgba(234, 235, 236, 0.43);">'
            '<img src="https://' + str(email_domain) +
            '/assets/img/logo.png"><h1><font color="#034F92">Welcome To Omniwallet!</font></h1>'
            '<p>'
            'Thank you for creating a new wallet and choosing to join the exciting world of cryptocurrency.<br>'
            'While we know you are eager to get started, this email contains important information about your new Omniwallet.<br>'
            'So please take a moment to read through it completely.<br>'
            '</p>'
            '<h2><font color="#034F92">Your Wallet Login Details</font></h2>'
            '<p>'
            'This is your <b>Wallet ID:</b> ' + str(uuid) + '<br>'
            'Never share your Wallet ID or Password with anyone. Be sure to keep them safe and stored separately for security.<br><br>'
            'This is your unique <b>Login Link:</b> <a href="https://' +
            str(email_domain) + '/login/' + str(uuid) + '">https://' +
            str(email_domain) + '/login/' + str(uuid) + '</a><br>'
            'Bookmark this, you can use it to login directly to your Omniwallet with your password.<br>'
            '</p><p>'
            '<strong>Omniwallet Never Stores Your Password.</strong><br>'
            'This means you need your password to access your wallet and the private keys within.<br>'
            'If you lose or forget your password there is nothing we can do to recover it.<br>'
            'This may result in the loss of funds in any wallet addresses which have not been Backed Up!<br><br>'
            '<strong>Please, Please, Please Keep Your Password Safe!</strong><br>'
            '</p>'
            '<h2><font color="#034F92">Important Information On Backing Up Your Wallet</font></h2>'
            '<p>'
            'If you lose or forget your password the only thing you can use to recover your funds is a Wallet Backup.<br>'
            'You should create a new backup any time you make a change to your wallet (add/remove an address).<br>'
            'Remove the old backup only after you have confirmed the contents of the new backup are complete.<br>'
            'On the "My Addresses" page you can export a backup of your wallet under the "Wallet Options" button.<br>'
            'This backup file contains every address and private key (if known) for the addresses in your wallet at the time of backup.<br>'
            '<strong>Store your backup file in a secure place. Anyone with access to this file has access to your funds.</strong>'
            '</p><p>'
            'Thank you for taking the time to read this introduction. <br>'
            'This as well as many more questions/answers are available on our <a href="https://'
            + str(email_domain) + '/about/faq">FAQ</a> page.<br>'
            'If you have any questions please feel free to reach out to us using the information on our <a href="https://'
            + str(email_domain) + '/about/contact">Contact Us</a> page.<br>'
            '</p><p>'
            'Sincerely, <br><i> The Omniwallet Team</i>'
            '</p></body></html>')

        part1 = MIMEText(text, 'plain')
        part2 = MIMEText(html, 'html')
        msg.attach(part1)
        msg.attach(part2)
        if config.WELCOMECID is not None:
            msg.add_header('X-Mailgun-Campaign-Id', config.WELCOMECID)

        #wfile = MIMEBase('application', 'octet-stream')
        #wfile.set_payload(wallet)
        #Encoders.encode_base64(wfile)
        #wfile.add_header('Content-Disposition', 'attachment', filename=uuid+'.json')
        #msg.attach(wfile)
        smtp = smtplib.SMTP(config.SMTPDOMAIN, config.SMTPPORT)
        if config.SMTPUSER is not None and config.SMTPPASS is not None:
            if config.SMTPSTARTTLS:
                smtp.starttls()
            smtp.login(config.SMTPUSER, config.SMTPPASS)
        smtp.sendmail(email_from, user_email, msg.as_string())
        smtp.close()
Example #45
0
BOOL = {'TRUE': ['Y', 'YES', 'TRUE'], 'FALSE': ['N', 'NO', 'FALSE']}


def search(dic, search_for):
    for key in dic:
        for val in dic[key]:
            if search_for in val: return key
    return None


faddr = raw_input(
    "What gmail account would you like to send from: ") + '@gmail.com'
pword = getpass.getpass(prompt="Password please: ")
taddr = raw_input("Who would you like to send an email to: ")

msg = MIMEMultipart()
msg['From'] = faddr
msg['To'] = taddr
msg['Subject'] = raw_input("What is your subject line: ")
msg.attach(
    MIMEText(raw_input("What would you like the body to contain?\n"), 'plain'))

if search(BOOL, raw_input("Do you want an attachment? ").upper()) == 'TRUE':
    fname = raw_input("What is the file name and extension: ")
    attachment = open("/nfs/2016/s/sjones/Downloads/wat.jpeg", "rb")
    aprt = MIMEBase('application', 'octet-stream')
    aprt.set_payload((attachment).read())
    encoders.encode_base64(aprt)
    aprt.add_header('Content-Disposition', "attachment; filename= %s" % fname)
    msg.attach(aprt)
else:
Example #46
0
                notification_emails_string += email

            else:
                notification_emails_string += ", "
                notification_emails_string += email

        print "Found " + str(len(missing_users)) + " missing users " + str(
            missing_users
        ) + " that need added to SaM LDAP, sending notifications to " + str(
            notification_emails) + "."

        notification_email_body += "Missing user(s) from group " + group + ":" + str(
            missing_users) + "\n"

    print ""

# Send the notification email if needed
if notification_email_body != "":
    msg = MIMEMultipart()
    msg["From"] = "*****@*****.**"
    msg["To"] = notification_emails_string
    msg["Subject"] = "Missing user(s) in SaM LDAP"
    msg.attach(MIMEText(notification_email_body))

    smtp = smtplib.SMTP("localhost")
    smtp.sendmail("*****@*****.**", notification_emails, msg.as_string())
    smtp.quit()

ad_ldap_obj.unbind_s()
sam_ldap_obj.unbind_s()
Example #47
0
    def _send_raw_email(self):
        self.doLock.acquire()
        index = self.current
        self.doLock.release()
        self.queue[index]['starttime'] = datetime.now()
        self.UIqueue[index]['formStarttime'] = self.queue[index]['starttime']
        self.UIqueue[index]['stat'] = STAT_STARTED
        obj = self.queue[index]
        # create MIME message
        msg = MIMEMultipart()
        msg['Subject'] = self.queue[index]['subject']
        msg['Message-Id'] = make_msgid('ebooks-web-app')
        msg['Date'] = formatdate(localtime=True)
        text = self.queue[index]['text']
        msg.attach(MIMEText(text.encode('UTF-8'), 'plain', 'UTF-8'))
        if obj['attachment']:
            result = get_attachment(obj['filepath'], obj['attachment'])
            if result:
                msg.attach(result)
            else:
                self._handleError(u"Attachment not found")
                return

        msg['From'] = obj['settings']["mail_from"]
        msg['To'] = obj['recipent']

        use_ssl = int(obj['settings'].get('mail_use_ssl', 0))
        try:
            # convert MIME message to string
            fp = StringIO()
            gen = Generator(fp, mangle_from_=False)
            gen.flatten(msg)
            msg = fp.getvalue()

            # send email
            timeout = 600  # set timeout to 5mins

            # redirect output to logfile on python2 pn python3 debugoutput is caught with overwritten
            # _print_debug function
            if sys.version_info < (3, 0):
                org_smtpstderr = smtplib.stderr
                smtplib.stderr = logger.StderrLogger('worker.smtp')

            if use_ssl == 2:
                self.asyncSMTP = email_SSL(obj['settings']["mail_server"],
                                           obj['settings']["mail_port"],
                                           timeout=timeout)
            else:
                self.asyncSMTP = email(obj['settings']["mail_server"],
                                       obj['settings']["mail_port"],
                                       timeout=timeout)

            # link to logginglevel
            if logger.is_debug_enabled():
                self.asyncSMTP.set_debuglevel(1)
            if use_ssl == 1:
                self.asyncSMTP.starttls()
            if obj['settings']["mail_password"]:
                self.asyncSMTP.login(str(obj['settings']["mail_login"]),
                                     str(obj['settings']["mail_password"]))
            self.asyncSMTP.sendmail(obj['settings']["mail_from"],
                                    obj['recipent'], msg)
            self.asyncSMTP.quit()
            self._handleSuccess()

            if sys.version_info < (3, 0):
                smtplib.stderr = org_smtpstderr

        except (MemoryError) as e:
            self._handleError(u'Error sending email: ' + e.message)
            return None
        except (smtplib.SMTPException, smtplib.SMTPAuthenticationError) as e:
            if hasattr(e, "smtp_error"):
                text = e.smtp_error.decode('utf-8').replace("\n", '. ')
            elif hasattr(e, "message"):
                text = e.message
            else:
                text = ''
            self._handleError(u'Error sending email: ' + text)
            return None
        except (socket.error) as e:
            self._handleError(u'Error sending email: ' + e.strerror)
            return None
Example #48
0
def create_html_mail(subject,
                     html,
                     text=None,
                     from_addr=None,
                     to_addr=None,
                     headers=None,
                     encoding='UTF-8'):
    """Create a mime-message that will render HTML in popular
    MUAs, text in better ones.
    """
    # Use DumbWriters word wrapping to ensure that no text line
    # is longer than plain_text_maxcols characters.
    plain_text_maxcols = 72

    html = html.encode(encoding)
    if text is None:
        # Produce an approximate textual rendering of the HTML string,
        # unless you have been given a better version as an argument
        textout = StringIO.StringIO()
        formtext = formatter.AbstractFormatter(
            formatter.DumbWriter(textout, plain_text_maxcols))
        parser = htmllib.HTMLParser(formtext)
        parser.feed(html)
        parser.close()

        # append the anchorlist at the bottom of a message
        # to keep the message readable.
        counter = 0
        anchorlist = "\n\n" + ("-" * plain_text_maxcols) + "\n\n"
        for item in parser.anchorlist:
            counter += 1
            anchorlist += "[%d] %s\n" % (counter, item)

        text = textout.getvalue() + anchorlist
        del textout, formtext, parser, anchorlist
    else:
        text = text.encode(encoding)

    # if we would like to include images in future, there should
    # probably be 'related' instead of 'mixed'
    msg = MIMEMultipart('mixed')
    # maybe later :)
    # msg['From'] = Header("%s <%s>" % (send_from_name, send_from), encoding)
    msg['Subject'] = Header(subject, encoding)
    msg['From'] = from_addr
    msg['To'] = to_addr
    msg['Date'] = formatdate(localtime=True)
    msg["Message-ID"] = email.Utils.make_msgid()
    if headers:
        for key, value in headers.items():
            msg[key] = value
    msg.preamble = 'This is a multi-part message in MIME format.'

    alternatives = MIMEMultipart('alternative')
    msg.attach(alternatives)
    alternatives.attach(MIMEText(text, 'plain', _charset=encoding))
    alternatives.attach(MIMEText(html, 'html', _charset=encoding))

    return msg
Example #49
0
def send_mail(mail_to, smtp_from, subject, smtp_server, smtp_port):
    '''
    Connect to the server once and send all mails
    from 'mail_to' dictionary. Contains emails as
    keys and messages to send as values.

    smtp_to: the sender
    subject: subject line, common for all mails
    '''
    if not mail_to:
        logging.debug('No mails to send (send_mail)')
        return

    logging.debug("Connecting to the server '%s:%s'", smtp_server, smtp_port)
    smtp = smtplib.SMTP(smtp_server, smtp_port)
    logging.debug('Connected.')
    smtp.set_debuglevel(0)

    for send_to in mail_to:
        text = mail_to[send_to]

        msg_root = MIMEMultipart('related')
        msg_root['From'] = smtp_from
        msg_root['To'] = send_to
        msg_root['Date'] = formatdate(localtime=True)
        msg_root['Message-ID'] = make_msgid()
        msg_root['Subject'] = subject
        msg_root.preamble = 'This is a multi-part message in MIME format.'

        msg = MIMEMultipart('alternative')
        msg.set_charset('utf-8')

        msg_root.attach(msg)

        # Wrapping text to the simple html header
        text = '<HTML><BODY><div><pre>' + text + '</pre></div></BODY></HTML>'

        # Attaching text to the letter
        msg_text = MIMEText(text.encode('utf-8', 'replace'),
                            'html',
                            _charset='utf-8')
        msg.attach(msg_text)

        email_file_data = msg_root.as_string()

        smtp.sendmail(smtp_from, send_to, email_file_data)
        logging.debug("Sent outgoing email to '%s'", send_to)

    smtp.close()
Example #50
0
            for wf in wfs:
                print wf[0]
                os.system("python2.6 assignRelValWorkflow.py -w " + wf[0] +
                          " -s " + site + " -p " + str(processing_version))
                time.sleep(30)

            curs.execute(
                "update batches set status=\"assigned\", current_status_start_time=\""
                + datetime.datetime.now().strftime("%y:%m:%d %H:%M:%S") +
                "\" where batch_id = " + str(batchid) + ";")

            mysqlconn.commit()

            if hn_message_id != "do_not_send_an_acknowledgement_email":

                msg = MIMEMultipart()
                reply_to = []
                #send_to = ["*****@*****.**"]
                send_to = [
                    "*****@*****.**",
                    "*****@*****.**"
                ]
                #send_to = ["*****@*****.**"]

                msg['In-Reply-To'] = hn_message_id
                msg['References'] = hn_message_id

                msg['From'] = "*****@*****.**"
                msg['reply-to'] = COMMASPACE.join(reply_to)
                msg['To'] = COMMASPACE.join(send_to)
                msg['Date'] = formatdate(localtime=True)
Example #51
0
def main():

    mysqlconn = MySQLdb.connect(host='dbod-cmsrv1.cern.ch',
                                user='******',
                                passwd="relval",
                                port=5506)

    curs = mysqlconn.cursor()

    curs.execute("use " + dbname + ";")

    #curs.execute("lock tables batches write, batches_archive write, workflows write, workflows_archive write, datasets write, clone_reinsert_requests write")

    curs.execute("select * from batches")
    batches = curs.fetchall()

    batches_colnames = [desc[0] for desc in curs.description]

    for batch in batches:
        #for name, value in zip(batches_colnames, batch):
        #    print name+" => "+str(value)

        batch_dict = dict(zip(batches_colnames, batch))

        userid = batch_dict["useridyear"] + "_" + batch_dict[
            "useridmonth"] + "_" + batch_dict["useridday"] + "_" + str(
                batch_dict["useridnum"]) + "_" + str(
                    batch_dict["batch_version_num"])

        if batch_dict["status"] == "input_dsets_ready":

            print "    userid => " + userid

            curs.execute(
                "select workflow_name from workflows where useridyear = \"" +
                batch_dict["useridyear"] + "\" and useridmonth = \"" +
                batch_dict["useridmonth"] + "\" and useridday = \"" +
                batch_dict["useridday"] + "\" and useridnum = " +
                str(batch_dict["useridnum"]) + " and batch_version_num = " +
                str(batch_dict["batch_version_num"]) + ";")
            wfs = curs.fetchall()

            #first do checks to make sure the workflows do not write into an existing dataset
            for wf in wfs:
                conn = httplib.HTTPSConnection(
                    'cmsweb.cern.ch',
                    cert_file=os.getenv('X509_USER_PROXY'),
                    key_file=os.getenv('X509_USER_PROXY'))
                r1 = conn.request(
                    "GET", '/reqmgr/reqMgr/request?requestName=' + wf[0])
                r2 = conn.getresponse()

                schema = json.loads(r2.read())

                for key, value in schema.items():
                    if type(value) is dict and key.startswith("Task"):
                        if ('KeepOutput' in value and value['KeepOutput']
                            ) or 'KeepOutput' not in value:
                            if 'InputDataset' in value:
                                dset = "/" + value['InputDataset'].split(
                                    '/'
                                )[1] + "/" + value[
                                    'AcquisitionEra'] + "-" + value[
                                        'ProcessingString'] + "-v" + str(
                                            batch_dict["processing_version"]
                                        ) + "/*"

                                curs.execute(
                                    "select * from datasets where dset_name = \""
                                    + dset.rstrip("*") + "\";")

                                dbs_dset_check = utils.getDatasets(dset)

                                curs_fetchall = curs.fetchall()

                                if len(curs_fetchall) != 0:
                                    dsets_colnames = [
                                        desc[0] for desc in curs.description
                                    ]
                                    dset_dict = dict(
                                        zip(dsets_colnames, curs_fetchall[0]))
                                    userid_previously_inserted_dset = dset_dict[
                                        "useridyear"] + "_" + dset_dict[
                                            "useridmonth"] + "_" + dset_dict[
                                                "useridday"] + "_" + str(
                                                    dset_dict["useridnum"]
                                                ) + "_" + str(dset_dict[
                                                    "batch_version_num"])
                                    os.system(
                                        'echo \"' + userid + "\n" + wf[0] +
                                        "\n" +
                                        userid_previously_inserted_dset +
                                        "\n" + dset_dict["workflow_name"] +
                                        "\n" + dset +
                                        '\" | mail -s \"assignor.py error 1\" [email protected]'
                                    )
                                    sys.exit(1)
                                elif len(dbs_dset_check) != 0:
                                    os.system(
                                        'echo \"' + userid + "\n" + wf[0] +
                                        "\n" + dset +
                                        '\" | mail -s \"assignment_loop.py error 5\" [email protected]'
                                    )
                                    sys.exit(1)
                                else:

                                    curs.execute(
                                        "insert into datasets set dset_name=\""
                                        + dset.rstrip("*") +
                                        "\", workflow_name=\"" + wf[0] +
                                        "\", useridyear = \"" +
                                        batch_dict["useridyear"] +
                                        "\", useridmonth = \"" +
                                        batch_dict["useridmonth"] +
                                        "\", useridday = \"" +
                                        batch_dict["useridday"] +
                                        "\", useridnum = " +
                                        str(batch_dict["useridnum"]) +
                                        ", batch_version_num = " +
                                        str(batch_dict["batch_version_num"]) +
                                        ";")

                            elif 'PrimaryDataset' in value:

                                dset = "/" + value[
                                    'PrimaryDataset'] + "/" + value[
                                        'AcquisitionEra'] + "-" + value[
                                            'ProcessingString'] + "-v" + str(
                                                batch_dict["processing_version"]
                                            ) + "/*"
                                curs.execute(
                                    "select * from datasets where dset_name = \""
                                    + dset.rstrip("*") + "\";")

                                curs_fetchall = curs.fetchall()

                                dbs_dset_check = utils.getDatasets(dset)

                                if len(curs_fetchall) != 0:
                                    dsets_colnames = [
                                        desc[0] for desc in curs.description
                                    ]
                                    dset_dict = dict(
                                        zip(dsets_colnames, curs_fetchall[0]))
                                    userid_previously_inserted_dset = dset_dict[
                                        "useridyear"] + "_" + dset_dict[
                                            "useridmonth"] + "_" + dset_dict[
                                                "useridday"] + "_" + str(
                                                    dset_dict["useridnum"]
                                                ) + "_" + str(dset_dict[
                                                    "batch_version_num"])
                                    os.system(
                                        'echo \"' + userid + "\n" + wf[0] +
                                        "\n" +
                                        userid_previously_inserted_dset +
                                        "\n" + dset_dict["workflow_name"] +
                                        "\n" + dset +
                                        '\" | mail -s \"assignment_loop.py error 2\" [email protected]'
                                    )
                                    sys.exit(1)
                                elif len(dbs_dset_check) != 0:
                                    os.system(
                                        'echo \"' + userid + "\n" + wf[0] +
                                        '\" | mail -s \"assignment_loop.py error 7\" [email protected]'
                                    )
                                    sys.exit(1)
                                else:
                                    curs.execute(
                                        "insert into datasets set dset_name=\""
                                        + dset.rstrip("*") +
                                        "\", workflow_name=\"" + wf[0] +
                                        "\", useridyear = " +
                                        batch_dict["useridyear"] +
                                        ", useridmonth = " +
                                        batch_dict["useridmonth"] +
                                        ", useridday = " +
                                        batch_dict["useridday"] +
                                        ", useridnum = " +
                                        str(batch_dict["useridnum"]) +
                                        ", batch_version_num = " +
                                        str(batch_dict["batch_version_num"]) +
                                        ";")

            #only assign the workflows after all of the checks are done
            for wf in wfs:
                conn = httplib.HTTPSConnection(
                    'cmsweb.cern.ch',
                    cert_file=os.getenv('X509_USER_PROXY'),
                    key_file=os.getenv('X509_USER_PROXY'))
                r1 = conn.request(
                    "GET", '/reqmgr/reqMgr/request?requestName=' + wf[0])
                r2 = conn.getresponse()

                if r2.status != 200:
                    os.system(
                        'echo ' + wf[0] +
                        ' | mail -s \"assignment_loop.py error 8\" [email protected]'
                    )
                    sys.exit(0)

                schema = json.loads(r2.read())

                #hack because workflows assigned to only T2_CH_CERN_T0 never get acquired
                site = batch_dict["site"]
                #if site == "T2_CH_CERN_T0":
                #    site = ["T2_CH_CERN","T2_CH_CERN_T0"]

                params = assignment.make_assignment_params(
                    schema, site, batch_dict["processing_version"])

                result = reqMgrClient.assignWorkflow("cmsweb.cern.ch", wf[0],
                                                     "relval", params)

                if result != True:
                    os.system(
                        'echo ' + wf[0] +
                        ' | mail -s \"assignment_loop.py error 4\" [email protected]'
                    )
                    sys.exit(0)

                time.sleep(30)

            curs.execute(
                "update batches set status=\"assigned\", current_status_start_time=\""
                + datetime.datetime.now().strftime("%y:%m:%d %H:%M:%S") +
                "\" where useridyear = \"" + batch_dict["useridyear"] +
                "\" and useridmonth = \"" + batch_dict["useridmonth"] +
                "\" and useridday = \"" + batch_dict["useridday"] +
                "\" and useridnum = " + str(batch_dict["useridnum"]) +
                " and batch_version_num = " +
                str(batch_dict["batch_version_num"]) + ";")

            mysqlconn.commit()

            if batch_dict[
                    "hn_message_id"] != "do_not_send_an_acknowledgement_email":

                msg = MIMEMultipart()
                reply_to = []
                send_to = [
                    "*****@*****.**",
                    "*****@*****.**"
                ]
                #send_to = ["*****@*****.**","*****@*****.**"]
                #send_to = ["*****@*****.**"]

                msg['In-Reply-To'] = batch_dict["hn_message_id"]
                msg['References'] = batch_dict["hn_message_id"]

                msg['From'] = "*****@*****.**"
                msg['reply-to'] = COMMASPACE.join(reply_to)
                msg['To'] = COMMASPACE.join(send_to)
                msg['Date'] = formatdate(localtime=True)
                msg['Subject'] = batch_dict["announcement_title"]
                msg['Message-ID'] = email.Utils.make_msgid()

                messageText = "Dear all,\n"
                messageText = messageText + "\n"
                messageText = messageText + "This batch has been assigned.\n"
                messageText = messageText + "\n"
                messageText = messageText + "RelVal Batch Manager"

                try:
                    msg.attach(MIMEText(messageText))
                    smtpObj = smtplib.SMTP()
                    smtpObj.connect()
                    smtpObj.sendmail("*****@*****.**", send_to,
                                     msg.as_string())
                    smtpObj.close()
                except Exception as e:
                    print "Error: unable to send email: %s" % (str(e))
Example #52
0
        if keep.search(line):
            # replace all unwanted substrings
            line = rep.sub("", line.lstrip())
            line = r3.sub(
                "\n"
                'http://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE',
                line)  # Change Accesion number to Accession hyperlink.
            out.write(line)

# Email
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

fromaddr = "*****@*****.**"  # sender email
toaddr = ""  # receiver email
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "GEO Data Sets - Supported platforms"

# To send send txt file in email body.
f1 = (open("email_data.txt", 'rU'))
geo = MIMEText(f1.read(), 'plain')
f1.close()
msg.attach(geo)

# Convert to string.
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
Example #53
0
def sendmail(from_addr, to_addr_list, subject, message, login, password):
    # Create the root message and fill in the from, to, and subject headers
    msgRoot = MIMEMultipart('related')
    msgRoot['From'] = from_addr
    msgRoot['Subject'] = subject
    msgRoot['To'] = str(to_addr_list)
    msgRoot.preamble = 'This is a multi-part message in MIME format.'

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

    msgText = MIMEText('This is the alternative plain text message.')
    msgAlternative.attach(msgText)

    # We reference the image in the IMG SRC attribute by the ID we give it below
    msgText = MIMEText(message, 'html')
    msgAlternative.attach(msgText)

    # Send the email (this example assumes SMTP authentication is required)
    server = smtplib.SMTP(
        'smtp.gmail.com:587'
    )  # This would work for Gmail, could be any SMTP server
    server.starttls()
    server.login(login, password)
    server.sendmail(from_addr, to_addr_list, msgRoot.as_string())
    server.quit()
Example #54
0
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import smtplib
import datetime
from task import *
Session = sessionmaker(bind=engine)
dbconn = Session()

em = '*****@*****.**'
em1 = '*****@*****.**'
em2 = '*****@*****.**'
em3 = '*****@*****.**'
em4 = '*****@*****.**'

msg = MIMEMultipart()
msg['From'] = '*****@*****.**'
msg['To'] = em
msg['Subject'] = '*** REPORT HD ***'
msg.set_charset('utf-8')
msg.set_default_type("text/html")
now = datetime.datetime.now()
delta = now + datetime.timedelta(hours=-3)
delta1 = now + datetime.timedelta(hours=-1)
mess = "<b>%s</b><br/>Задачи находятся без движения более одного часа.<br/>" % (
    now.strftime('%Y-%m-%d %H:%M'))
mess += """
<br>
<table border='1' cellpadding="0" cellspacing="0" ><tr><td>PERFORMER</td><td>THREADS</td></tr>
"""
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
# Please go to "mypassword.py" to change your password
from mypassword import gmailPassword

gmailUser = '******'
recipients = [gmailUser, '*****@*****.**', '*****@*****.**']

# Send this script to all receivers
filename = "send_gmail.py"
with open(filename, "rb") as f:
    message = f.read()

msg = MIMEMultipart()
msg['From'] = gmailUser
msg['To'] = ", ".join(recipients)
msg['Subject'] = "My python email script!"
msg.attach(MIMEText(message))

# Establish a connection to the gmail esmtp server
mailServer = smtplib.SMTP('smtp.gmail.com', 587)
# Identify ourselves to esmtp gmail client (ESMTP (Extended SMTP) is more secure)
mailServer.ehlo()
# Secure our email with TLS (Transport Layer Security) encryption
mailServer.starttls()
# Re-identify ourselves as an encrypted connection
mailServer.ehlo()
# Login to the gmail services
mailServer.login(gmailUser, gmailPassword)
# Send your email!
Example #56
0
def sendReport():
    if (not (os.path.exists(testconf['seleniumReport']))):
        print "Report file not found, quitting."
        sys.exit(1)

    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEText import MIMEText
    from email.MIMEImage import MIMEImage
    import smtplib

    # Create the root message and fill in the from, to, and subject headers
    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = 'Test Runner report'
    msgRoot['From'] = testconf['mailFrom']
    msgRoot['To'] = testconf['mailTo']
    msgRoot.preamble = 'This is a multi-part message in MIME format.'

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

    msgText = MIMEText('Test Runner results.')
    msgAlternative.attach(msgText)

    reportFile = open(testconf['seleniumReport'], 'rb')

    msgText = MIMEText(reportFile.read(), 'html')
    msgAlternative.attach(msgText)

    reportFile.close()

    print("Sending report to " + testconf['mailTo'])

    mailServer = smtplib.SMTP(testconf['smtpHost'], testconf['smtpPort'])
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    #mailServer.login(testconf['smtpUser'], testconf['smtpPwd'])
    mailServer.sendmail(testconf['mailFrom'], testconf['mailTo'],
                        msgRoot.as_string())
    mailServer.close()
Example #57
0
def send(subject = "(No Subject)", text = "(No Body)", to = '*****@*****.**',
	     from_addr = '*****@*****.**', user = '******', server='smtp.gmail.com', password = '', attachments=[],
	     size = None, wrap_html = False, html_format = False):
	from os import error
	#print "Using tg.mail to send e-mail"
	if not from_addr:
		from_addr = user

	if not password or not user or not server or not to:
		raise(RuntimeError("SMTP server, user, recipient (to), or password not specified. Can't log onto server to send e-mail"))
		return False

	html = ''
	if wrap_html:
		html_format = True
		html =  '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" '
		html += '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">'
		html += '<body style="font-size:11px;font-family:Verdana">'
		html += 'Automatic delivery from <strong>tagim</strong>.'

	html += text

	if wrap_html:
		html += "</body></html>"

	msg = MIMEMultipart()
	msg['Subject'] = subject
	msg['From'] = user
	if type(to) == type([]):
		msg['To'] = ', '.join(to)
	else:
		msg['To'] = to

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

	# create a separate "fileMsg" attachment
#	fileMsg = MIMEBase('application','vnd.ms-excel')
#	fileMsg.set_payload(file('2009_butter.xls').read())
#	encode_base64(fileMsg)
#	fileMsg.add_header('Content-Disposition','attachment;filename=anExcelFile.xls')
#	msg.attach(fileMsg)

	if not len(attachments)>0:
		warnings.warn("No attachments were received by tg.mail.send()")
	if not size:
		(attachments,size) = optimize_size(attachments)
	if type(attachments) == type([]):
		for attachmentPath in attachments:
			print attachmentPath
			msg.attach(getAttachment(attachmentPath,size))
	elif type(attachments) == type((str,'')):
		msg.attach(getAttachment(attachments,size))
	else:
		warnings.warn("Attachments parameter was of invalid type: ",type(attachments))

	mailServer = smtplib.SMTP(server, 587)
	mailServer.ehlo()
	mailServer.starttls()
	mailServer.ehlo()
	mailServer.login(user, password)
	mailServer.sendmail(user, to, msg.as_string())
	mailServer.close()

	print('Successflly sent email titled {subject} to {to}'.format(subject=subject,to=to))
from email.MIMEText import MIMEText

# inputs for from, to, subject and body text
fromaddr = raw_input("Sender's email: ")
toaddr = raw_input('To: ')
sub = raw_input('Subject: ')
text = raw_input('Body: ')

# email account info from where we'll be sending the email from
smtp_host = 'smtp.mail.com'
smtp_port = '###'
user = '******'
password = '******'

# parts of the actual email
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = sub
msg.attach(MIMEText(text))

# connect to the server
server = smtplib.SMTP()
server.connect(smtp_host, smtp_port)

# initiate communication with server
server.ehlo()

# use encryption
server.starttls()
Example #59
0
def main():

    mysqlconn = MySQLdb.connect(host='dbod-cmsrv1.cern.ch', user='******', passwd="relval", port=5506)

    curs = mysqlconn.cursor()

    curs.execute("use "+dbname+";")

    #curs.execute("lock tables batches write, batches_archive write, workflows write, workflows_archive write, datasets write, clone_reinsert_requests write")

    curs.execute("select * from batches")
    batches=curs.fetchall()
    
    batches_colnames = [desc[0] for desc in curs.description]

    for batch in batches:

        batch_dict= dict(zip(batches_colnames, batch))

        if batch_dict["status"] != "assigned":
            continue

        userid=batch_dict["useridyear"]+"_"+batch_dict["useridmonth"]+"_"+batch_dict["useridday"]+"_"+str(batch_dict["useridnum"])+"_"+str(batch_dict["batch_version_num"])

        print "   userid ==> "+userid

        curs.execute("select workflow_name from workflows where useridyear = \""+batch_dict["useridyear"]+"\" and useridmonth = \""+batch_dict["useridmonth"]+ "\" and useridday = \""+batch_dict["useridday"]+"\" and useridnum = "+str(batch_dict["useridnum"])+" and batch_version_num ="+str(batch_dict["batch_version_num"])+";")
        wfs=curs.fetchall()

        n_workflows=0
        n_completed=0
        for wf in wfs:
            n_workflows=n_workflows+1
            conn  =  httplib.HTTPSConnection(url, cert_file = os.getenv('X509_USER_PROXY'), key_file = os.getenv('X509_USER_PROXY'))
            r1=conn.request('GET','/reqmgr2/data/request?name='+wf[0],headers={"Accept": "application/json"})
            r2=conn.getresponse()
            data = r2.read()
            if r2.status != 200:
                time.sleep(10)
                #try it again
                conn  =  httplib.HTTPSConnection(url, cert_file = os.getenv('X509_USER_PROXY'), key_file = os.getenv('X509_USER_PROXY'))
                r1=conn.request('GET','/reqmgr2/data/request?name='+wf[0],headers={"Accept": "application/json"})
                r2=conn.getresponse()
                data = r2.read()
                if r2.status != 200:
                    time.sleep(10)
                    #try it a third time
                    conn  =  httplib.HTTPSConnection(url, cert_file = os.getenv('X509_USER_PROXY'), key_file = os.getenv('X509_USER_PROXY'))
                    r1=conn.request('GET','/reqmgr2/data/request?name='+wf[0],headers={"Accept": "application/json"})
                    r2=conn.getresponse()
                    data = r2.read()
                    if r2.status != 200:
                        os.system('echo \"'+wf[0]+'\" | mail -s \"announcor.py error 1\" [email protected]')
                        sys.exit(1)
            s = json.loads(data)

            for status in s['result'][0][wf[0]]['RequestTransition']:
                if status['Status'] == "completed" or status['Status'] == "force-complete":
                    #conn  =  httplib.HTTPSConnection(url, cert_file = os.getenv('X509_USER_PROXY'), key_file = os.getenv('X509_USER_PROXY'))
                    #r1=conn.request('GET',"/wmstatsserver/data/isfinished/"+wf[0],headers={"Accept": "application/json"})
                    #r2=conn.getresponse()
                    #data = r2.read()        
                    #s = json.loads(data)
                    
                    #if s['result'][0] == "true":
                    #    n_completed=n_completed+1
                    n_completed=n_completed+1
                    break    

        print "datetime.datetime.now() = " + str(datetime.datetime.now())            
        print "n_workflows = " + str(n_workflows)
        print "n_completed = " + str(n_completed)

        if n_workflows != n_completed:
            continue

        #string="2016_04_11_1_0"

        #if not (string.split('_')[0] == batch_dict["useridyear"] and string.split('_')[1] == batch_dict["useridmonth"] and string.split('_')[2] == batch_dict["useridday"] and string.split('_')[3] == str(batch_dict["useridnum"]) and string.split('_')[4] == str(batch_dict["batch_version_num"])):
        #    continue

        wf_list = []
        
        for wf in wfs:
            print wf[0]

            wf_list.append(wf[0])

        job_failure_information=collect_job_failure_information.collect_job_failure_information(wf_list)

        needs_assistance = assistance_decision.assistance_decision(job_failure_information)

        if needs_assistance:
            curs.execute("update batches set status=\"assistance\", current_status_start_time=\""+datetime.datetime.now().strftime("%y:%m:%d %H:%M:%S")+"\" where useridyear = \""+batch_dict["useridyear"]+"\" and useridmonth = \""+batch_dict["useridmonth"]+ "\" and useridday = \""+batch_dict["useridday"]+"\" and useridnum = "+str(batch_dict["useridnum"])+" and batch_version_num ="+str(batch_dict["batch_version_num"])+";")
            mysqlconn.commit()
            os.system('echo \"batch_id: '+userid+'\" | mail -s \"a batch of relval workflows needs assistance\" [email protected]')
            continue

        #if there is a '\r' character in the body of an e-mail, it does not get sent
        description=batch_dict["description"].replace('\r','')

        for wf in wf_list:
            too_many_events_check.too_many_events_check(wf)

        dset_nevents_list=collect_dsets_and_nevents.collect_dsets_and_nevents(wf_list)

        print_dsets_and_nevents.print_dsets_and_nevents(dset_nevents_list, userid+".txt")

        ret=os.system("cp "+userid+".txt /afs/cern.ch/user/r/relval/webpage/relval_stats/"+userid+".txt")

        if ret == 0:
            os.system("rm "+userid+".txt")
        else:
            os.system('echo \"'+userid+'\" | mail -s \"announcor.py error 2\" [email protected]')
            sys.exit(0)

        dsets_list = []    

        for dset_nevents in dset_nevents_list:
            dsets_list.append(dset_nevents[0])

        for dset in dsets_list:
            setDatasetStatusDBS3.setStatusDBS3("https://cmsweb.cern.ch/dbs/prod/global/DBSWriter", dset, "VALID", True)

        for wf in wf_list:
            reqMgrClient.closeOutWorkflow("cmsweb.cern.ch",wf)
            reqMgrClient.announceWorkflow("cmsweb.cern.ch",wf)

        msg = MIMEMultipart()
        reply_to = []
        #send_to = ["*****@*****.**","*****@*****.**"]
        send_to = ["*****@*****.**","*****@*****.**","*****@*****.**"]
        #send_to = ["*****@*****.**"]
            
        #msg['In-Reply-To'] = hn_message_id
        #msg['References'] = hn_message_id
            
        msg['From'] = "*****@*****.**"
        msg['reply-to'] = COMMASPACE.join(reply_to)
        msg['To'] = COMMASPACE.join(send_to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = batch_dict["announcement_title"]
        msg['Message-ID'] = email.Utils.make_msgid()

        messageText="Dear all,\n"
        messageText=messageText+"\n"
        messageText=messageText+"A batch of relval workflows has finished.\n"
        messageText=messageText+"\n"
        messageText=messageText+"Batch ID:\n"
        messageText=messageText+"\n"
        messageText=messageText+userid+"\n"
        if batch_dict["batch_version_num"] > 0:
            messageText=messageText+"\n"
            messageText=messageText+"original workflow name ==> clone name:\n"
            messageText=messageText+"\n"
            curs.execute("select workflow_name,original_workflow_name from workflows where useridyear = \""+batch_dict["useridyear"]+"\" and useridmonth = \""+batch_dict["useridmonth"]+ "\" and useridday = \""+batch_dict["useridday"]+"\" and useridnum = "+str(batch_dict["useridnum"])+" and batch_version_num ="+str(batch_dict["batch_version_num"])+";")
            workflows=curs.fetchall()
            for workflow in workflows:
                messageText=messageText+workflow[1] + " ==> "+workflow[0] + "\n"
        messageText=messageText+"\n"        
        messageText=messageText+"List of datasets:\n"
        messageText=messageText+"\n"
        messageText=messageText+"http://cms-project-relval.web.cern.ch/cms-project-relval/relval_stats/"+userid+".txt\n"
        messageText=messageText+"\n"
        messageText=messageText+"Description:\n"
        messageText=messageText+"\n"
        messageText=messageText+description.rstrip('\n')
        messageText=messageText+"\n"
        #messageText=messageText+"\n"
        [istherefailureinformation,return_string]=print_job_failure_information.print_job_failure_information(job_failure_information)

        if istherefailureinformation:
            messageText=messageText+"\n"
            messageText=messageText+return_string
            messageText=messageText+"\n"
        messageText=messageText+"\n"
        messageText=messageText+"RelVal Batch Manager"

        #put the announcement message into an e-mail to the relval hypernews and also in a url
        output_file = open("/afs/cern.ch/user/r/relval/webpage/relval_announcements/"+userid+".txt", 'w')

        output_file.write(messageText)

        try:
            msg.attach(MIMEText(messageText))
            smtpObj = smtplib.SMTP()
            smtpObj.connect()
            smtpObj.sendmail("*****@*****.**", send_to, msg.as_string())
            smtpObj.close()
        except Exception as e:
            print "Error: unable to send email: %s" %(str(e))

        dsets_fnal_disk_list = []
        dsets_cern_disk_list = []
            
        for dset in dsets_list:

            #print dset.split('/')

            # we were asked to transfer some specific datasets to the cern tier 2
            if dset.split('/')[3] != "RECO" and dset.split('/')[3] != "ALCARECO":
                dsets_cern_disk_list.append(dset)

            if dset.split('/')[3] == "GEN-SIM":
                dsets_fnal_disk_list.append(dset)

            if dset.split('/')[3] == "GEN-SIM-DIGI-RAW":
                dsets_fnal_disk_list.append(dset)

            if dset.split('/')[3]  == "GEN-SIM-RECO":
                dsets_fnal_disk_list.append(dset)

            if "RelValTTBar" in dset.split('/')[1] and "TkAlMinBias" in dset.split('/')[2] and dset.split('/')[3] != "ALCARECO":
                dsets_cern_disk_list.append(dset)

            if "MinimumBias" in dset.split('/')[1] and "SiStripCalMinBias" in dset.split('/')[2] and dset.split('/')[3] != "ALCARECO":
                dsets_cern_disk_list.append(dset)

        result=utils.makeReplicaRequest("cmsweb.cern.ch", "T2_CH_CERN", dsets_cern_disk_list, "relval datasets",group="RelVal")
        if result != None:
            phedexid = result['phedex']['request_created'][0]['id']
            utils.approveSubscription("cmsweb.cern.ch",phedexid)

        result=utils.makeReplicaRequest("cmsweb.cern.ch", "T1_US_FNAL_Disk", dsets_fnal_disk_list, "relval datasets", group = "RelVal")
        if result != None:
            phedexid = result['phedex']['request_created'][0]['id']
            utils.approveSubscription("cmsweb.cern.ch",phedexid)

        result=utils.makeMoveRequest("cmsweb.cern.ch", "T0_CH_CERN_MSS", dsets_list, "relval datasets", group = "RelVal")
        if result != None:
            phedexid = result['phedex']['request_created'][0]['id']
            #even if you disapprove the subscription at the source, it will still deleted the datasets that are at the source but not subscribed their
            utils.disapproveSubscription("cmsweb.cern.ch",phedexid,["T2_CH_CERN"])
            utils.disapproveSubscription("cmsweb.cern.ch",phedexid,["T1_US_FNAL_Disk"])
            utils.disapproveSubscription("cmsweb.cern.ch",phedexid,["T1_FR_CCIN2P3_Disk"])
            utils.disapproveSubscription("cmsweb.cern.ch",phedexid,["T1_DE_KIT_Disk"])
            utils.approveSubscription("cmsweb.cern.ch",phedexid,["T0_CH_CERN_MSS"])

        #phedexid = result['phedex']['request_created'][0]['id']
        #utils.approveSubscription("cmsweb.cern.ch",phedexid)

        curs.execute("update batches set status=\"announced\", current_status_start_time=\""+datetime.datetime.now().strftime("%y:%m:%d %H:%M:%S")+"\" where useridyear = \""+batch_dict["useridyear"]+"\" and useridmonth = \""+batch_dict["useridmonth"]+ "\" and useridday = \""+batch_dict["useridday"]+"\" and useridnum = "+str(batch_dict["useridnum"])+" and batch_version_num ="+str(batch_dict["batch_version_num"])+";")
        mysqlconn.commit()
Example #60
0
    def send_msg(self,
                 body_msg,
                 image=None,
                 image2=None,
                 maxmin_in=None,
                 maxmin_out=None):
        """ Send a message with pictures and data. """

        print "send_msg", body_msg
        t_s = time.gmtime()

        for email in mod.Email.objects.all():
            msg_from = email.from_email
            msg_to = email.to_email
            msg = MIMEMultipart()
            msg['From'] = msg_from
            msg['To'] = msg_to
            msg['Subject'] = "Lucky & Miracle: " + body_msg

            body = body_msg
            if maxmin_in is not None:
                body += '\nThe maximum temperature measured inside was '
                body += str(maxmin_in.max_temp) + 'F at '
                body += maxmin_in.max_temp_date.strftime(
                    '%y/%m/%d %H:%M:%S') + '\n'
                body += '\nThe minimum temperature measured inside was ' + str(
                    maxmin_in.min_temp)
                body += 'F at ' + maxmin_in.min_temp_date.strftime(
                    '%y/%m/%d %H:%M:%S') + '\n'

            if maxmin_out is not None:
                body += '\nThe maximum temperature measured outside was '
                body += str(maxmin_out.max_temp) + 'F at '
                body += maxmin_out.max_temp_date.strftime(
                    '%y/%m/%d %H:%M:%S') + '\n'
                body += '\nThe minimum temperature measured outside was '
                body += str(maxmin_out.min_temp) + 'F at '
                body += maxmin_out.min_temp_date.strftime(
                    '%y/%m/%d %H:%M:%S') + '\n'

            msg.attach(MIMEText(body, 'plain'))
            if image is not None:
                f_p = open(image, 'rb')
                img = MIMEImage(f_p.read())
                f_p.close()
                msg.attach(img)

            if image2 is not None:
                f_p = open(image2, 'rb')
                img = MIMEImage(f_p.read())
                f_p.close()
                msg.attach(img)

            if t_s.tm_wday == 6 and re.search('sunrise', body_msg):
                report_file = self.report()
                f_p = open(report_file, 'rb')
                report = MIMEBase('application', 'octet-stream')
                report.set_payload(f_p.read())
                f_p.close()
                encoders.encode_base64(report)
                report.add_header("Content-Disposition",
                                  "attachment",
                                  filename='report.xlsx')
                msg.attach(report)

            try:
                # if True:
                hotmail = smtplib.SMTP('smtp.live.com', 587)
                hotmail.starttls()
                hotmail.login(msg_from, email.from_password)
                text = msg.as_string()
                hotmail.sendmail(msg_from, msg_to, text)
                hotmail.quit()
            except (RuntimeError, TypeError, NameError):
                print "Email:", RuntimeError, TypeError, NameError
            except ValueError:
                print "Email ValueError", ValueError