def send_to_email(mandrill_login, email_from='*****@*****.**', email_to=[], subject='', message='', list_of_files=[]): # email_to must be list smtp = smtplib.SMTP("smtp.mandrillapp.com", 587) smtp.starttls() smtp.login(*mandrill_login) mpart = MIMEMultipart() mpart.set_charset("utf-8") mpart["From"] = email_from mpart["Subject"] = subject mpart.attach(MIMEText(message, 'plain')) for f in list_of_files: fpart = MIMEBase('application', "octet-stream") fpart.set_payload(open(f, "rb").read()) Encoders.encode_base64(fpart) fpart.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) mpart.attach(fpart) for to in email_to: mpart["To"] = to smtp.sendmail(mpart["From"], to, mpart.as_string()) smtp.close()
def send(gmail_user, gmail_pwd, to, subject, text, attach=None): msg = MIMEMultipart("alternative") msg.set_charset("utf-8") msg['From'] = gmail_user msg['To'] = to msg['Subject'] = subject msg.attach(MIMEText(text, "plain", "utf-8")) if attach is not None: part = MIMEBase('application', 'octet-stream') part.set_payload(open(attach, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach)) msg.attach(part) print msg try: mailServer = smtplib.SMTP("smtp.gmail.com", 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(gmail_user, gmail_pwd) mailServer.sendmail(gmail_user, to, msg.as_string()) # Should be mailServer.quit(), but that crashes... mailServer.close() except: app.loggger.error("Couldn't send confirmation email: " + str(text)) pass
def mail(config, encoding, subject, body, out_data, err_data): msg = MIMEMultipart() msg.set_charset(encoding) subject = Header(subject, encoding) msg["From"] = config["user"] msg["To"] = config["user"] msg["Subject"] = subject part = MIMEBase("text", "html", _charset=encoding) part.set_payload(body) Encoders.encode_base64(part) msg.attach(part) if not out_data is None: part = MIMEText(out_data, _charset=encoding) part.add_header("Content-Disposition", "attachment", filename="stdout.txt") msg.attach(part) if not err_data is None: part = MIMEText(err_data, _charset=encoding) part.add_header("Content-Disposition", "attachment", filename="stderr.txt") msg.attach(part) port = 25 if config["auth"]: port = 587 mailServer = smtplib.SMTP(config["server"], port, local_hostname="localhost") if config["tls"]: mailServer.ehlo() mailServer.starttls() mailServer.ehlo() if config["auth"]: mailServer.login(config["user"], config["pass"]) mailServer.sendmail(config["user"], config["user"], msg.as_string()) mailServer.close()
def send_mail(mail): msg = MIMEMultipart() msg.set_charset('utf-8') msg['From'] = mail['From'] msg['Bcc'] = COMMASPACE.join(mail['To']) msg['Date'] = formatdate(localtime=True) msg['Subject'] = mail['Subject'] msg['Reply-To'] = mail['Reply-To'] msg['Message-ID'] = mail['Message-ID'] msg['In-Reply-To'] = mail['In-Reply-To'] #msg['Content-Type'] = 'text/plain; charset=UTF-8' msg.attach( MIMEText(mail['text'], _charset="utf-8") ) for f in mail['files']: part = MIMEBase('application', "octet-stream") part.set_payload( open('./files/%s' % f['id'],"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % f['name']) msg.attach(part) try: smtp = getSMTPServer() content = msg.as_string() smtp.sendmail(mail['Reply-To'], mail['To'], content) smtp.close() except : pass
def send_mail(send_from, send_to, subject, text, files=[], server="localhost", ssl=False, username=None, password=None): msg = MIMEMultipart('alternative') msg.set_charset('utf-8') msg['From'] = send_from msg['To'] = send_to msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject part = MIMEText(text) part.set_charset('utf-8') msg.attach(part) if ssl: smtp = smtplib.SMTP_SSL(server) else: smtp = smtplib.SMTP(server) if username: smtp.login(username, password) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send(gmail_user, gmail_pwd, to, subject, text, attach=None): msg = MIMEMultipart("alternative") msg.set_charset("utf-8") msg['From'] = gmail_user msg['To'] = to msg['Subject'] = subject msg.attach(MIMEText(text, "plain", "utf-8")) if attach is not None: part = MIMEBase('application', 'octet-stream') part.set_payload(open(attach, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach)) msg.attach(part) print msg try: mailServer = smtplib.SMTP("smtp.gmail.com", 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(gmail_user, gmail_pwd) mailServer.sendmail(gmail_user, to, msg.as_string()) # Should be mailServer.quit(), but that crashes... mailServer.close() return True except: # app.loggger.error("Couldn't send confirmation email: " + str(text)) - Causes crash # TODO: fix error logging here so that it doesn't cause a crash. pass
def sendEmail(send_from, send_to, subject, text, cc_to=[], files=[], server="192.168.42.13"): assert type(send_to)==list assert type(files)==list msg=MIMEMultipart() msg.set_charset("utf-8") msg['From']=send_from msg['To']=COMMASPACE.join(send_to) if cc_to: assert type(cc_to)==list msg['cc']=COMMASPACE.join(cc_to) send_to.extend(cc_to) msg['Date']=formatdate(localtime=True) msg['Subject']=subject msg.attach(MIMEText(text)) for f in files: part=MIMEBase('application', "octet-stream") part.set_payload(open(f, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"'%Header(os.path.basename(f), 'utf-8')) msg.attach(part) smtp=smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def __prepareEmail(self, conn, mailid, mailtype, header, data, attlen): """ Method creates text part of email, it means without base64 encoded attachments. This includes following steps: 1) Create HDF dataset (base of templating) 2) Template subject 3) Run templating for all wanted templates and attach them 4) Create email headers 5) Dump email in string form """ # init headers hdf = neo_util.HDF() # pour defaults in data set for pair in self.__dbGetDefaults(conn): hdf.setValue("defaults." + pair[0], pair[1]) # pour user provided values in data set for pair in data: hdf.setValue(pair.key, pair.value) mailtype_id, subject_tpl, templates = self.__dbGetMailTypeData(conn, mailtype) # render subject cs = neo_cs.CS(hdf) cs.parseStr(subject_tpl) subject = cs.render() # Create email object multi or single part (we have to decide now) if attlen > 0 or len(templates) > 1 or self.vcard: msg = MIMEMultipart() # render text attachments for item in templates: cs = neo_cs.CS(hdf) cs.parseStr(item["template"]) mimetext = MIMEText(cs.render().strip() + '\n', item["type"]) mimetext.set_charset("utf-8") # Leave this commented out, otherwise it duplicates header # Content-Transfer-Encoding #Encoders.encode_7or8bit(mimetext) msg.attach(mimetext) # Attach vcard attachment if configured so if self.vcard: mimetext = MIMEText(self.vcard, "x-vcard") mimetext.set_charset("utf-8") msg.attach(mimetext) else: # render text attachment cs = neo_cs.CS(hdf) cs.parseStr(templates[0]["template"]) msg = MIMEText(cs.render().strip()+'\n', templates[0]["type"]) msg.set_charset("utf-8") # init email header (BEWARE that header struct is modified in this # call to function, so it is filled with defaults for not provided # headers, which is important for obtaining envelope sender). self.__dbSetHeaders(conn, mailid, subject, header, msg) return msg.as_string(), mailtype_id
def get_standard_message(self, multipart=False): '''Form a standard email message from Roundup. Returns a Message object. ''' charset = getattr(self.config, 'EMAIL_CHARSET', 'utf-8') if multipart: message = MIMEMultipart() else: message = MIMEText("") message.set_charset(charset) return message
def send_mail(send_from, send_to, subject, text, files=[], server="localhost"): msg = MIMEMultipart('alternative') msg.set_charset('utf-8') msg['From'] = send_from msg['To'] = send_to msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject part = MIMEText(text) part.set_charset('utf-8') msg.attach(part) smtp = smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def get_standard_message(self, to, subject, author=None, multipart=False): '''Form a standard email message from Roundup. "to" - recipients list "subject" - Subject "author" - (name, address) tuple or None for admin email Subject and author are encoded using the EMAIL_CHARSET from the config (default UTF-8). Returns a Message object. ''' # encode header values if they need to be charset = getattr(self.config, 'EMAIL_CHARSET', 'utf-8') tracker_name = unicode(self.config.TRACKER_NAME, 'utf-8') if not author: author = (tracker_name, self.config.ADMIN_EMAIL) name = author[0] else: name = unicode(author[0], 'utf-8') author = nice_sender_header(name, author[1], charset) if multipart: message = MIMEMultipart() else: message = MIMEText("") message.set_charset(charset) try: message['Subject'] = subject.encode('ascii') except UnicodeError: message['Subject'] = Header(subject, charset) message['To'] = ', '.join(to) message['From'] = author message['Date'] = formatdate(localtime=True) # add a Precedence header so autoresponders ignore us message['Precedence'] = 'bulk' # Add a unique Roundup header to help filtering try: message['X-Roundup-Name'] = tracker_name.encode('ascii') except UnicodeError: message['X-Roundup-Name'] = Header(tracker_name, charset) # and another one to avoid loops message['X-Roundup-Loop'] = 'hello' # finally, an aid to debugging problems message['X-Roundup-Version'] = __version__ return message
def enviar_email(msg,destino,servidor,login,senha): msgRoot = MIMEMultipart('related') msgRoot.set_charset("utf-8") msgRoot['Subject'] = msg.assunto #'Meu desejo de Boas Festas' msgRoot['From'] = msg.email_from msgRoot['To'] = limpa(destino.email) msgRoot['List-Unsubscribe']= msg.email_responder_para msgRoot['Precedence'] = 'bulk' msgRoot['Reply-To'] = msg.email_responder_para 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) msgAlternative.set_charset("utf-8") msgText = MIMEText(msg.mensagem_texto_alternativo.encode("utf-8"),_charset="utf-8") msgAlternative.attach(msgText) remove_span = u"""<p style="text-align:center;font-family:Verdana;font-size:9pt;color:#a2a2a2;">Caso não esteja visualizando corretamente este e mail, <a href="http://rabodolagarto.com.br/newsletter/view/%d/">acesse aqui</a></p><br> <br>%s <p style="text-align:center;font-size:9pt;font-family:Verdana;color:#a2a2a2;">Caso não queira mais receber informações da pousada <a href="http://rabodolagarto.com.br/newsletter/cancela/%d/%d/">clique aqui</a> ou responda este email com assunto REMOVER.<br> Agradecemos sua atenção durante este período.</p> """ % (msg.id,msg.mensagem,msg.id,destino.id) # We reference the image in the IMG SRC attribute by the ID we give it below msgText = MIMEText(remove_span.encode("utf-8"),'html',_charset="utf-8") msgAlternative.attach(msgText) # This example assumes the image is in the current directory fp = open(msg.imagem.path) msgImage = MIMEImage(fp.read()) fp.close() # Define the image's ID as referenced above msgImage.add_header('Content-ID', '<image1>') msgRoot.attach(msgImage) # Send the email (this example assumes SMTP authentication is required) import smtplib smtp = smtplib.SMTP() smtp.connect(servidor) smtp.starttls() smtp.login(login,senha) try: smtp.sendmail(msg.email_from, [limpa(destino.email),], msgRoot.as_string()) except Exception, err: return err
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()
def sendErrorToMail(subject, reason): email_from = "*****@*****.**" email_rcpt = "*****@*****.**" msg = MIMEMultipart('alternative') msg.set_charset('utf-8') sub = Header(subject, 'utf-8') msg['Subject'] = sub msg['From'] = email_from msg['To'] = email_rcpt textv = reason part1 = MIMEText(textv, 'plain', 'utf-8') msg.attach(part1) mailer = smtplib.SMTP("server.smtp.com", 25) mailer.sendmail(email_from, email_rcpt, msg.as_string()) mailer.quit()
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()
def send_mail(to, subject, text, frm=SMTP_MAIL_FROM, is_html=False, files=[], cc=[], bcc=[]): assert type(to) == list assert type(files) == list assert type(cc) == list assert type(bcc) == list message = MIMEMultipart() message['From'] = frm message['To'] = COMMASPACE.join(to) message['Date'] = formatdate(localtime=True) message['Subject'] = subject message['Cc'] = COMMASPACE.join(cc) message.set_charset('UTF-8') if is_html: message.attach(MIMEText(text, 'html')) else: message.attach(MIMEText(text, 'plain')) for f in files: part = MIMEBase('application', 'octet-stream') part.set_payload(open(f, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) message.attach(part) addresses = [] for x in to: addresses.append(x) for x in cc: addresses.append(x) for x in bcc: addresses.append(x) smtp = smtplib.SMTP(SMTP_MAIL_SERVER) smtp.sendmail(frm, addresses, message.as_string()) smtp.close()
def send_mail(mail_from, password, mail_to, subject, text, servername="smtp.gmail.com", files=[], performDebugging=False, name_from='', name_to=''): import smtplib import os import email.utils from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders # assert type(send_to)==list assert type(files) == list msg = MIMEMultipart() msg.set_charset('utf-8') msg['From'] = email.utils.formataddr((name_from, mail_from)) msg['To'] = email.utils.formataddr((name_to, mail_to)) msg['Subject'] = subject msg['Date'] = formatdate(localtime=True) msg.attach(MIMEText(text, 'html' if 'html' in text.lower() else '')) msg.set_charset('utf-8') for f in files: part = MIMEBase('application', "octet-stream") part.set_payload(open(f, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) server = smtplib.SMTP(servername, 587) try: server.set_debuglevel(performDebugging) # start the SMTP twitter server.ehlo() # start encryption if feature is supported by server if server.has_extn('STARTTLS'): server.starttls() # restart SMTP session over TLS connection server.ehlo() server.login(mail_from, password) server.sendmail(mail_from, mail_to, msg.as_string()) else: raise Exception('STARTTLS extension not supported by server') finally: server.quit()
def sendmail(mail_to,mail_content): msg = MIMEMultipart() msg['Subject'] = email.Header.Header(mail_sub,'gb2312') msg['From'] = mail_from msg['To'] = mail_to msg['Date'] = Utils.formatdate(localtime = 1) msg.set_charset('gb2312') msgText = MIMEText(mail_content,_subtype='plain',_charset='gb2312') msg.attach(msgText) try: s = smtplib.SMTP() s.connect(mail_host) s.login(mail_user,mail_pass) s.sendmail(mail_from, mail_to, msg.as_string()) s.quit() except Exception,e: print e
def mail(config, encoding, subject, body, out_data, err_data): msg = MIMEMultipart() msg.set_charset(encoding) subject = Header(subject, encoding) msg['From'] = config['user'] msg['To'] = config['user'] msg['Subject'] = subject part = MIMEBase('text', 'html', _charset=encoding) part.set_payload(body) Encoders.encode_base64(part) msg.attach(part) if not out_data is None: part = MIMEText(out_data, _charset=encoding) part.add_header('Content-Disposition', 'attachment', filename='stdout.txt') msg.attach(part) if not err_data is None: part = MIMEText(err_data, _charset=encoding) part.add_header('Content-Disposition', 'attachment', filename='stderr.txt') msg.attach(part) port = 25 if config['auth']: port = 587 mailServer = smtplib.SMTP(config['server'], port, local_hostname="localhost") if config['tls']: mailServer.ehlo() mailServer.starttls() mailServer.ehlo() if config['auth']: mailServer.login(config['user'], config['pass']) mailServer.sendmail(config['user'], config['user'], msg.as_string()) mailServer.close()
def create_mail(**kwargs): ''' Arguments: mailfrom mailto subject images [list] attachements [list] plaintext htmltext ''' strFrom = kwargs.get('mailfrom') CHARSET = 'iso-8859-2' msgRoot = MIMEMultipart('related') msgRoot.add_header('X-Mailer', kwargs.get('xmailer', 'Ella CMS')) subj = Header(kwargs.get('subject', 'CMS E-mail'), CHARSET) msgRoot['Subject'] = subj msgRoot['From'] = strFrom msgRoot['To'] = kwargs.get('mailto', '*****@*****.**') msgRoot.set_charset(CHARSET) msgRoot.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgAlternative.set_charset(CHARSET) msgRoot.attach(msgAlternative) text = kwargs['plaintext'] msgText = MIMEText(__uni2iso(text), 'plain', CHARSET) msgAlternative.attach(msgText) html = kwargs['htmltext'] html = html.replace('UTF-8', CHARSET) msgText = MIMEText(__uni2iso(html), 'html', CHARSET) msgAlternative.attach(msgText) for img in kwargs.get('images', []): __mimeImage(img, msgRoot) for at in kwargs.get('attachements', []): __mimeData(at, msgRoot) return msgRoot
def send_mail(send_from, send_to, subject, text, files=[], server="mail.pardus.org.tr"): msg = MIMEMultipart() msg.set_charset("utf-8") msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject text_ = MIMEText(text) text_.set_charset("utf-8") msg.attach( text_ ) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) try: smtp = smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close() except: return 0 return 1
def _create_email(self, from_addr, to_addr, subject, msg): """Create an email object. This object will be used to construct the reply. :param: from_addr (string) the address of the sender. :param: to_addr (string) the address of the recipient. :param: subject (string) the subject of the email. :param: msg (string) the content of the email. :return: (object) the email object. """ email_obj = MIMEMultipart() email_obj.set_charset("utf-8") email_obj['Subject'] = subject email_obj['From'] = from_addr email_obj['To'] = to_addr msg_attach = MIMEText(msg, 'plain') email_obj.attach(msg_attach) return email_obj
def main(): email_sender = smtplib.SMTP('localhost') today = datetime.now() tomorrow = datetime.now() + timedelta(days=1) try: results = urllib.urlopen(QUERY).read() except: raise results = json.loads(results) try: data = results['ask']['results']['items'] except KeyError: raise ValueError("Bad API data") for item in data: try: displaytitle = item['properties']['displaytitle'] except: #no title continue try: start_date = datetime.strptime(item['properties']['start_date'], "%Y-%m-%d %H:%M:%S" ) except ValueError: # cannot parse date, move to next time continue try: end_date = datetime.strptime(item['properties']['end_date'], "%Y-%m-%d %H:%M:%S" ) except ValueError: # cannot parse end date, make it equal to start_date + 1 end_date = start_date + timedelta(hour=1) when = None if sameday(today, start_date): when = u"Σήμερα" elif sameday(tomorrow, start_date): when = u"Αύριο" if when: # shorten url # url-quote wiki page title so we # generate correct links uri = item['uri'][43:].encode("utf-8") url = tinyurl.create(item['uri'][:43] + urllib.quote(uri) ).next() url = url.encode("utf-8") title = unescape(item['title']) tweet_message = u"%s στις %02d.%02d: %s %s" %\ (when, start_date.hour, start_date.minute, truncate(title, 140), url ) tweet_message = tweet_message.encode("utf-8") email_message = u"%s στις %02d.%02d: %s" %\ (when, start_date.hour, start_date.minute, title ) email_message = email_message.encode("utf-8") if TWEET: squawk(USERNAME, PASSWORD, tweet_message) if MAIL: msg = MIMEMultipart() msg.set_charset('utf-8') msg['Approved'] = MAIL_KEY msg['From'] = MAIL_FROM msg['To'] = MAIL_TO msg['Subject'] = '[hsgr-ann] %s' % email_message BODY = string.join( (email_message, u"\r\nΠερισσότερα: ".encode("utf-8") + url, "\r\n--\r\nHackerspace Little Event Bot", ), "\r\n" ) t = MIMEText(BODY) t.set_charset('utf-8') msg.attach(t) # attach ICS part = MIMEBase('text', "calendar") part.set_payload(string.join( ( "BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//hsgr/handcal//NONSGML v1.0//EN", "BEGIN:VEVENT", "UID:%s@hsgr" % displaytitle.encode('utf-8').replace(' ', '_'), "DTSTAMP;TZID=Europe/Athens:%04d%02d%02dT%02d%02d00" % ( start_date.year, start_date.month, start_date.day, start_date.hour, start_date.minute), "ORGANIZER;CN=Hackerspace:MAILTO:[email protected]", "DTSTART;TZID=Europe/Athens:%04d%02d%02dT%02d%02d00" % ( start_date.year, start_date.month, start_date.day, start_date.hour, start_date.minute), "DTEND;TZID=Europe/Athens:%04d%02d%02dT%02d%02d00" % ( end_date.year, end_date.month, end_date.day, end_date.hour, end_date.minute), "SUMMARY:%s" % email_message, "END:VEVENT", "END:VCALENDAR" ), "\r\n") ) part.add_header('Content-Disposition', 'attachment; filename="event.ics"') part.set_charset('utf-8') msg.attach(part) email_sender.sendmail(MAIL_FROM, MAIL_TO, msg.as_string())
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] # @added 20180524 - Task #2384: Change alerters to cc other recipients # The alerters did send an individual email to each recipient. This would be # more useful if one email was sent with the first smtp recipient being the # to recipient and the subsequent recipients were add in cc. if recipients: primary_recipient = False cc_recipients = False for i_recipient in recipients: if not primary_recipient: primary_recipient = str(i_recipient) if primary_recipient != i_recipient: if not cc_recipients: cc_recipients = str(i_recipient) else: new_cc_recipients = '%s,%s' % (str(cc_recipients), str(i_recipient)) cc_recipients = str(new_cc_recipients) logger.info( 'alert_smtp - will send to primary_recipient :: %s, cc_recipients :: %s' % (str(primary_recipient), str(cc_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: # @modified 20180519 - Feature #2378: Add redis auth to Skyline and rebrow if settings.REDIS_PASSWORD: REDIS_ALERTER_CONN = redis.StrictRedis( password=settings.REDIS_PASSWORD, unix_socket_path=settings.REDIS_SOCKET_PATH) else: REDIS_ALERTER_CONN = redis.StrictRedis( unix_socket_path=settings.REDIS_SOCKET_PATH) except: logger.error(traceback.format_exc()) 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') # @modified 20180417 - Bug #2358: set_axis_bgcolor method removed from Matplotlib - Luminosity # IssueID #49 'AxesSubplot' object has no attribute 'set_axis_bgcolor' # ax.set_axis_bgcolor('black') if hasattr(ax, 'set_facecolor'): ax.set_facecolor('black') else: 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) # @modified 20180417 - Bug #2358: set_axis_bgcolor method removed from Matplotlib - Luminosity # IssueID #49 'AxesSubplot' object has no attribute 'set_axis_bgcolor' # ax.set_axis_bgcolor('black') if hasattr(ax, 'set_facecolor'): ax.set_facecolor('black') else: 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()) # @modified 20180524 - Task #2384: Change alerters to cc other recipients # Do not send to each recipient, send to primary_recipient and cc the other # recipients, thereby sending only one email # for recipient in recipients: if primary_recipient: 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 # @modified 20180524 - Task #2384: Change alerters to cc other recipients # msg['To'] = recipient msg['To'] = primary_recipient # @added 20180524 - Task #2384: Change alerters to cc other recipients # Added Cc if cc_recipients: msg['Cc'] = cc_recipients 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: # @modified 20180524 - Task #2384: Change alerters to cc other recipients # Send to primary_recipient and cc_recipients # s.sendmail(sender, recipient, msg.as_string()) if cc_recipients: s.sendmail(sender, [primary_recipient, cc_recipients], msg.as_string()) else: s.sendmail(sender, primary_recipient, msg.as_string()) if settings.ENABLE_DEBUG or LOCAL_DEBUG: # logger.info('debug :: alert_smtp - message sent to %s OK' % str(recipient)) logger.info( 'debug :: alert_smtp - message sent OK to primary_recipient :: %s, cc_recipients :: %s' % (str(primary_recipient), str(cc_recipients))) except: logger.info(traceback.format_exc()) # logger.error('error :: alert_smtp - could not send email to %s' % str(recipient)) logger.error( 'error :: alert_smtp - could not send email to primary_recipient :: %s, cc_recipients :: %s' % (str(primary_recipient), str(cc_recipients))) 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
if evaluation > 2: exit() time.sleep(15) fromaddr = "robot@asterisk.*****.ru" toaddr = "tech@*****.net" msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "*** ASTERISK: Система оценки операторов" msg['Date'] = formatdate(localtime=True) msg.set_charset("utf-8") body = '''Что-то пошло не так и вам поставили плохую оценку :( ----------------------------------------------- Время звонка : %s Номер абонента : %s Номер оператора : %s Имя оператора : %s Оценка : %s Очередь : %s ----------------------------------------------- Файл с записью разговора прикреплен к сообщению. ''' % (date, in_num, op_num, op_name, evaluation, queue)
re_queued = re.compile('^reply: retcode .* queued as ([0-9A-F]{10,11})$') smtp_srv="mail.arc.world" port=25 _from='*****@*****.**' subject="Тест" receiver="8 921, <*****@*****.**>" #receiver="<*****@*****.**>, <*****@*****.**>" send_message="Просто тест" sender = _from receivers = receiver.split(",") ### msg = MIMEMultipart("alternative") msg = MIMEMultipart() msg.add_header('Content-Transfer-Encoding', '7bit') msg.set_charset("utf-8") msg["From"] = _from #msg["Subject"] = subject #msg["To"] = receiver msg['Subject'] = Header(subject, 'utf-8') msg["To"] = Header(receiver, 'utf-8') now = datetime.now(pytz.timezone('W-SU')) day = now.strftime('%a') date = now.strftime('%d %b %Y %X %z') msg["Date"] = day + ', ' + date part1 = MIMEText(send_message, "plain", "utf-8") msg.attach(part1) rc = 0 rcpt_refused = []
def _do_send(self, transport, event, format, recipients, formatter): output = formatter.format(transport, event.realm, format, event) subject = formatter.format_subject(transport, event.realm, format, event) alternate_format = formatter.get_format_alternative(transport, event.realm, format) if alternate_format: alternate_output = formatter.format(transport, event.realm, alternate_format, event) else: alternate_output = None rootMessage = MIMEMultipart("related") rootMessage.set_charset(self._charset) proj_name = self.env.project_name trac_version = get_pkginfo(trac.core).get('version', trac.__version__) announcer_version = get_pkginfo(announcerplugin).get('version', 'Undefined') rootMessage['X-Mailer'] = 'AnnouncerPlugin v%s on Trac ' \ 'v%s'%(announcer_version, trac_version) rootMessage['X-Trac-Version'] = trac_version rootMessage['X-Announcer-Version'] = announcer_version rootMessage['X-Trac-Project'] = proj_name rootMessage['X-Trac-Announcement-Realm'] = event.realm rootMessage['X-Trac-Announcement-ID'] = self._event_id(event) msgid = self._message_id(event.realm, self._event_id(event)) rootMessage['Message-ID'] = msgid if event.category is not 'created': rootMessage['In-Reply-To'] = msgid rootMessage['References'] = msgid rootMessage['Precedence'] = 'bulk' rootMessage['Auto-Submitted'] = 'auto-generated' provided_headers = formatter.format_headers(transport, event.realm, format, event) for key in provided_headers: rootMessage['X-Announcement-%s'%key.capitalize()] = \ to_unicode(provided_headers[key]) rootMessage['Date'] = formatdate() # sanity check if not self._charset.body_encoding: try: dummy = output.encode('ascii') except UnicodeDecodeError: raise TracError(_("Ticket contains non-ASCII chars. " \ "Please change encoding setting")) prefix = self.smtp_subject_prefix if prefix == '__default__': prefix = '[%s]' % self.env.project_name if event.category is not 'created': prefix = 'Re: %s'%prefix if prefix: subject = "%s %s"%(prefix, subject) rootMessage['Subject'] = Header(subject, self._charset) from_header = '"%s" <%s>'%( Header(self.smtp_from_name or proj_name, self._charset), self.smtp_from ) rootMessage['From'] = from_header if self.smtp_always_bcc: rootMessage['Bcc'] = self.smtp_always_bcc if self.smtp_to: rootMessage['To'] = '"%s"'%(self.smtp_to) if self.use_public_cc: rootMessage['Cc'] = ', '.join([x[2] for x in recipients if x]) rootMessage['Reply-To'] = self.smtp_replyto rootMessage.preamble = 'This is a multi-part message in MIME format.' if alternate_output: parentMessage = MIMEMultipart('alternative') rootMessage.attach(parentMessage) else: parentMessage = rootMessage if alternate_output: alt_msg_format = 'html' in alternate_format and 'html' or 'plain' msgText = MIMEText(alternate_output, alt_msg_format) parentMessage.attach(msgText) msg_format = 'html' in format and 'html' or 'plain' msgText = MIMEText(output, msg_format) del msgText['Content-Transfer-Encoding'] msgText.set_charset(self._charset) parentMessage.attach(msgText) start = time.time() package = (from_header, [x[2] for x in recipients if x], rootMessage.as_string()) if self.use_threaded_delivery: self.get_delivery_queue().put(package) else: self._transmit(*package) stop = time.time() self.log.debug("EmailDistributor took %s seconds to send."\ %(round(stop-start,2)))
def _do_send(self, transport, event, format, recipients, formatter): output = formatter.format(transport, event.realm, format, event) subject = formatter.format_subject(transport, event.realm, format, event) alternate_format = formatter.get_format_alternative( transport, event.realm, format) if alternate_format: alternate_output = formatter.format(transport, event.realm, alternate_format, event) else: alternate_output = None rootMessage = MIMEMultipart("related") rootMessage.set_charset(self._charset) proj_name = self.env.project_name trac_version = get_pkginfo(trac.core).get('version', trac.__version__) announcer_version = get_pkginfo(announcerplugin).get( 'version', 'Undefined') rootMessage['X-Mailer'] = 'AnnouncerPlugin v%s on Trac ' \ 'v%s'%(announcer_version, trac_version) rootMessage['X-Trac-Version'] = trac_version rootMessage['X-Announcer-Version'] = announcer_version rootMessage['X-Trac-Project'] = proj_name rootMessage['X-Trac-Announcement-Realm'] = event.realm event_id = self._event_id(event) rootMessage['X-Trac-Announcement-ID'] = event_id if self.set_message_id: msgid = self._message_id(event, event_id, 0) if event.category is not 'created': rootMessage['In-Reply-To'] = msgid rootMessage['References'] = msgid msgid = self._message_id(event, event_id, time.time()) rootMessage['Message-ID'] = msgid rootMessage['Precedence'] = 'bulk' rootMessage['Auto-Submitted'] = 'auto-generated' provided_headers = formatter.format_headers(transport, event.realm, format, event) for key in provided_headers: rootMessage['X-Announcement-%s'%key.capitalize()] = \ to_unicode(provided_headers[key]) rootMessage['Date'] = formatdate() # sanity check if not self._charset.body_encoding: try: dummy = output.encode('ascii') except UnicodeDecodeError: raise TracError(_("Ticket contains non-ASCII chars. " \ "Please change encoding setting")) prefix = self.smtp_subject_prefix if prefix == '__default__': prefix = '[%s]' % self.env.project_name if event.category is not 'created': prefix = 'Re: %s' % prefix if prefix: subject = "%s %s" % (prefix, subject) rootMessage['Subject'] = Header(subject, self._charset) from_header = '"%s" <%s>' % (Header(self.smtp_from_name or proj_name, self._charset), self.smtp_from) rootMessage['From'] = from_header if self.smtp_always_bcc: rootMessage['Bcc'] = self.smtp_always_bcc if self.smtp_to: rootMessage['To'] = '"%s"' % (self.smtp_to) if self.use_public_cc: rootMessage['Cc'] = ', '.join([x[2] for x in recipients if x]) rootMessage['Reply-To'] = self.smtp_replyto rootMessage.preamble = 'This is a multi-part message in MIME format.' if alternate_output: parentMessage = MIMEMultipart('alternative') rootMessage.attach(parentMessage) else: parentMessage = rootMessage if alternate_output: alt_msg_format = 'html' in alternate_format and 'html' or 'plain' msgText = MIMEText(alternate_output, alt_msg_format) parentMessage.attach(msgText) msg_format = 'html' in format and 'html' or 'plain' msgText = MIMEText(output, msg_format) del msgText['Content-Transfer-Encoding'] msgText.set_charset(self._charset) parentMessage.attach(msgText) start = time.time() package = (from_header, [x[2] for x in recipients if x], rootMessage.as_string()) if self.use_threaded_delivery: self.get_delivery_queue().put(package) else: self._transmit(*package) stop = time.time() self.log.debug("EmailDistributor took %s seconds to send."\ %(round(stop-start,2)))
print " ## ##" print " ##################################################\n\n" print "ATTENTION : L'utilisation de ce script a des fin malveillantes engage votre entière responsabilité." print "Je ne suis en aucun cas responsable des dommages causés par ce script.\n" print "PRÉREQUIS : Merci d'éditer le fichier 'liste_client.txt' avant l'utilisation de ce script !! \n\n" infos = setInformations() fichierHTML = open(raw_input("-> Chemin de la page HTML : "), "r").read() with open('liste_clients.txt') as clients: for email in clients: # FORMATTAGE DU MAIL mail = MIMEMultipart() mail.set_charset("utf-8") mail['From'] = infos[1] mail['Subject'] = infos[2] mail['To'] = email mail['Content-Type'] = "text/html; charset=utf-8" emailtext = MIMEText(fichierHTML, 'html') emailtext.set_charset('utf-8') mail.attach(emailtext) # CONFIGURATION DU SMTP serv = smtplib.SMTP(infos[0]) print "Configuration du serveur smtp : OK!"
def sendmail(to,sender,subject,body,attachments=None, cc=None,bcc=None): '''Sends away a mail with optional attachments using smtplib. This should be fired off in a new process / thread to avoid waiting for mail server attachments: [('filename','content of first attachment','mime/type'),...]''' if not attachments: attachments = [] outer = MIMEMultipart() outer.set_charset('utf-8') if cc is None: cc = '' if bcc is None: bcc = '' outer['To'] = to outer['From'] = sender outer['Cc'] = cc outer['Bcc'] = bcc outer['Subject'] = subject.encode('utf-8') outer.preamble = 'the holy preamble' attachments.insert(0,['',body,'text/plain']) for filename,content,mimetype in attachments: maintype, subtype = mimetype.split('/', 1) if maintype == 'text': # Note: we should handle calculating the charset try: content = content.encode('utf-8') except UnicodeDecodeError: #the incoming content might already encoded at utf-8 pass msg = MIMEText(content, _subtype=subtype) msg.set_charset('utf-8') 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 if filename: msg.add_header('Content-Disposition', 'attachment', filename=filename) outer.attach(msg) mail_server = config.get('hubspace.mail') if mail_server: server = smtplib.SMTP(mail_server) #this bit should actually fire off else: print `body` return fp = StringIO() g = Generator(fp) g.flatten(outer) final = fp.getvalue() to = [to] if cc: to.append(cc) if bcc: to.append(bcc) try: server.sendmail(sender, to, final) except smtplib.SMTPRecipientsRefused: print "SMTP RECIPIENT REFUSED" server.quit()
Session = sessionmaker(bind=engine) dbconn = Session() em = '*****@*****.**' em1 = '*****@*****.**' em2 = '*****@*****.**' em3 = '*****@*****.**' em4 = '*****@*****.**' em5 = '*****@*****.**' 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() delta1 = now + datetime.timedelta(days=-1) mess = "<b>%s</b><br/>Задачи, закрытые за %s.<br/>" % ( now.strftime('%Y-%m-%d %H:%M'), delta1.strftime('%Y-%m-%d')) mess += """ <br> <table border='1' cellpadding="0" cellspacing="0" ><tr><td>Исполнитель</td><td>Задачи</td></tr><tr><td colspan='2'>HELPDESK</td></tr> """ do = False for email, profile_id, fio in dbconn.query( Userprofile.email, Userprofile.id, Userprofile.fio ): #.filter(sqlalchemy.or_(Userprofile.system_id == 2, Userprofile.id.in_((54, 29, 30, 31)))): threads = [ str(r[0]) for r in dbconn.query(Threads.id_global).filter(
port=25 _from='*****@*****.**' subject="Тест" #receiver="8 921, <*****@*****.**>" #receiver="<*****@*****.**>, <*****@*****.**>" receiver="<*****@*****.**>" send_message="Изменение статуса счёта № 55181155\nЭто письмо сформировано автоматически, отвечать на него не нужно.\n\nЗаказ 55181155 отправлен: Автотрейдинг, № документа:спбп-04699 от 2014-04-24\nОтследить состояние доставки Вы можете по <a href=\"http://kipspb.ru/exp_mod/ae5000_invoicenumber.php?date=01.04.2014&number=%D1%81%D0%BF%D0%B1%D0%BF-00019\">ссылке</a>\n\nНа все Ваши вопросы Вам ответит Ваш персональный менеджер:\nАлексеева Александра, e-mail: [email protected],\nтелефон: (812)327-327-4\nС уважением,\nООО «КИП СПБ»" sender = _from receivers = receiver.split(",") ### msg = MIMEMultipart("alternative") ###msg = MIMEMultipart() msg.add_header('Content-Transfer-Encoding', '8bit') msg.set_charset("UTF-8") now = datetime.now(pytz.timezone('W-SU')) day = now.strftime('%a') date = now.strftime('%d %b %Y %X %z') msg["Date"] = day + ', ' + date msg["From"] = _from msg["To"] = Header(receiver, 'UTF-8') msg['Subject'] = Header(subject, 'UTF-8') #msg["Subject"] = subject #msg["To"] = receiver html_prefix = """\ <html> <head>