def form_valid(self, form): user = UserProfile.objects.get(user=request.user) product = Product.objects.get(id=request.GET.get('product_id')) try: margin = user.margin except: margin = 30.0 price_increased = (product.price * margin) / 100.00 price = product.price + price_increased to_email = [form.cleaned_data['Customer_email']] subject = '%s - %s' % (product.model, product.manufacturer) text_content = render_to_string('saas_app/email/product_info_email.txt') html_content = render_to_string('saas_app/email/product_info_email.html', {'text_content':text_content, 'price':price, 'product':product}) msg = EmailMultiAlternatives(subject, text_content, [user.email], to_email) msg.attach_alternative(html_content, 'text/html') msg.mixed_subtype = 'related' img_content_id = 'product' img_data = open(product.image_url(), 'rb') msg_img = MIMEImage(img_data.read()) img_data.close() msg_img.add_header('Content-ID', '<{}>'.format(product.picture)) msg.attach(msg_img) msg.send()
def build_picture_email(self, relative_directory, num_of_results, image_store_location, files_list): # Create the root message and fill in the from, to, and subject headers self.msgRoot['From'] = self.gmail_sender_username self.msgRoot['Subject'] = self.email_subject self.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. self.msgRoot.attach(self.msgAlternative) self.msgAlternative.attach(self.msgText) # We reference the image in the IMG SRC attribute by the ID we give it below self.msgAlternative.attach(self.msgPicText) # This example assumes the image is in the current directory for ii in range(num_of_results): fp = open(varutil.open_subdirectory(relative_directory, image_store_location, files_list[ii]), 'rb') msgImage = MIMEImage(fp.read()) print "Successfully added image " + files_list[ii] fp.close() # Define the image's ID as referenced above msgImage.add_header('Content-ID', '<image' + str(ii) + '>') self.msgRoot.attach(msgImage)
def send_mail(self,sender, receivers, text, html, path='FALSE'): msg = MIMEMultipart('related') msg_alt = MIMEMultipart('alternative') msg.attach(msg_alt) msg['To'] = self.to msg['From'] = email.utils.formataddr((self.titleFrom, '*****@*****.**')) msg['Subject'] = "%s" % (text) part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') msg_alt.attach(part1) msg_alt.attach(part2) fp = open(environ['SCRIPTS_HOME']+'/logo_firma.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<logo>') msg.attach(msgImage) if (path != 'FALSE'): fp = open(path, 'rb') msgImage = MIMEImage(fp.read()) fp.close() # Define the image's ID as referenced above msgImage.add_header('Content-ID', '<image1>') msg.attach(msgImage) try: mailServer = smtplib.SMTP('localhost') mailServer.sendmail(sender, receivers, msg.as_string()) logging.info("Successfully sent email") except Exception: logging.error("Error: unable to send email") mailServer.close()
def _create_msg(): msg = MIMEMultipart("related") msg["Subject"] = "Zabbix Screen Report: %s" % screen_name msg["From"] = me msg["To"] = ";".join(to_list) msg.preamble = "This is a multi-part message in MIME format." contents = "<h1>Screen %s</h1><br>" % screen_name contents += "<table>" for g_name in graphs: with open(os.path.join(GRAPH_PATH, g_name), "rb") as fp: msg_image = MIMEImage(fp.read()) msg_image.add_header("Content-ID", "<%s>" % g_name) msg.attach(msg_image) contents += "" contents += "<tr><td><img src='cid:%s'></td></tr>" % g_name contents += "</table>" msg_text = MIMEText(contents, "html") msg_alternative = MIMEMultipart("alternative") msg_alternative.attach(msg_text) msg.attach(msg_alternative) return msg
def send_email(request): try: recipients = request.GET["to"].split(",") url = request.GET["url"] proto, server, path, query, frag = urlsplit(url) if query: path += "?" + query conn = HTTPConnection(server) conn.request("GET", path) try: # Python 2.7+, use buffering of HTTP responses resp = conn.getresponse(buffering=True) except TypeError: # Python 2.6 and older resp = conn.getresponse() assert resp.status == 200, "Failed HTTP response %s %s" % (resp.status, resp.reason) rawData = resp.read() conn.close() message = MIMEMultipart() message["Subject"] = "Graphite Image" message["To"] = ", ".join(recipients) message["From"] = "composer@%s" % gethostname() text = MIMEText("Image generated by the following graphite URL at %s\r\n\r\n%s" % (ctime(), url)) image = MIMEImage(rawData) image.add_header("Content-Disposition", "attachment", filename="composer_" + strftime("%b%d_%I%M%p.png")) message.attach(text) message.attach(image) s = SMTP(settings.SMTP_SERVER) s.sendmail("composer@%s" % gethostname(), recipients, message.as_string()) s.quit() return HttpResponse("OK") except: return HttpResponse(format_exc())
def _doemail(request): cgiParams = request.GET assert 'recipients' in cgiParams and 'url' in cgiParams and 'title' in cgiParams, "Incomplete doemail, requires recipients, url, and title" import smtplib, httplib, urlparse from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage url = cgiParams['url'] title = cgiParams['title'] recipients = cgiParams['recipients'].split(',') proto, server, path, query, frag = urlparse.urlsplit(url) if query: path += '?' + query conn = httplib.HTTPConnection(server) conn.request('GET',path) resp = conn.getresponse() assert resp.status == 200, "Failed HTTP response %s %s" % (resp.status, resp.reason) rawData = resp.read() conn.close() message = MIMEMultipart() message['Subject'] = "Graphite Image" message['To'] = ', '.join(recipients) message['From'] = 'frontend@%s' % socket.gethostname() text = MIMEText( "Image generated by the following graphite URL at %s\r\n\r\n%s" % (time.ctime(),url) ) image = MIMEImage( rawData ) image.add_header('Content-Disposition', 'attachment', filename=title + time.strftime("_%b%d_%I%M%p.png")) message.attach(text) message.attach(image) server = smtplib.SMTP(settings.SMTP_SERVER) server.sendmail('frontend@%s' % socket.gethostname(),recipients,message.as_string()) server.quit() return stdout("Successfully sent %s to %s" % (url,cgiParams['recipients']))
def attach(self): """ Attaches file(s) from cwd. Can embed html image with header. Runs on default email package. """ # ## EMBED HTML IMAGE if self.embed: body_text = '%s<br><img src="cid:%s"><br>%s' % (self.embedh, self.embed, self.message) self.part = MIMEText(body_text, 'html') self.msg.attach(self.part) fp = open(self.embed, 'rb') img = MIMEImage(fp.read()) fp.close() img.add_header('Content-ID', self.embed) self.msg.attach(img) # ## OR DON'T ... else: self.part = MIMEText(self.message, "html") self.msg.attach(self.part) if self.files: for f in self.files: if f.strip().endswith('*'): f = ambiguous_extension(f) # print d_ self.part = MIMEBase('application', "octet-stream") self.part.set_payload(open(f, "rb").read()) Encoders.encode_base64(self.part) self.part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) self.msg.attach(self.part)
def sendEmail(smtpServer,smtpUser,smtpPwd,fromMail,toMail): ISOTIMEFORMAT='%Y-%m-%d-%H:%M' mailTime = time.strftime(ISOTIMEFORMAT,time.localtime()) msg = MIMEMultipart() msg['Subject'] = "磁盘扫描邮件[%s]"%scaning.getLocalIp() txt = MIMEText("At time:%s, Machine:[%s],disk idle:%s start to scanning disk."%(mailTime, scaning.getLocalIp(), int(scaning.check_disk_used()))) msg.attach(txt) fileName = r'/tmp/cldisky.pid' ctype, encoding = mimetypes.guess_type(fileName) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) att1 = MIMEImage((lambda f: (f.read(), f.close()))(open(fileName, 'rb'))[0], _subtype = subtype) att1.add_header('Content-Disposition', 'attachment', filename = fileName) # msg.attach(att1) xiaoxi = msg.as_string() try: smtp = smtplib.SMTP() smtp.connect(smtpServer) #smtp.login('%s'%smtpUser, '%s'%smtpPwd) #smtp.sendmail(fromMail, toMail, xiaoxi) #smtp.quit() smtp.docmd("AUTH LOGIN", base64.b64encode(smtpUser)) smtp.docmd(base64.b64encode(smtpPwd), "") smtp.sendmail(fromMail, toMail, xiaoxi) smtp.close return True except Exception, e: print str(e) return False
def send_email(request): try: recipients = request.GET['to'].split(',') url = request.GET['url'] proto, server, path, query, frag = urlsplit(url) if query: path += '?' + query conn = HTTPConnection(server) conn.request('GET',path) resp = conn.getresponse() assert resp.status == 200, "Failed HTTP response %s %s" % (resp.status, resp.reason) rawData = resp.read() conn.close() message = MIMEMultipart() message['Subject'] = "Graphite Image" message['To'] = ', '.join(recipients) message['From'] = 'composer@%s' % gethostname() text = MIMEText( "Image generated by the following graphite URL at %s\r\n\r\n%s" % (ctime(),url) ) image = MIMEImage( rawData ) image.add_header('Content-Disposition', 'attachment', filename="composer_" + strftime("%b%d_%I%M%p.png")) message.attach(text) message.attach(image) s = SMTP(settings.SMTP_SERVER) s.sendmail('composer@%s' % gethostname(),recipients,message.as_string()) s.quit() return HttpResponse( "OK" ) except: return HttpResponse( format_exc() )
def main(): msgRoot = MIMEMultipart('alternative') msgRoot.preamble = 'This is a multi-part message in MIME format.' with open(TEXT_FILE, 'r') as txt_f: text = txt_f.read() msgRoot.attach(MIMEText(text)) with open(HTML_FILE,'r') as html_f: html = html_f.read() if IMAGES: msgRelated = MIMEMultipart('related') msgRelated.attach(MIMEText(html, 'html')) for image in IMAGES: with open(image, 'rb') as img: msgImage = MIMEImage(img.read()) msgImage.add_header('Content-ID', os.path.split(image)[1]) ## clean up to remove the folder location in the for cid msgRelated.attach(msgImage) msgRoot.attach(msgRelated) else: msgRoot.attach(MIMEText(html, 'html')) if SEND: msgRoot['To'] = SEND[0] msgRoot['From'] = SEND[1] msgRoot['Subject'] = SEND[2] smtp = smtplib.SMTP('localhost') smtp.sendmail(SEND[0], SEND[1], msgRoot.as_string()) smtp.quit() print(msgRoot.as_string())
def send_email(percentage): import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEImage import MIMEImage from email.MIMEText import MIMEText # Prepare actual message msg = MIMEMultipart() msg['From'] = "*****@*****.**" # change to your mail msg['To'] = "*****@*****.**" # change to your mail msg['Subject'] = "RPi Camera Alarm!" imgcv = Image("image.jpg") imgcv.save("imagesend.jpg", quality=50) # reducing quality of the image for smaller size img1 = MIMEImage(open("imagesend.jpg","rb").read(), _subtype="jpg") img1.add_header('Content-Disposition', 'attachment; filename="image.jpg"') msg.attach(img1) part = MIMEText('text', "plain") part.set_payload(("Raspberry Pi camera alarm activated with level {:f}").format(percentage)) msg.attach(part) try: server = smtplib.SMTP("mail.htnet.hr", 25) #change to your SMTP provider server.ehlo() server.starttls() server.sendmail(msg['From'], msg['To'], msg.as_string()) server.quit() print 'Successfully sent the mail' except smtplib.SMTPException as e: print(e)
def embed_img(email, img_id, img_data): "Embeds an image in an html email" img = MIMEImage(img_data) img.add_header('Content-ID', '<%s>' % img_id) img.add_header('Content-Disposition', 'inline; filename=logo.jpg') email.attach(img)
def render(self): if not self.subject: raise Exception("No Subject") elif not self.html_template or not self.text_template: raise Exception("No Template") else: self.subject = self.subject % self.context self.raw_body_html = render_template(self.html_template, **self.context) self.raw_body_text = render_template(self.text_template, **self.context) msg_root = MIMEMultipart('related') msg_root['Subject'] = self.subject msg_root['From'] = _encode_str(self.email_from) msg_root['To'] = _encode_str(self.recipient) msg_alternative = MIMEMultipart('alternative') msg_root.attach(msg_alternative) msg_text = MIMEText(_encode_str(self.raw_body_text)) msg_alternative.attach(msg_text) msg_text = MIMEText(_encode_str(self.raw_body_html), 'html') msg_alternative.attach(msg_text) for filename in self.list_images: fullpath = os.path.join(STATIC_FOLDER,"layout/emails/",filename) fp = open(fullpath, 'rb') msg_image = MIMEImage(fp.read()) fp.close() msg_image.add_header('Content-ID', '<%s>' % filename.replace(".","")) msg_root.attach(msg_image) return msg_root.as_string()
def send_mail(report_contents): msg = MIMEMultipart() msg['Subject'] = SUBJECT msg['From'] = EMAIL_FROM msg['To'] = ', '.join(EMAIL_TO) fp = open('/home/pierre/es_email_intel/wordcloud.png', 'rb') try: msgImage = MIMEImage(fp.read()) except: fp = open('/home/pierre/es_email_intel/1x1.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<wordcloud>') msg.attach(msgImage) part = MIMEBase('application', "octet-stream") part.set_payload(report_contents) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="report.html"') msg.attach(part) server = smtplib.SMTP(EMAIL_SERVER) server.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
def emailCharts(fromaddr, toaddrs, subject, charts, server, username, password): msgRoot = MIMEMultipart() msgRoot['Subject'] = subject msgRoot['From'] = fromaddr msgRoot['To'] = toaddrs msgRoot.preamble = subject msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText(subject) msgAlternative.attach(msgText) html = '<br>' for chart in charts: html = html + '<img src="cid:' + chart[0] + '"><br>' msgText = MIMEText(html, 'html') msgAlternative.attach(msgText) for chart in charts: fp = open(chart[1], 'rb') img = MIMEImage(fp.read()) fp.close() img.add_header('Content-ID', '<' + chart[0] + '>') msgRoot.attach(img) smtp = smtplib.SMTP(server) smtp.starttls() smtp.login(username, password) smtp.sendmail(fromaddr, toaddrs, msgRoot.as_string()) smtp.quit()
def upload_attachments(to, gmail_user, gmail_pwd, attachment_names): for attachment in attachment_names: file_to_upload = 'media/%s.png' % (attachment,) if not os.path.exists(file_to_upload): print '!!! error: attachment %s was not generated correctly' % (attachment,) sys.exit(1) to = 'media+' + to for attachment in attachment_names: print 'uploading attachment for %s' % (attachment,) file_to_upload = 'media/%s.png' % (attachment,) content = MIMEMultipart() content['From'] = gmail_user content['To'] = to content['Subject'] = 'attachment %s\n' % (attachment,) img = MIMEImage(file(file_to_upload).read()) img.add_header('Content-Type', 'image/png', name=attachment + '.png') img.add_header('Content-Disposition', 'attachment', filename=attachment + '.png') content.attach(img) msg = content.as_string() smtpserver = smtplib.SMTP("smtp.gmail.com", 587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo smtpserver.login(gmail_user, gmail_pwd) smtpserver.sendmail(gmail_user, to, msg) smtpserver.close()
def send_email(html): addressees = ['*****@*****.**'] fromaddr = '*****@*****.**' password = '******' toaddr = ', '.join(addressees) msg = MIMEMultipart() msg['from'] = fromaddr msg['to'] = toaddr msg['subject'] = 'TEST EMAIL' # msg.attach(MIMEText(text, 'plain')) msg.attach(MIMEText(html, 'html')) fp = open('brief-news-logo.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image1>') msg.attach(msgImage) server = smtplib.SMTP_SSL('smtp.zoho.com', 465) server.ehlo() server.login(fromaddr, password) text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit()
def send_mail(etc=""): open_ports = get_ports() ports = pickle.load(open("tcp_ports", "rb")) text = """ Open Ports:<br><br> <table cellspacing="15"> <tr> <th>Port</th> <th>Service</th> </tr> """ for p in open_ports: text += "<tr><td>%s</td><td>%s</td></tr>" % (p, lsofi(p)) parser = SafeConfigParser() parser.read("./stats.conf") msg = MIMEMultipart('related') msg['Subject'] = "Traffic report from %s" % (socket.getfqdn()) msg['From'] = parser.get('email', 'from') msg['To'] = parser.get('email', 'to') msg.preamble = 'This is a multi-part message in MIME format.' body = """ %s<br><br> <img src="cid:graph_packets"><br><br> <img src="cid:graph_conns"><br><br> <img src="cid:graph_bandwidth"><br><br>%s</table>""" % (etc, text) msgBody = MIMEText(body, 'html') msg.attach(msgBody) attachments = [ ('packets.png', 'graph_packets'), ('conns.png', 'graph_conns'), ('bps.png', 'graph_bandwidth') ] for attachment in attachments: fp = open(attachment[0], 'rb') img = MIMEImage(fp.read()) img.add_header('Content-ID', attachment[1]) fp.close() msg.attach(img) s = smtplib.SMTP(parser.get('email', 'smtp_server'), parser.getint('email', 'port')) if parser.getboolean('email', 'auth'): s.ehlo() if parser.getboolean('email', 'use_tls'): s.starttls() s.ehlo() if parser.getboolean('email', 'auth'): s.login(parser.get('email', 'username'), parser.get('email', 'password')) s.sendmail(parser.get('email', 'from'), [parser.get('email', 'to')], msg.as_string()) s.quit()
def process(options, args): config = get_config(options) # Write the email msg = MIMEMultipart() msg['From'] = config['fromaddr'] msg['To'] = config['toaddrs'] msg['Subject'] = options.subject body = options.body msg.attach(MIMEText(body, 'plain')) # Attach image if options.image_file: try: filename = open(options.image_file, "rb") attach_image = MIMEImage(filename.read()) attach_image.add_header('Content-Disposition', 'attachment; filename = %s'%options.image_file) msg.attach(attach_image) filename.close() except: msg.attach(MIMEText('Image attachment error', 'plain')) # Converting email to text text = msg.as_string() # The actual mail send server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.ehlo() server.login(config['username'],config['password']) server.sendmail(config['fromaddr'], config['toaddrs'], text) server.quit()
def create_email(from_address, to_address, subject, message, cc=None, image=None, pdf=None): msg = MIMEMultipart('alternative') msg['From'] = from_address msg['To'] = to_address msg['Subject'] = subject if cc: msg['Cc'] = cc if image: msg_img = MIMEImage(open(image, 'rb').read()) msg_img.add_header('Content-ID', '<image>') msg_img.add_header('Content-Disposition', 'inline', filename=image) if pdf: msg_pdf = MIMEApplication(open(pdf, 'rb').read(), 'pdf') msg_pdf.add_header('Content-ID', '<pdf>') msg_pdf.add_header('Content-Disposition', 'attachment', filename=pdf) msg_pdf.add_header('Content-Disposition', 'inline', filename=pdf) msg.attach(MIMEText(message, 'html')) msg.attach(msg_img) msg.attach(msg_pdf) return msg.as_string()
def send_invoice(page_type, user): if page_type.send_email: subject= page_type.email_subject try: attachment = open(page_type.attachment.url[1:],'r') except: attachment=None email_to= [user.email] plaintext = get_template('pages/custom_email.txt') htmly = get_template('pages/custom_email.html') try: sponsorship = SponsorshipPackage.objects.get(title=user.companyprofile.sponsor) except: sponsorship = None d = Context({'sponsorship':sponsorship, 'paypal_info': PayPalInfo.objects.all()[0], 'company':user.companyprofile}) text_content = plaintext.render(d) html_content = htmly.render(d) email = EmailMultiAlternatives(subject, text_content, 'Career Fair Staff', email_to) email.attach_alternative(html_content, "text/html") email.mixed_subtype = 'related' f = "/opt/myenv/careerfair/static/media/uploads/static images/header.png" fp = open(f, 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<header.png>'.format(f)) msg_img.add_header("Content-Disposition", "inline", filename="header.png") email.attach(msg_img) email.send()
def send_multipart_email(subject, text_part1, text_part2, img_url, replyto, to_list): msgRoot = MIMEMultipart("related") msgRoot["Subject"] = subject msgRoot["From"] = FROM msgRoot["To"] = ", ".join(to_list) msgRoot.add_header("reply-to", replyto) msgRoot.preamble = "This is a multi-part message in MIME format." msgAlternative = MIMEMultipart("alternative") msgRoot.attach(msgAlternative) msgText = MIMEText(text_part1 + text_part2) msgAlternative.attach(msgText) msgText = MIMEText( text_part1.replace("\r\n", "<br />") + '<img src="cid:image1">' + text_part2.replace("\r\n", "<br />"), "html" ) msgAlternative.attach(msgText) content = urllib2.urlopen(img_url).read() msgImage = MIMEImage(content) msgImage.add_header("Content-ID", "<image1>") msgRoot.attach(msgImage) smtp = smtplib.SMTP() smtp.connect("smtp.gmail.com", 587) smtp.ehlo() smtp.starttls() smtp.login(gmail_user, gmail_pwd) smtp.sendmail(FROM, to_list, msgRoot.as_string()) smtp.quit()
def SendEmail(subject, msgText, to, user,password, alias, imgName, replyTo=None): sender = alias try: conn = SMTP('smtp.gmail.com', 587) msg = MIMEMultipart() msg.attach(MIMEText(msgText, 'html')) msg['Subject']= subject msg['From'] = sender msg['cc'] = to #msg['cc'] = ', '.join(to) if replyTo: msg['reply-to'] = replyTo if imgName != None: fp = open(imgName, 'rb') img = MIMEImage(fp.read(), _subtype="pdf") fp.close() img.add_header('Content-Disposition', 'attachment', filename = imgName) msg.attach(img) conn.ehlo() conn.starttls() conn.set_debuglevel(False) conn.login(user, password) try: conn.sendmail(sender, to, msg.as_string()) finally: conn.close() except: print "Unexpected error:", sys.exc_info()[0]
def ComposeLetter(self, reciever_email, santa_name, reciever_name ): #With HTML support means "related" message_root = MIMEMultipart("related") message_root['Subject'] = self.Subject.format(santa_name) message_root['From'] = self.SenderName message_root['To'] = reciever_email alternate = MIMEMultipart('alternative') message_root.attach(alternate) plain_text = MIMEText("Тебе выпал: {}".format(reciever_name), "", "utf-8") alternate.attach(plain_text) html_pattern_file_name = "letter_pattern.html" html_pattern_file = codecs.open(html_pattern_file_name, "r", "utf-8") html_pattern = html_pattern_file.read() html_pattern_file.close() html_message = MIMEText(html_pattern, "html", "utf-8") alternate.attach(html_message) image_file_name = self.ComposeImage(santa_name, reciever_name) image_file = open(image_file_name, "rb") message_image = MIMEImage(image_file.read()) image_file.close() message_image.add_header("Content-ID", "<main_image>") message_root.attach(message_image) return message_root
def set_image_email(node,msg): # {{{ if not node.getchildren(): if node.tag=='img' : content = '' try : if node.get('name') and node.get('name').find('http') >=0: content=urllib2.urlopen(node.get('name')).read() node.set('src', node.get('name')) elif node.get('src'): if node.get('src').find('data:image/gif;base64,') >= 0: content = base64.decodestring(node.get('src').replace('data:image/gif;base64,', '')) elif node.get('src').find('http') >= 0: content=urllib2.urlopen(node.get('src')).read() msgImage = MIMEImage(content) image_name = ''.join( Random().sample(string.letters+string.digits, 12) ) msgImage.add_header('Content-ID','<%s>'%image_name) msg.attach(msgImage) node.set('src',"cid:%s"%image_name) except : return 'image_content_error' else: for n in node.getchildren(): state = set_image_email(n,msg) if state == 'image_content_error' : return state
def main(): images = os.listdir(IMAGE_DIR) encoded_images = {} strFrom = '' strTo = '' msgRoot = MIMEMultipart('alternative') msgRoot['Subject'] = "" msgRoot['To'] = strTo msgRoot['From'] = strFrom msgRoot.preamble = 'This is a multi-part message in MIME format.' with open('text.txt', 'r') as text: text = text.read() msgRoot.attach(MIMEText(text)) if not images: msgRoot.attach(MIMEText(render_template(), 'html')) else: msgRelated = MIMEMultipart('related') msgRelated.attach(MIMEText(render_template(images), 'html')) for image in images: with open(image, 'rb') as img: byte_data = img.read() msgImage = MIMEImage(byte_data) msgImage.add_header('Content-ID', image) msgRelated.attach(msgImage) b64 = b64encode(byte_data) encoded_images[image]=b64 msgRoot.attach(msgRelated) with open("../../public_html/preview.html", 'w') as preview: preview.write(render_template(images, preview=encoded_images)) print(msgRoot.as_string())
def send_mail(text, content, filename=''): global email_username, email_password fromaddr = '*****@*****.**' recipients = ["*****@*****.**"] toaddrs = ", ".join(recipients) username = email_username password = email_password msgRoot = MIMEMultipart('related') msgRoot['Subject'] = text msgRoot['From'] = fromaddr msgRoot['To'] = toaddrs msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText(content, 'html') msgAlternative.attach(msgText) if filename is not '': img = MIMEImage(open(filename,"rb").read(), _subtype="png") img.add_header('Content-ID', '<carpedm20>') msgRoot.attach(img) server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username,password) server.sendmail(fromaddr, recipients, msgRoot.as_string()) server.quit() print " - mail sended"
def edit(request, class_id, place=None): class_info = get_object_or_404(Class, pk=class_id) power = False if place == "1": active_nav = 'CLASSES' place = 'base/base.html' else: active_nav = 'DASHBOARD' place = 'base/base_admin.html' if request.method == "POST": formEdit = EditForm(data=request.POST) power = True if formEdit.is_valid(): temp = formEdit.cleaned_data if len(Teacher.objects.filter(user_id = request.user.id)) > 0: teacher = Teacher.objects.get(user_id = request.user.id) school_info = teacher.school.all()[0] elif len(Admin.objects.filter(user_id = request.user.id)) > 0: admin_school = Admin.objects.get(user_id = request.user.id) school_info = admin_school.school class_info.school = school_info class_info.year_level = temp['year_level'] class_info.section = temp['section'] class_info.subject = temp['subject'] class_info.academic_year = temp['academic_year'] class_info.save() try: check_ifAdmin = Admin.objects.get(user=request.user) template = get_template('app_classes/notification.html').render( Context({ 'sender': check_ifAdmin.user, 'school': temp['school'], 'year_level' : temp['year_level'], 'section' : temp['section'], 'subject' : temp['subject'], 'academic_year' : temp['academic_year'] }) ) fp = open('./static/base/img/icons/[email protected]', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image1>') mailSend = EmailMessage('[TECS] Class Information Changed', template, '*****@*****.**', [class_info.teacher.user.email] ) mailSend.content_subtype = "html" # Main content is now text/html mailSend.attach(msgImage) mailSend.send() except: pass return viewClassList(request, class_id, '' ,'Changes to class details were saved.') if not power: formEdit = EditForm(initial={'year_level':class_info.year_level, 'section':class_info.section, 'academic_year':class_info.academic_year, 'subject':class_info.subject}) avatar = UserProfile.objects.get(user_id = request.user.id).avatar return render(request, 'app_classes/teacher_editClass.html', {'avatar':avatar, 'place':place, 'active_nav':active_nav, 'class_info':class_info, 'formEdit':formEdit})
def invia_mail(utente, template, to, subject,dominio, from_email=''): from django.core.mail import EmailMultiAlternatives from django.template.loader import get_template from django.template import Context from email.MIMEImage import MIMEImage from django.conf import settings dominio = str(dominio).replace("www.", "") d = Context({ 'nome': utente.first_name, 'cognome': utente.last_name , 'domain': dominio, 'id': utente.id, 'confirmation_code': utente.profilo.confirmation_code }) plaintext = get_template('accounts/email/'+template+'.txt') htmly = get_template('accounts/email/'+template+'.html') html_content = htmly.render(d) text_content = plaintext.render(d) if not from_email: from_email = settings.EMAIL_CLIENTE msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") #logo fp = open(settings.STATIC_ROOT + "/img/logo.png", 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format("logo.jpg")) msg.attach(msg_img) return msg.send()
def enviar_correo(asunto, contenido, correo, custom_filename, adjuntos=[]): if not type(custom_filename) is list: custom_filename = [custom_filename] try: msg = EmailMessage(asunto, contenido, to=correo) msg.content_subtype = "html" # msg.attach_alternative(contenido, "text/html") # msg.mixed_subtype = 'related' for f in custom_filename: fp = open(path.join(BASE_DIR, 'static', 'img', f), 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format(f)) msg.attach(msg_img) if adjuntos: for ad in adjuntos: try: msg.attach_file(ad) except Exception as e: msg.attach_file(ad[1:]) msg.send() except Exception as e: print '=======>Error al enviar correo<=========', e # raise e return False return True
def cbr_email(user, password, bid, to, key): h1 = "" h2 = "" working = "" if not bid: print "You must provide a bridge ID using the --bid option." exit() else: print "Requesting list" r = requests.get('http://geras.1248.io/serieslist', auth=(key, '')) allseries = json.loads(r.content) serieslist = [] for t in allseries: if (bid + "/") in t: print t serieslist.append(t) startTime = start() endTime = startTime + oneDay print "startTime:", nicetime(startTime), " endTime:", nicetime(endTime) # Read HTML file with open(fileName, "r") as f: h1 = f.read() # Because there can be "illigal" ASCII characters in the HTML file: i = 0 for c in h1: if ord(c) > 127: #print "Replaced:", c, ord(c) h2 += " " else: h2 += c # Headers h1 = h2.replace("nnn", bid) h2 = h1.replace("<date1>", nicedate(startTime)) h1 = h2.replace("<date2>", nicedate(endTime)) working = "h1" timeseries = {} col = 1 for gerasPath in serieslist: if not ( "Light-Mesh" in gerasPath or "battery" in gerasPath or "connected" in gerasPath or "luminance" in gerasPath or "magnet" in gerasPath or "button" in gerasPath or "ir_temperature" in gerasPath or ("tag_ti" in gerasPath.lower() and "temperature" in gerasPath) or ("tbk" in gerasPath.lower() and "binary" in gerasPath.lower())): # ("binary" in gerasPath.lower() and "coffee" in gerasPath.lower()) or # ("binary" in gerasPath.lower() and "coffee_cupboard" in gerasPath.lower())): url = gerasurl + 'series/' + gerasPath + '?start=' + str( startTime) + '&end=' + str(endTime) #print "\nurl:", url r = requests.get(url, auth=(key, '')) timeseries[gerasPath] = json.loads(r.content) #print "timeseries:", json.dumps(timeseries, indent=4) series = timeseries[gerasPath]["e"] # split it into BID, Name, Type (_ is a sledgehammer - see below) #ss = re.split('\W+|/|-|_',gerasPath) ss = re.split('\W+|/|-', gerasPath) print "First ss:", ss #exit() # Change some "types" according to sensor type length = len(ss) for i in range(0, len(ss)): if "pir" in ss[i].lower(): ss[length - 1] = ss[length - 1].replace( "binary", "Activity") if "tbk" in ss[i].lower(): ss[length - 1] = ss[length - 1].replace("binary", "Switch") if "binary" in ss: if "Kettle" or "Door" in ss: del ss[ss.index("binary")] #print "What's left?:",ss # get rid of blank field, BID & sensor type unless it's a KM if "KM" in ss: del ss[0:2] else: del ss[0:3] # squash it down to three lines for the template if len(ss) > 4: ss[0] = ss[0] + " " + ss[1] del ss[1] ss[1] = ss[1] + " " + ss[2] del ss[2] elif len(ss) > 3: ss[1] = ss[1] + " " + ss[2] del ss[2] # There are four possible fields plus the type. # And there should only be underscores left for i in range(0, len(ss)): ss[i] = ss[i].replace("_", " ") #print "ss[",i,"]:", ss[i], "\n" #print "What's left now?:",ss for value in ss[0:len(ss)]: holder = "S_" + str(col) + "_name" + str(ss.index(value) + 1) print "holder:", holder, " value:", value if working == "h1": h2 = h1.replace(holder, value) working = "h2" else: h1 = h2.replace(holder, value) working = "h1" # build table entries if series and "magsw" in gerasPath.lower( ): # Always on doors & drawers for now for stepTime in range(startTime, startTime + oneDay, tenMinutes): holder = "S_" + str(col) + "_" + stepHourMin(stepTime) if activeInTenMinutes(series, stepTime): value = "Open" else: value = "" if working == "h1": h2 = h1.replace(holder, value) working = "h2" else: h1 = h2.replace(holder, value) working = "h1" elif series and "power" in gerasPath.lower(): for stepTime in range(startTime, startTime + oneDay, tenMinutes): holder = "S_" + str(col) + "_" + stepHourMin(stepTime) if powerInTenMinutes(series, stepTime): value = "On" else: value = "" if working == "h1": h2 = h1.replace(holder, value) working = "h2" else: h1 = h2.replace(holder, value) working = "h1" elif series and "temperature" in gerasPath.lower(): prev_temperature = "none" for stepTime in range(startTime, startTime + oneDay, tenMinutes): holder = "S_" + str(col) + "_" + stepHourMin(stepTime) value = tempInTenMinutes(series, stepTime) if value == "": if prev_temperature != "none": value = prev_temperature else: prev_temperature = value if working == "h1": h2 = h1.replace(holder, value) working = "h2" else: h1 = h2.replace(holder, value) working = "h1" elif series and "pir" in gerasPath.lower( ) and "binary" in gerasPath.lower(): for stepTime in range(startTime, startTime + oneDay, tenMinutes): holder = "S_" + str(col) + "_" + stepHourMin(stepTime) if activeInTenMinutes(series, stepTime): value = "A" else: value = "" if working == "h1": h2 = h1.replace(holder, value) working = "h2" else: h1 = h2.replace(holder, value) working = "h1" else: for stepTime in range(startTime, startTime + oneDay, tenMinutes): holder = "S_" + str(col) + "_" + stepHourMin(stepTime) value = "-" if working == "h1": h2 = h1.replace(holder, value) working = "h2" else: h1 = h2.replace(holder, value) working = "h1" print "\n" col += 1 # Remove any unused holders if working == "h1": h2 = re.sub("S_[0-9]+_name[0-9]+", "", h1, 0) h1 = re.sub("S_[0-9]+_[0-9]+", "", h2, 0) else: h1 = re.sub("S_[0-9]+_name[0-9]+", "", h2, 0) h2 = re.sub("S_[0-9]+_[0-9]+", "", h1, 0) if working == "h1": htmlText = h1 else: htmlText = h2 # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = "Activity for bridge " + bid + " from " + nicedate( startTime) + " to " + nicedate(endTime) msg['From'] = "Bridges <*****@*****.**>" recipients = to.split(',') [p.strip(' ') for p in recipients] if len(recipients) == 1: msg['To'] = to else: msg['To'] = ", ".join(recipients) # Create the body of the message (a plain-text and an HTML version). text = "Content only available with HTML email clients\n" # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') part2 = MIMEText(htmlText, 'html') fp = open('image001.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close() # Define the image's ID as referenced above msgImage.add_header('Content-ID', '<image001.png>') msg.attach(msgImage) msg.attach(part1) msg.attach(part2) mail = smtplib.SMTP('smtp.gmail.com', 587) mail.ehlo() mail.starttls() mail.login(user, password) mail.sendmail(user, recipients, msg.as_string()) mail.quit()
msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText(TEXT) msgAlternative.attach(msgText) msgText = MIMEText(HTML, 'html') msgAlternative.attach(msgText) # Attach images if os.path.exists(logoImagePath): fp = open(logoImagePath, 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<icinga2_logo>') msgRoot.attach(msgImage) if args.panelid: GET = urllib2.Request(GRAFANAPNG) GET.add_header('Authorization', 'Bearer ' + GRAFANAAPIKEY) GRAPH = urllib2.urlopen(GET) PNG = GRAPH.read() msgImage = MIMEImage(PNG) msgImage.add_header('Content-ID', '<grafana_perfdata>') msgRoot.attach(msgImage) # Send mail using SMTP smtp = smtplib.SMTP() try: smtp.connect(SERVER)
def alert_smtp(datapoint, metric_name, expiration_time, metric_trigger, algorithm): sender = settings.BOUNDARY_SMTP_OPTS['sender'] matched_namespaces = [] for namespace in settings.BOUNDARY_SMTP_OPTS['recipients']: CHECK_MATCH_PATTERN = namespace check_match_pattern = re.compile(CHECK_MATCH_PATTERN) pattern_match = check_match_pattern.match(metric_name) if pattern_match: matched_namespaces.append(namespace) matched_recipients = [] for namespace in matched_namespaces: for recipients in settings.BOUNDARY_SMTP_OPTS['recipients'][namespace]: matched_recipients.append(recipients) def unique_noHash(seq): seen = set() return [x for x in seq if str(x) not in seen and not seen.add(str(x))] recipients = unique_noHash(matched_recipients) # 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. primary_recipient = False cc_recipients = False if recipients: 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))) alert_algo = str(algorithm) alert_context = alert_algo.upper() # @added 20191008 - Feature #3194: Add CUSTOM_ALERT_OPTS to settings try: main_alert_title = settings.CUSTOM_ALERT_OPTS['main_alert_title'] except: main_alert_title = 'Skyline' try: app_alert_context = settings.CUSTOM_ALERT_OPTS[ 'boundary_alert_heading'] except: app_alert_context = 'Boundary' # @modified 20191002 - Feature #3194: Add CUSTOM_ALERT_OPTS to settings # Use alert_context # unencoded_graph_title = 'Skyline Boundary - %s at %s hours - %s - %s' % ( # alert_context, graphite_previous_hours, metric_name, datapoint) unencoded_graph_title = '%s %s - %s at %s hours - %s - %s' % ( main_alert_title, app_alert_context, alert_context, graphite_previous_hours, metric_name, datapoint) # @added 20181126 - Task #2742: Update Boundary # 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('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(metric_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: # @modified 20191002 - Feature #3194: Add CUSTOM_ALERT_OPTS to settings # unencoded_graph_title = 'Skyline Boundary - %s at %s hours - derivative graph - %s - %s' % ( # alert_context, graphite_previous_hours, metric_name, datapoint) unencoded_graph_title = '%s %s - %s at %s hours - derivative graph - %s - %s' % ( main_alert_title, app_alert_context, alert_context, graphite_previous_hours, metric_name, datapoint) graph_title_string = quote(unencoded_graph_title, safe='') graph_title = '&title=%s' % graph_title_string # @added 20181126 - Bug #2498: Incorrect scale in some graphs # Task #2742: Update Boundary # If -xhours is used the scale is incorrect if x hours > than first # retention period, passing from and until renders the graph with the # correct scale. graphite_port = '80' if settings.GRAPHITE_PORT != '': graphite_port = str(settings.GRAPHITE_PORT) until_timestamp = int(time()) from_seconds_ago = graphite_previous_hours * 3600 from_timestamp = until_timestamp - from_seconds_ago graphite_from = dt.datetime.fromtimestamp( int(from_timestamp)).strftime('%H:%M_%Y%m%d') logger.info('graphite_from - %s' % str(graphite_from)) graphite_until = dt.datetime.fromtimestamp( int(until_timestamp)).strftime('%H:%M_%Y%m%d') logger.info('graphite_until - %s' % str(graphite_until)) graphite_target = 'target=cactiStyle(%s)' if known_derivative_metric: graphite_target = 'target=cactiStyle(nonNegativeDerivative(%s))' # @modified 20190520 - Branch #3002: docker # Use GRAPHITE_RENDER_URI # link = '%s://%s:%s/render/?from=%s&until=%s&%s%s%s&colorList=%s' % ( # settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, graphite_port, # str(graphite_from), str(graphite_until), graphite_target, # settings.GRAPHITE_GRAPH_SETTINGS, graph_title, # graphite_graph_line_color) link = '%s://%s:%s/%s/?from=%s&until=%s&%s%s%s&colorList=%s' % ( settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, graphite_port, settings.GRAPHITE_RENDER_URI, str(graphite_from), str(graphite_until), graphite_target, settings.GRAPHITE_GRAPH_SETTINGS, graph_title, graphite_graph_line_color) content_id = metric_name image_data = None if settings.BOUNDARY_SMTP_OPTS.get('embed-images'): try: # @modified 20170913 - Task #2160: Test skyline with bandit # Added nosec to exclude from bandit tests image_data = urllib2.urlopen(link).read() # nosec except urllib2.URLError: image_data = None # 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 # @modified 20191002 - Feature #3194: Add CUSTOM_ALERT_OPTS to settings # body = '%s :: %s <br> Next alert in: %s seconds <br> skyline Boundary alert - %s <br><a href="%s">%s</a>' % ( # datapoint, metric_name, expiration_time, alert_context, link, img_tag) body = '%s :: %s <br> Next alert in: %s seconds <br> %s %s alert - %s <br><a href="%s">%s</a>' % ( main_alert_title, app_alert_context, datapoint, metric_name, expiration_time, alert_context, link, img_tag) # @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: logger.info( 'alert_smtp - will send to primary_recipient :: %s, cc_recipients :: %s' % (str(primary_recipient), str(cc_recipients))) msg = MIMEMultipart('alternative') # @modified 20191002 - Feature #3194: Add CUSTOM_ALERT_OPTS to settings # msg['Subject'] = '[Skyline alert] ' + 'Boundary ALERT - ' + alert_context + ' - ' + datapoint + ' - ' + metric_name msg['Subject'] = '[' + main_alert_title + ' alert] ' + app_alert_context + ' ALERT - ' + alert_context + ' - ' + datapoint + ' - ' + metric_name 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')) if image_data is not None: msg_attachment = MIMEImage(image_data) msg_attachment.add_header('Content-ID', '<%s>' % content_id) msg.attach(msg_attachment) s = SMTP('127.0.0.1') # @modified 20180524 - Task #2384: Change alerters to cc other recipients # Send to primary_recipient and cc_recipients # s.sendmail(sender, recipient, msg.as_string()) try: if cc_recipients: s.sendmail(sender, [primary_recipient, cc_recipients], msg.as_string()) else: s.sendmail(sender, primary_recipient, msg.as_string()) except: logger.info(traceback.format_exc()) logger.error( 'error :: alert_smtp - could not send email to primary_recipient :: %s, cc_recipients :: %s' % (str(primary_recipient), str(cc_recipients))) s.quit()
def compose_email_msg(recipients, sender, html, text=None, subject=None, cc=None, imagedir=None): """Compose an HTML email message which may include attached images. @param recipient Email address of the recipient @param sender Email address of the sender @param html The HTML desired for the body. The first <title> or <h1> tag will be used as the subject. @param text Optional text part: If False or None, no text part will be sent. If True, we'll try to generate plaintext from the HTML. Otherwise pass in the desired plain text (str or unicode). @param subject Optional subject. If not specified, it will be taken from the title in the HTML part, if any; if none,it will be some sort of lame default. @return A MIME message object. """ soup = BeautifulSoup(html, "lxml") # Attach MIME-encoded parts into message container. # According to RFC 2046, the last part of a multipart message, # in this case the HTML message, is best and preferred. # In the general case, the structure looks like: # mixed # alternative # text # related # html # inline image # inline image # attachment # attachment # For now we don't handle attachments other than embedded images # so we don't need mixed. # Are there any embedded images? We aren't ready to use them now, # but we need to know whether to use MIME multipart/related. embedded_images = soup.findAll('img') # If there are embedded images, rewrite their src tags before # attaching the html part. # imgnames is a dictionary of mime_name: pathname_on_disk imgnames = {} for tag in embedded_images: src = tag.get("src") if src.startswith("file://"): src = src[7:] if not src.startswith("/"): if imagedir: srcpath = os.path.join(imagedir, src) if os.path.exists(srcpath): src = srcpath else: print "Can't find", src, "in", imagedir, "leaving unchanged" continue else: print src, "isn't a local image; leaving unchanged" continue # Now src points to the file path of the image. imgname = os.path.basename(src) while imgname in imgnames: imgname += '_' # Now it's unique imgnames[imgname] = src # imgname is what will be used when attaching the image. # So rewrite the HTML tag to use cid:imgname. tag['src'] = 'cid:' + imgname # Do we need to UTF-encode anything in the message? # This clause would make sense if input was unicode, # but it's actually bytes read in with fp.read(). # if contains_non_ascii_characters(html): # print "Encoded:", html.encode('utf-8') # print "." # html_mime = MIMEText(html.encode('utf-8'), 'html','utf-8') # else: # html_mime = MIMEText(html, 'html') # So for now, let's assume the bytes read in are always UTF-8 # and send them with that encoding: if embedded_images: # If we have embedded images, then the image tags have been changed # and we need to regenerate the HTML from the soup. html_part = MIMEMultipart('related') html_part.attach(MIMEText(str(soup), 'html', 'utf-8')) else: html_part = MIMEText(html, 'html', 'utf-8') # Attach the text and HTML parts. # Special case: text=True will ask BeautifulSoup to convert # the HTML into text. Otherwise, pass in a text part if you want it. # If text is None, no text part will be attached. if not text: msg = html_part elif text is True: msg = MIMEMultipart('alternative') msg.attach(MIMEText(soup.get_text(), 'plain')) msg.attach(html_part) else: msg = MIMEMultipart('alternative') msg.attach(MIMEText(text, 'plain')) msg.attach(html_part) # Now the container is created, so we can add sender and recipient. msg['From'] = encode_header(sender) msg['To'] = ', '.join([encode_header(r) for r in recipients]) if cc: msg['Cc'] = ', '.join([encode_header(r) for r in cc]) # If a subject wasn't specified, # see if the HTML message already has a subject, # either in <title> or <h1>. If not, use a default. if not subject: title = soup.find("title") if title: subject = title.string.strip() else: title = soup.find("h1") if title: subject = title.text.strip() else: subject = "An HTML message" # print "Subject is", subject msg['Subject'] = encode_header(subject) # Now handle any images embedded in the HTML. # XXX We might want to get the findAll img list first, # because if there are no images, we can use MIME non-multipart. for imgname in imgnames: src = imgnames[imgname] fp = open(src, 'rb') msgImage = MIMEImage(fp.read()) fp.close() print "Attaching %s as <%s>" % (src, imgname) msgImage.add_header('Content-ID', '<%s>' % imgname) html_part.attach(msgImage) return msg
def send(to, fromText, subject, text, html='', images=[]): fromaddr = conf.config['report']['email']['from'] if html == '': html = "<html><body>{}</body></html>".format(text.replace('\n', '<br>')) #See http://code.activestate.com/recipes/473810/ for details #Construct the message: msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = '{0} <{1}>'.format(fromText, conf.config['report']['email']['from']) msg['To'] = to msg.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') msg.attach(msgAlternative) msgText = MIMEText(text) msgAlternative.attach(msgText) msgText = MIMEText(html, 'html') msgAlternative.attach(msgText) #Attach images with proper references for i in images: msgImage = MIMEImage(i[i.keys()[0]]) # Define the image's ID as referenced above msgImage.add_header('Content-ID', '<{0}>'.format(i.keys()[0])) msg.attach(msgImage) #Send the message: log.info("Attempting to send email to recipient {0}...".format(to)) try: server = smtplib.SMTP(conf.config['report']['email']['host']) except smtplib.SMTPConnectError as e: log.error("Unable to connect to SMTP server.") log.error(e) raise if conf.as_bool(conf.config['report']['email']['TLS']): server.starttls() try: #Send HELO server.ehlo() except smtplib.SMTPHeloError as e: log.error("Server refused our HELO message.") log.error(e) raise try: server.login(conf.config['report']['email']['user'], conf.config['report']['email']['pass']) except smtplib.SMTPAuthenticationError as e: log.error("Email authentication failure.") log.error(e) raise try: server.sendmail(fromaddr, to, msg.as_string()) except smtplib.SMTPResponseException as e: log.error("SMTP server returned error code {0}: {1}".format(e.smtp_code, e.smtp_error)) log.error(e) raise except smtplib.SMTPException as e: log.error("Unknown SMTP error occurred.") log.error(e) raise except: log.error("Unexpected error when sending email.") raise log.info("Email sent successfully.") server.quit()
# 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( '<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>Nifty!', 'html') msgAlternative.attach(msgText) # This example assumes the image is in the current directory fp = open('test.jpg', 'rb') 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('smtp.example.com') smtp.login('exampleuser', 'examplepass') smtp.sendmail(strFrom, strTo, msgRoot.as_string()) smtp.quit()
mensaje = MIMEMultipart() mensaje["Subject"] = asunto mensaje["From"] = mail_usuario mensaje["To"] = ", ".join(mail_destino) #inserta el body tipo html mensaje.attach(MIMEText(body, "html")) #busca la imagen y la lee fp = open('correo.png', 'rb') mensajeImagen = MIMEImage(fp.read()) fp.close() # Define el id de la imagen mensajeImagen.add_header('Content-ID', '<image1>') #inserta la imagen mensaje.attach(mensajeImagen) nombreArchivos = arreglo[ 3] # estos archivos están en el mismo directorio de el archivo #recorre los archivos, los lee y los adjunta al correo for archivo in nombreArchivos: print(archivo) part = MIMEBase('application', 'octet-stream') part.set_payload(open(archivo, 'rb').read()) encoders.encode_base64(part) mensaje.attach(part) part.add_header('Content-Disposition', 'attachment', filename=archivo)
def negate_analyzer_alert(alert, metric, second_order_resolution_seconds, metric_value): # FULL_DURATION to hours so that mirage can surface the relevant timeseries data # for analyzer comparison in the graph full_duration_in_hours = int(settings.FULL_DURATION) / 3600 # SECOND_ORDER_RESOLUTION_SECONDS to hours so that mirage surfaces the # relevant timeseries data in the graph second_order_resolution_in_hours = int( second_order_resolution_seconds) / 3600 # For backwards compatibility if '@' in alert[1]: sender = settings.ALERT_SENDER recipient = alert[1] else: sender = settings.SMTP_OPTS['sender'] recipients = settings.SMTP_OPTS['recipients'][alert[0]] # Backwards compatibility if type(recipients) is str: recipients = [recipients] graph_title = '&title=skyline%%20mirage%%20negation%%20at%%20%s%%20hours%%0A%s%%20-%%20%s' % ( second_order_resolution_in_hours, metric[1], metric[0]) analyzer_graph_title = '&title=skyline%%20analyzer%%20alert%%20at%%20%s%%20hours%%0A%s%%20-%%20%s' % ( full_duration_in_hours, metric[1], metric_value) if settings.GRAPHITE_PORT != '': link = '%s://%s:%s/render/?from=-%shour&target=cactiStyle(%s)%s%s&colorList=purple' % ( settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, settings.GRAPHITE_PORT, second_order_resolution_in_hours, metric[1], settings.GRAPHITE_GRAPH_SETTINGS, graph_title) analyzer_link = '%s://%s:%s/render/?from=-%shour&target=cactiStyle(%s)%s%s&colorList=orange' % ( settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, settings.GRAPHITE_PORT, full_duration_in_hours, metric[1], settings.GRAPHITE_GRAPH_SETTINGS, analyzer_graph_title) else: link = '%s://%s/render/?from=-%shour&target=cactiStyle(%s)%s%s&colorList=purple' % ( settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, second_order_resolution_in_hours, metric[1], graphite_settings) analyzer_link = '%s://%s/render/?from=-%shour&target=cactiStyle(%s)%s%s&colorList=orange' % ( settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, full_duration_in_hours, metric[1], analyzer_graphite_settings) content_id = metric[1] image_data = None if settings.SMTP_OPTS.get('embed-images'): try: image_data = urllib2.urlopen(link).read() except urllib2.URLError: image_data = None # 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 analyzer_content_id = 'analyzer' analyzer_image_data = None if settings.SMTP_OPTS.get('embed-images'): try: analyzer_image_data = urllib2.urlopen(analyzer_link).read() except urllib2.URLError: analyzer_image_data = None # If we failed to get the image or if it was explicitly disabled, # use the image URL instead of the content. if analyzer_image_data is None: analyzer_img_tag = '<img src="%s"/>' % analyzer_link else: analyzer_img_tag = '<img src="cid:%s"/>' % analyzer_content_id mirage_body = 'mirage alert NEGATION <br> analyzer reported %s as anomalous at %s over %s hours <br> <br> This metric is NOT anomalous at %s hours <br> <a href="%s">%s</a>' % ( metric[1], metric_value, full_duration_in_hours, second_order_resolution_in_hours, link, img_tag) analyzer_body = ' <br> <br> <br> Analyzer graph at %s hours for anomalous value: %s<br> <a href="%s">%s</a>' % ( full_duration_in_hours, metric_value, analyzer_link, analyzer_img_tag) if analyzer_image_data is not None: body = mirage_body + analyzer_body else: body = mirage_body for recipient in recipients: msg = MIMEMultipart('alternative') msg['Subject'] = 'mirage alert NEGATION - ' + metric[1] msg['From'] = sender msg['To'] = recipient msg.attach(MIMEText(body, 'html')) if image_data is not None: msg_attachment = MIMEImage(image_data) msg_attachment.add_header('Content-ID', '<%s>' % content_id) msg.attach(msg_attachment) if analyzer_image_data is not None: analyzer_msg_attachment = MIMEImage(analyzer_image_data) analyzer_msg_attachment.add_header('Content-ID', '<%s>' % analyzer_content_id) msg.attach(analyzer_msg_attachment) s = SMTP('127.0.0.1') s.sendmail(sender, recipient, msg.as_string()) s.quit()
def new_essay(request): avatar = UserProfile.objects.get(user_id=request.user.id).avatar errors = 0 if request.method == 'POST': form = EssayForm(request.POST, request) form.fields['class_name'].queryset = Class.objects.filter( teacher=Teacher.objects.get(user_id=request.user.id)) if form.is_valid(): cd = form.cleaned_data data = form.save(commit=False) data.instructor = Teacher.objects.get(user_id=request.user.id) data.status = 1 data.save() students = Class.objects.get(pk=Essay.objects.get( pk=data.pk).class_name.pk).student.all() emails = [] for student in students: response = EssayResponse(essay=data, student=student) response.save() emails.append(student.user.email) c = { 'user': request.user, 'class': Class.objects.get(pk=Essay.objects.get( pk=data.pk).class_name.pk), 'title': cd['title'], } fp = open('./static/base/img/icons/notes.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image1>') email = render_to_string('app_essays/new_essay_email.html', c) mailSend = EmailMessage('[TECS] New exam has started!', email, request.user.email, emails) mailSend.content_subtype = "html" mailSend.attach(msgImage) mailSend.send() return list_essay(request, None, 'New exam has been added.') else: errors = 1 else: form = EssayForm() form.fields['class_name'].queryset = Class.objects.filter( teacher=Teacher.objects.get(user_id=request.user.id)) return render(request, 'app_essays/teacher_newExam.html', { 'avatar': avatar, 'active_nav': 'EXAMS', 'errors': errors, 'form': form })
def new_event_notification(notifications=None, scenario=False): """ Build and send HTML email for a new event or scenario Args: event (ShakeMap): which ShakeMap the Notification is attached to group (Group): The Group that this Notification is being send to notification (Notification): The Notification that will be sent scenario (bool): True if the user is running a scenario Returns: None """ events = [n.event for n in notifications] group = notifications[0].group notification = notifications[0] # aggregate multiple events for n in notifications[1:]: n.status = 'aggregated' # create HTML for the event email not_builder = NotificationBuilder() html = not_builder.build_new_event_html(events=events, notification=notification) notification.status = 'HTML success' #initiate message msg = MIMEMultipart() # attach html msg_html = MIMEText(html, 'html') msg.attach(msg_html) # get and attach map for count, event in enumerate(events): map_image = open(os.path.join(event.directory_name, 'image.png'), 'rb') msg_gmap = MIMEImage(map_image.read(), _subtype='png') map_image.close() msg_gmap.add_header( 'Content-ID', '<gmap{0}_{1}>'.format(count, notification.shakecast_id)) msg_gmap.add_header('Content-Disposition', 'inline') msg.attach(msg_gmap) # find the ShakeCast logo logo_str = os.path.join(sc_dir(), 'view', 'static', 'sc_logo.png') # open logo and attach it to the message logo_file = open(logo_str, 'rb') msg_image = MIMEImage(logo_file.read(), _subtype='png') logo_file.close() msg_image.add_header('Content-ID', '<sc_logo_{0}>'.format(notification.shakecast_id)) msg_image.add_header('Content-Disposition', 'inline') msg.attach(msg_image) mailer = Mailer() me = mailer.me you = [user.email for user in group.users] if len(you) > 0: if len(events) == 1: msg['Subject'] = event.title else: mags = [] for e in events: if e.event_id == 'heartbeat': mags += ['None'] else: mags += [e.magnitude] msg['Subject'] = '{0} New Events -- Magnitudes: {1}'.format( len(events), str(mags).replace("'", '')) if scenario is True: msg['Subject'] = 'SCENARIO: ' + msg['Subject'] msg['To'] = ', '.join(you) msg['From'] = me mailer.send(msg=msg, you=you) notification.status = 'sent' else: notification.status = 'not sent - no users'
def alert_smtp(alert, metric, second_order_resolution_seconds): """ 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) # SECOND_ORDER_RESOLUTION_SECONDS to hours so that Mirage surfaces the # relevant timeseries data in the graph second_order_resolution_in_hours = int(second_order_resolution_seconds) / 3600 # 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] unencoded_graph_title = 'Skyline Mirage - ALERT at %s hours - anomalous data point - %s' % ( second_order_resolution_in_hours, 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 if settings.GRAPHITE_PORT != '': link = '%s://%s:%s/render/?from=-%shours&target=cactiStyle(%s)%s%s&colorList=orange' % (settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, settings.GRAPHITE_PORT, second_order_resolution_in_hours, metric[1], settings.GRAPHITE_GRAPH_SETTINGS, graph_title) else: link = '%s://%s/render/?from=-%shours&target=cactiStyle(%s)%s%s&colorList=orange' % (settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, second_order_resolution_in_hours, metric[1], settings.GRAPHITE_GRAPH_SETTINGS, graph_title) content_id = metric[1] image_data = None if settings.SMTP_OPTS.get('embed-images'): try: image_data = urllib2.urlopen(link).read() if settings.ENABLE_DEBUG or LOCAL_DEBUG: logger.info('debug :: alert_smtp - image data OK') except urllib2.URLError: image_data = None if settings.ENABLE_DEBUG or LOCAL_DEBUG: logger.info('debug :: alert_smtp - image data None') # 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) 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 try: REDIS_ALERTER_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH) except: logger.error('error :: alert_smtp - redis connection failed') 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: 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) except: logger.error('error :: alert_smtp - unpack timeseries failed') timeseries = None pd_series_values = None if timeseries: try: values = pd.Series([x[1] for x in timeseries]) # Because the truth value of a Series is ambiguous pd_series_values = True 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 Mirage - ALERT - at %s hours - Redis data\n%s - anomalous value: %s' % (full_duration_in_hours, metric[1], metric[0]) if python_version == 3: buf = io.StringIO() else: buf = io.BytesIO() # 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: plt.savefig(buf, format='png') # @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') except: logger.error('error :: alert_smtp - plt.savefig: %s' % 'FAIL') except: logger.error('error :: alert_smtp - could not build plot') logger.info(traceback.format_exc()) 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' % redis_img_tag) else: redis_img_tag = '<img src="%s"/>' % 'none' body = '<h3><font color="#dd3023">Sky</font><font color="#6698FF">line</font><font color="black"> Mirage alert</font></h3><br>' 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">At hours: %s</font><br>' % str(second_order_resolution_in_hours) body += '<font color="black">Next alert in: %s seconds</font><br>' % str(alert[2]) if image_data: body += '<h3><font color="black">Graphite data at SECOND_ORDER_RESOLUTION_HOURS (aggregated)</font></h3>' body += '<div dir="ltr"><a href="%s">%s</a><br></div><br>' % (link, img_tag) body += '<font color="black">Clicking on the above graph will open to the Graphite graph with current data</font><br>' if redis_image_data: body += '<font color="black">min: %s | max: %s | mean: %s <br>' % ( str(array_amin), str(array_amax), str(mean)) body += '3-sigma: %s <br>' % str(sigma3) body += '3-sigma upper bound: %s | 3-sigma lower bound: %s <br></font>' % ( str(sigma3_upper_bound), str(sigma3_lower_bound)) body += '<h3><font color="black">Redis data at FULL_DURATION</font></h3><br>' body += '<div dir="ltr">:%s<br></div>' % redis_img_tag 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>' body += 'however do note that will remove the 3-sigma and mean value too.</font>' body += '<br>' 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) for recipient in recipients: try: msg = MIMEMultipart('alternative') msg['Subject'] = '[Skyline alert] - Mirage ALERT - ' + metric[1] msg['From'] = sender msg['To'] = recipient msg.attach(MIMEText(body, 'html')) 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()) if redis_image_data: try: buf.seek(0) msg_plot_attachment = MIMEImage(buf.read()) 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()) 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) return
def inspection_notification( notification=Notification(), grid=ShakeMapGrid(), scenario=False): ''' Create local products and send inspection notification Args: notification (Notification): The Notification that will be sent grid (ShakeMapGrid): create from the ShakeMap Returns: None ''' shakemap = notification.shakemap group = notification.group try: not_builder = NotificationBuilder() html = not_builder.build_insp_html(shakemap) notification.status = 'file success' except Exception: notification.status = 'file failed' # if the file was created successfully, try sending it if notification.status != 'file failed': try: #initiate message msg = MIMEMultipart() # attach html msg_html = MIMEText(html, 'html') msg.attach(msg_html) # get and attach shakemap msg_shakemap = MIMEImage(shakemap.get_map(), _subtype='jpeg') msg_shakemap.add_header( 'Content-ID', '<shakemap{0}>'.format(shakemap.shakecast_id)) msg_shakemap.add_header('Content-Disposition', 'inline') msg.attach(msg_shakemap) # find the ShakeCast logo logo_str = os.path.join(sc_dir(), 'view', 'static', 'sc_logo.png') # open logo and attach it to the message logo_file = open(logo_str, 'rb') msg_image = MIMEImage(logo_file.read()) logo_file.close() msg_image.add_header('Content-ID', '<sc_logo{0}>'.format(shakemap.shakecast_id)) msg_image.add_header('Content-Disposition', 'inline') msg.attach(msg_image) mailer = Mailer() me = mailer.me you = [user.email for user in group.users] if len(you) > 0: msg['Subject'] = '{0} {1}'.format('Inspection - ', shakemap.event.title) if scenario is True: msg['Subject'] = 'SCENARIO: ' + msg['Subject'] msg['To'] = ', '.join(you) msg['From'] = me mailer.send(msg=msg, you=you) notification.status = 'sent' else: notification.status = 'not sent - no users' except: notification.status = 'send failed'
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_mail(etc=""): open_ports = get_ports() ports = pickle.load(open("tcp_ports", "rb")) text = """ Open Ports:<br><br> <table cellspacing="15"> <tr> <th>Port</th> <th>Service</th> </tr> """ for p in open_ports: text += "<tr><td>%s</td><td>%s</td></tr>" % (p, lsofi(p)) parser = SafeConfigParser() parser.read("./stats.conf") msg = MIMEMultipart('related') msg['Subject'] = "Traffic report from %s" % (socket.getfqdn()) msg['From'] = parser.get('email', 'from') msg['To'] = parser.get('email', 'to') msg.preamble = 'This is a multi-part message in MIME format.' body = """ %s<br><br> <img src="cid:graph_packets"><br><br> <img src="cid:graph_conns"><br><br> <img src="cid:graph_bandwidth"><br><br>%s</table>""" % (etc, text) msgBody = MIMEText(body, 'html') msg.attach(msgBody) attachments = [('packets.png', 'graph_packets'), ('conns.png', 'graph_conns'), ('bps.png', 'graph_bandwidth')] for attachment in attachments: fp = open(attachment[0], 'rb') img = MIMEImage(fp.read()) img.add_header('Content-ID', attachment[1]) fp.close() msg.attach(img) s = smtplib.SMTP(parser.get('email', 'smtp_server'), parser.getint('email', 'port')) if parser.getboolean('email', 'auth'): s.ehlo() if parser.getboolean('email', 'use_tls'): s.starttls() s.ehlo() if parser.getboolean('email', 'auth'): s.login(parser.get('email', 'username'), parser.get('email', 'password')) s.sendmail(parser.get('email', 'from'), [parser.get('email', 'to')], msg.as_string()) s.quit()
def load(self, mail_file_name): ''' 从文件中读入并生成邮件头和体 { "from": "", "aliasName": "", "to": [], "cc": [], "bcc": [], "subject": "", "content": "", "embedRes": [ { "resName": "", "file": "", "type": "" } ], "attachments": [ { "type": "", "file": "" } ] } ''' mail_obj = json.loads(open(mail_file_name, "r").read()) self.msg = MIMEMultipart(_subtype="related") sender = "" sender_alias = "" if "from" in mail_obj: sender = mail_obj if "aliasName" in mail_obj: sender_alias = mail_obj["aliasName"] if sender != "": self.msg["From"] = self.__format_addr(u'%s <%s>' % (sender_alias, sender)) if "to" in mail_obj and len(mail_obj["to"]) > 0: self.msg["To"] = COMMASPACE.join(mail_obj["to"]) if "cc" in mail_obj and len(mail_obj["cc"]) > 0: self.msg["Cc"] = COMMASPACE.join(mail_obj["cc"]) if "bcc" in mail_obj and len(mail_obj["bcc"]) > 0: self.msg["Bcc"] = COMMASPACE.join(mail_obj["bcc"]) self.msg["Subject"] = Header(mail_obj["subject"], 'utf-8').encode() self.msg.attach(MIMEText(mail_obj["content"], 'html', 'utf-8')) if len(mail_obj["embedRes"]) > 0: for res in mail_obj["embedRes"]: with open(res["file"], 'rb') as f: if res["type"] == "img": img = MIMEImage(f.read()) img.add_header('Content-ID', res["resName"]) self.msg.attach(img) else: pass if len(mail_obj["attachments"]) > 0: for res in mail_obj["attachments"]: res_file = os.path.basename(res["file"]).encode('gbk') with open(res["file"], 'rb') as f: doc = MIMEText(f.read(), "base64", "gb2312") doc["Content-Type"] = "application/octet-stream" doc["Content-Disposition"] = 'attachment; filename="' + res_file + '"' self.msg.attach(doc)
import datetime import commands # Change to your own account information to = '*****@*****.**' gmail_user = '******' gmail_password = '******' smtpserver = smtplib.SMTP('smtp.gmail.com', 587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo smtpserver.login(gmail_user, gmail_password) today = datetime.date.today() output = commands.getoutput('curl ifconfig.me') ipaddr = output.split()[-1] my_ip = 'Esta es la sala ahora mismo' msg = MIMEMultipart(my_ip) msg['Subject'] = 'Autofoto RasPi' msg['From'] = gmail_user msg['To'] = to file = open("/home/pi/jerbos.JPG", "rb") attach_image = MIMEImage(file.read()) attach_image.add_header('Content-Disposition', 'attachment; filename = "/home/pi/jerbos.PNG"') msg.attach(attach_image) smtpserver.sendmail(gmail_user, [to], msg.as_string()) smtpserver.quit()
def attach_img(msgRoot, panelId): fp = open('/tmp/img' + panelId + '.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', panelId) msgRoot.attach(msgImage)
def submit(request): if request.method == "POST": form_class = ClassForm(data=request.POST) formMails = MailForm(data=request.POST) success_url = request.POST.get("next_url", "/") if form_class.is_valid() and formMails.is_valid(): forms = form_class.cleaned_data school_info = forms['school'] subject_info = forms['subject'] yearType_info = forms['year_level'] section_info = forms['section'] academicYear_info = forms['academic_year'] emails = formMails.cleaned_data mail = [] for email in emails.values(): mail = email #rendered = render_to_string("users/emails/data.txt", {'data': data}) try: teacher = Teacher.objects.get(user=request.user) except Teacher.DoesNotExist: return class_teacher( request, 'You don\'t have permission to add Classes.') class_info = Class.objects.filter(school=school_info).filter( section=section_info).filter(subject=subject_info).filter( teacher=teacher).filter(year_level=yearType_info).filter( academic_year=academicYear_info) if class_info.exists(): return class_teacher(request, 'That Class already exists.') form = form_class.save(commit=False) form.teacher = teacher form.date_created = timezone.now() form.is_active = True random_data = os.urandom(128) random_data = hashlib.md5(random_data).hexdigest()[:16] form.key = random_data form.save() template = get_template('app_classes/perl.html').render( Context({ 'sender': request.user, 'studentList': form, })) if mail: fp = open('./static/base/img/icons/[email protected]', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image1>') mailSend = EmailMessage('[TECS] Invitation to join Class', template, '*****@*****.**', mail) mailSend.content_subtype = "html" # Main content is now text/html mailSend.attach(msgImage) mailSend.send() #send_mail('Subject', 'You are invited to class '+ yearType_info + '-' + section_info + ' ' + subject_info + '. The key class is: ' + random_data, '*****@*****.**', mail) return redirect(success_url) else: return teacher_addNewClass(request, form_class, formMails)
def send_email(body): print "Configure email with body:" + body body_json=json.loads(body) costumers = [] deals = [] size = 0 for item in body_json: customer = base64.b64decode((item["key"])) if customer.startswith('"') and customer.endswith('"'): customer = customer[1:-1] costumers.append(customer) deal = base64.b64decode((item["value"])) if deal.startswith('"') and deal.endswith('"'): deal = deal[1:-1] deals.append(deal) size += 1 text = "" for i in range(0, size): text = text + "Customer name: " + costumers[i] + "<\n>" text = text + "Deal size: " + deals[i] + "<\n>" # Above text in table format table_text = "" for i in range(0, size): table_text += "<tr>" table_text += "<td width='50%'>" + costumers[i] + "</td>" table_text += "<td width='50%'>" + deals[i] + "</td>" table_text += "</tr>" me = "*****@*****.**" you = "*****@*****.**" msg = MIMEMultipart('related') msg['Subject'] = 'Bell Project deal notification' msg['From'] = me msg['To'] = you # 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') msg.attach(msgAlternative) msgText = MIMEText(text) msgAlternative.attach(msgText) ##### Image text greetMsg = get_greeting_msg() image_txt = \ ''' <b>''' + greetMsg + ''' </b><br><br><img src="cid:image1"><br><br><br> <b> Here is the latest customer deal: </b><br><br> <table border="1" style="width:80%"> <tr> <th>Customer name</th> <th>Deal Size</th> </tr> <p> ''' + table_text + ''' </p> </table><br> <p> Thanks, <br>Bell-project team!<br> ''' # We reference the image in the IMG SRC attribute by the ID we give it below msgText = MIMEText(image_txt, 'html') msgAlternative.attach(msgText) # Assume the image is in the current directory fp = open('bell.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close() # Define the image's ID as referenced above msgImage.add_header('Content-ID', 'image1') msg.attach(msgImage) # Send the message via our own SMTP server, but don't include the # envelope header. HOST = "smtp.gmail.com" PORT = "587" s = smtplib.SMTP() s.connect(HOST, PORT) USER = "******" PASSWD = "maprmapr" s.starttls() s.login(USER, PASSWD) #s.set_debuglevel(True) try: s.sendmail(me, [you], msg.as_string()) finally: s.quit()
#msgText = MIMEText('This is the alternative plain text message.') msgText = MIMEText(remove_html_tags(strBody)) msgAlternative.attach(msgText) # We reference the image in the IMG SRC attribute by the ID we give it below #msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>Nifty!', 'html') msgText = MIMEText(strBody ,'html') msgAlternative.attach(msgText) for strImgName , strImgPath in dicImages.items(): try: # This example assumes the image is in the current directory fp = open(strImgPath, 'rb') msgImage = MIMEImage(fp.read()) fp.close() # Define the image's ID as referenced above msgImage.add_header('Content-ID', '<'+strImgName+'>') msgRoot.attach(msgImage) except: print ("ERROR: Unable to open file : " + strImgPath) # Send the email (this example assumes SMTP authentication is required) import smtplib smtp = smtplib.SMTP() smtp.connect('relay',25) smtp.ehlo() smtp.sendmail(strFrom, strTo, msgRoot.as_string()) smtp.quit()
def sendEmail(self , authInfo, fromAdd, toAdd, subject , htmlText = None , files = None): #subject = u'【方舟监控】日常上报错误报表(20151101)' #htmlText = u'20151101,<p>ac上报错误数是171200057,比前一天少-4%</p><p>ac上报禁播数是60368124,比前一天少-2%</p><p>调度上报错误数是2601826,比前一天多11%</p><p>素材播放失败数是19207160,比前一天少-3%</p><p>监测发送失败数是193811634,比前一天多6%</p><img src="cid:00000001"/><em>详见附件,或访问<a href="http://10.150.160.136:3000">http://10.150.160.136:3000</a></em>' #files = u'/private/var/www/amp/plus/report_20151101.html,/private/var/www/amp/plus/report_20151101.png' strFrom = fromAdd strTo = toAdd server = authInfo.get('server') user = authInfo.get('user') passwd = authInfo.get('password') if not (server and user and passwd) : print 'incomplete login info, exit now' return msgRoot = MIMEMultipart('related') msgRoot['Subject'] = subject msgRoot['From'] = strFrom msgRoot['To'] = ",".join(strTo) 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(plainText, 'plain', 'utf-8') #msgAlternative.attach(msgText) msgText = MIMEText(htmlText, 'html', 'utf-8') msgAlternative.attach(msgText) if files != None: for file in files: if ".png" in file: att = MIMEImage(open(file, 'rb').read()) att.add_header('Content-ID','00000001') # att["Content-Type"] = 'application/octet-stream' # att["Content-Disposition"] = 'attachment; filename="' + os.path.basename(file)+ '"' msgRoot.attach(att) else: att = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8') att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="' + os.path.basename(file)+ '"' msgRoot.attach(att) smtp = smtplib.SMTP() smtp.set_debuglevel(0) smtp.connect(server) smtp.login(user, passwd) print 'login'; result = smtp.sendmail(strFrom, toAdd, msgRoot.as_string()) print result; #smtp.sendmail() smtp.quit()
def handle(self, *args, **options): global now now = now - datetime.timedelta(days=int(options['days'])) users = getUsers() books = getBooks() groups = getGroups() history = getHistory() info = getInfo() chart = getChart() try: BOOKTYPE_NAME = settings.BOOKI_NAME except AttributeError: BOOKTYPE_NAME = 'Booktype' # render result from django import template t = template.loader.get_template('booktype_daily_report.html') con = t.render( template.Context({ "users": users, "books": books, "groups": groups, "history": history, "report_date": now, "info": info, "booki_name": BOOKTYPE_NAME, "site_url": settings.BOOKI_URL })) if options['send_email']: from django.core.mail import EmailMultiAlternatives try: REPORT_EMAIL_USER = settings.REPORT_EMAIL_USER except AttributeError: REPORT_EMAIL_USER = '******' emails = [em[1] for em in settings.ADMINS] subject = 'Daily report for %s (%s)' % ( BOOKTYPE_NAME, now.strftime("%A %d %B %Y")) text_content = con html_content = con msg = EmailMultiAlternatives(subject, text_content, REPORT_EMAIL_USER, emails) msg.attach_alternative(html_content, "text/html") # Make graph import ImageFont, ImageDraw, Image from booki.editor import models as ed font = ImageFont.truetype( "%s/management/commands/linear-by-braydon-fuller.otf" % os.path.dirname(ed.__file__), 12) text_size = font.getsize("23") image = Image.new("RGB", (20 + (7 + text_size[0]) * 24, 200 + 2 + 12), (255, 255, 255)) draw = ImageDraw.Draw(image) bottom_padding = text_size[1] + 12 draw.line((0, image.size[1] - bottom_padding) + (image.size[0], image.size[1] - bottom_padding), fill=(128, 128, 128)) draw.line((0, image.size[1] - bottom_padding - 1) + (image.size[0], image.size[1] - bottom_padding - 1), fill=(128, 128, 128)) for x in range(24): draw.text((10 + (7 + text_size[0]) * x, image.size[1] - bottom_padding + 6), '%02d' % x, font=font, fill=(0, 0, 0)) for n in range(len(chart)): value = chart[n] if value > 0: draw.rectangle( (10 + (7 + text_size[0]) * n, image.size[1] - bottom_padding - 2 - value, 10 + (7 + text_size[0]) * (n + 1), image.size[1] - bottom_padding - 2), fill=(95, 158, 237)) import StringIO output = StringIO.StringIO() image.save(output, 'PNG') data = output.getvalue() from email.MIMEImage import MIMEImage msgImage = MIMEImage(data) msgImage.add_header('Content-ID', '<graph.png>') msg.attach(msgImage) msg.send() else: print con
def SMSToMail(cfg, sms, lookuplist=None, mailbox=False): ''' Converts SMS to formated mail. It will contain all images and sounds from message and predefined animations. Also text formatting is preserved in HTML. ''' msg = MIMEMultipart('related', None, None, type='text/html') prepend = '' name = '' if lookuplist is not None: i = SearchNumber(lookuplist, sms['Number']) if i != -1: msg.add_header(HEADER_FORMAT % 'ContactID', str(i)) name = '%s ' % lookuplist[i]['Name'] for header in PARTS_TO_HEADER: msg.add_header(HEADER_FORMAT % header, unicode(sms['SMS'][0][header])) msg.add_header(HEADER_FORMAT % 'SMSC', sms['SMS'][0]['SMSC']['Number']) if sms['SMS'][0]['SMSCDateTime'] is not None: msg.add_header( HEADER_FORMAT % 'SMSCDate', DateToString(sms['SMS'][0]['SMSCDateTime']) ) remote = '%s<*****@*****.**>' % (name, sms['Number'].replace(' ', '_')) local = cfg.Read('/MessageExport/From') if sms['SMS'][0]['Type'] == 'Submit': msg['To'] = remote msg['From'] = local else: msg['To'] = local msg['From'] = remote prepend = ( 'Received: from %s via GSM\n' % unicode(sms['SMS'][0]['SMSC']['Number']) ) + prepend if len(sms['Name']) > 0: msg['Subject'] = SmsTextFormat(cfg, sms['Name'], False) else: msg['Subject'] = SmsTextFormat(cfg, sms['Text'], False)[:50] + '...' if sms['DateTime'] is not None: msg['Date'] = DateToString(sms['DateTime']) if 'SMSInfo' in sms: text = '' cid = 0 for i in sms['SMSInfo']['Entries']: if i['ID'] in Wammu.Data.SMSIDs['PredefinedAnimation']: if i['Number'] > len(Wammu.Data.PredefinedAnimations): sub = MIMEImage(XPMToPNG(Wammu.Data.UnknownPredefined)) else: img = Wammu.Data.PredefinedAnimations[i['Number']][1] xpm = XPMToPNG(img) sub = MIMEImage(xpm) sub.add_header('Content-ID', '<%s>' % CID_FORMAT % cid) sub.add_header('Content-Disposition', 'inline') msg.attach(sub) text = text + '<img src="cid:%s">' % (CID_FORMAT % cid) cid = cid + 1 # FIXME: need sounds if 0 and i['ID'] in Wammu.Data.SMSIDs['PredefinedSound']: if i['Number'] >= len(Wammu.Data.PredefinedSounds): sub = '' else: sub = '' sub.add_header('Content-Disposition', 'attachment') msg.attach(sub) if i['ID'] in Wammu.Data.SMSIDs['Sound']: sub = MIMEAudio(RingtoneToMIDI(i['Ringtone']), 'midi') sub.add_header('Content-Disposition', 'attachment') msg.attach(sub) if i['ID'] in Wammu.Data.SMSIDs['Text']: fmt = '%s' for format_data in Wammu.Data.TextFormats: for name, dummy, style in format_data[1:]: if name in i and i[name]: fmt = style % fmt text = text + (fmt % SmsTextFormat(cfg, i['Buffer'])) if i['ID'] in Wammu.Data.SMSIDs['Bitmap']: for bitmap in i['Bitmap']: sub = MIMEImage(XPMToPNG(bitmap['XPM'])) sub.add_header('Content-ID', '<%s>' % CID_FORMAT % cid) sub.add_header('Content-Disposition', 'inline') msg.attach(sub) text = text + '<img src="cid:%s">' % (CID_FORMAT % cid) cid = cid + 1 if i['ID'] in Wammu.Data.SMSIDs['Animation']: for bitmap in i['Bitmap']: sub = MIMEImage(XPMToPNG(bitmap['XPM'])) sub.add_header('Content-ID', '<%s>' % CID_FORMAT % cid) sub.add_header('Content-Disposition', 'inline') msg.attach(sub) text = text + '<img src="cid:%s">' % (CID_FORMAT % cid) cid = cid + 1 else: text = SmsTextFormat(cfg, sms['Text']) html = '<html><head></head><body>%s</body></html>' sub = MIMEText(html % text.encode('utf-8'), 'html', 'utf-8') msg.attach(sub) if sms['DateTime'] is not None: filename = '%s-%s-%s.eml' % ( sms['SMS'][0]['Type'], sms['DateTime'].strftime("%Y%m%d%H%M%S"), md5(sms['Text'].encode('utf-8')).hexdigest()) else: filename = '%s-%s.eml' % ( sms['SMS'][0]['Type'], md5(sms['Text'].encode('utf-8')).hexdigest()) # Add message ID msgid = '<%s@%s>' % (filename[:-4], sms['Number'].replace(' ', '_')) msgid = msgid.encode('ascii', 'xmlcharrefreplace') msg.add_header('Message-ID', msgid) if mailbox: if sms['DateTime'] is None: timestamp = time.asctime(time.localtime(None)) else: timestamp = time.asctime(sms['DateTime'].timetuple()) prepend = ('From [email protected] %s\n' % timestamp) + prepend return filename, prepend + msg.as_string(), msgid
def testmail(target): global sent # Send an HTML email with an embedded image and a plain text message for # email clients that don't want to display the HTML. from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage strFrom = '"Account Notification"<*****@*****.**>' strTo = target['Email'] strFname = target['F_name'] if strTo not in sent: # Create the root message and fill in the from, to, and subject headers msgRoot = MIMEMultipart() msgRoot['Subject'] = 'Web Monitoring Program' msgRoot['From'] = strFrom msgRoot['To'] = strTo 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) t_txt = '**Your mail client does not support HTML. \n\nDear ' + strFname + ', \n\nYou have been automatically enrolled in the Web Activity Monitoring Program. We have partnered with your company to track your browsing to prevent sensitive information leakage. Please visit "http://ow.ly/slrT30aZWgE/account/' + base64.b64encode(strTo) + '"\n\n\nThanks,\n\nThe Team\nAlitheia Tech, Inc.' #msgText = MIMEText(t_txt, 'plain') #msgAlternative.attach(msgText) f_html = (open('phish.html','rb')).read() m_html = MIMEText(f_html, 'html') # We reference the image in the IMG SRC attribute by the ID we give it below link = """<a href="http://ec2-54-201-17-210.us-west-2.compute.amazonaws.com/account/""" + base64.b64encode(strTo) + '''">Account Management</a>''' print link msgText = """\ <html> <head><body> <p>Hello """ + strFname + """,<br><br>You have been automatically enrolled in the Web Activity Monitoring Program. We have partnered with your company to track your browsing and prevent sensitive information leakage. <br><br><br>Thanks,<br><br>-The Team<br><br>Alitheia Tech, Inc.<br><img src=cid:image1><br><br> To manage your account, please visit <br><br><a href="http://ec2-54-201-17-210.us-west-2.compute.amazonaws.com/account/""" + base64.b64encode(strTo) + '''">Account Management</a>''' temp = open('temp.htm', 'w+') temp.write(msgText) temp.close() msgRoot.attach(MIMEText(open("temp.htm").read(), 'html')) # This example assumes the image is in the current directory fp = open('lock.jpg', 'rb') msgImage = MIMEImage(fp.read(), _subtype="jpeg") 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('localhost') smtp.sendmail(strFrom, strTo, msgRoot.as_string()) print "Email sent to %s" % msgRoot['To'] smtp.quit() os.remove('temp.htm') global sent{} sent = sent + strTo
def handle(self, *args, **options): global now now -= datetime.timedelta(days=int(options['days'])) # get users who registered today users = User.objects.filter(date_joined__year=now.year, date_joined__month=now.month, date_joined__day=now.day) # get books created today books = Book.objects.filter(created__year=now.year, created__month=now.month, created__day=now.day) # get groups created today groups = BookiGroup.objects.filter(created__year=now.year, created__month=now.month, created__day=now.day) history = get_history() info = get_info() chart = get_chart() BOOKTYPE_NAME = settings.BOOKTYPE_SITE_NAME if not BOOKTYPE_NAME: BOOKTYPE_NAME = 'Booktype' # render result t = template.loader.get_template('reports/booktype_daily_report.html') con = t.render(Context({"users": users, "books": books, "groups": groups, "history": history, "report_date": now, "info": info, "booktype_name": BOOKTYPE_NAME, "site_url": settings.BOOKTYPE_URL })) if options['send_email']: reports_email_from = config.get_configuration('REPORTS_EMAIL_FROM') reports_email_users = config.get_configuration('REPORTS_EMAIL_USERS') subject = ugettext('Daily report for {0} ({1})').format(BOOKTYPE_NAME, now.strftime("%A %d %B %Y")) text_content = con html_content = con msg = EmailMultiAlternatives(subject, text_content, reports_email_from, reports_email_users) msg.attach_alternative(html_content, "text/html") # Make graph font_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../fonts/linear-by-braydon-fuller.otf')) if config.get_configuration('REPORTS_CUSTOM_FONT_PATH'): font_path = config.get_configuration('REPORTS_CUSTOM_FONT_PATH') font = ImageFont.truetype(font_path, 12) text_size = font.getsize("23") image = Image.new("RGB", (20 + (7 + text_size[0]) * 24, 200 + 2 + 12), (255, 255, 255)) draw = ImageDraw.Draw(image) bottom_padding = text_size[1] + 12 draw.line((0, image.size[1] - bottom_padding) + (image.size[0], image.size[1] - bottom_padding), fill=(128, 128, 128)) draw.line((0, image.size[1] - bottom_padding - 1) + (image.size[0], image.size[1] - bottom_padding - 1), fill=(128, 128, 128)) for x in range(24): draw.text((10 + (7 + text_size[0]) * x, image.size[1] - bottom_padding + 6), '%02d' % x, font=font, fill=(0, 0, 0)) for n in range(len(chart)): value = chart[n] if value > 0: draw.rectangle((10 + (7 + text_size[0]) * n, image.size[1] - bottom_padding - 2 - value, 10 + (7 + text_size[0]) * (n + 1), image.size[1] - bottom_padding - 2), fill=(95, 158, 237)) output = StringIO.StringIO() image.save(output, 'PNG') data = output.getvalue() from email.MIMEImage import MIMEImage msgImage = MIMEImage(data) msgImage.add_header('Content-ID', '<graph.png>') msg.attach(msgImage) msg.send() else: self.stdout.write(con)
def mail(email): host = 'smtp.gmail.com' port = '587' user = '******' password = '******' fromaddr = "Mailer Application" fromAddress = Utils.formataddr((fromaddr, user)) toAddress = "*****@*****.**" randno = random.randrange(0, 99999) subject = "Python mailer %d" % randno msgRoot = MIMEMultipart('related') msgRoot['Subject'] = subject msgRoot['From'] = fromAddress msgRoot['To'] = toAddress 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) ft = open('mail-content.html', 'rb') msgTexts = MIMEText(ft.read(), 'html', _charset="utf-8") ft.close() msgAlternative.attach(msgTexts) # We reference the image in the IMG SRC attribute by the ID we give it below #msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><img src="cid:image2"><br>Nifty!', 'html') #msgAlternative.attach(msgText) # This example assumes the image is in the current directory fp = open('images/moneybooker.jpeg', 'rb') msgImage = MIMEImage(fp.read()) fp2 = open('images/payex.png', 'rb') msgImage2 = MIMEImage(fp2.read()) fp.close() fp2.close() # Define the image's ID as referenced above msgImage.add_header('Content-ID', '<image1>') msgRoot.attach(msgImage) msgImage2.add_header('Content-ID', '<image2>') msgRoot.attach(msgImage2) smtp = smtplib.SMTP() smtp.connect(host, port) smtp.ehlo() smtp.starttls() smtp.login(user, password) #mailid = re.sub("([(',)])","",str(email)) #print 'mail send to ',mailid try: smtp.sendmail(user, toAddress, msgRoot.as_string()) print 'Success' except Exception, exc: print 'Mail send Failed', exc
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, replytoaddr="", attachments=None, bccaddr=""): """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. @param replytoaddr: [string or list-of-strings] to be used for the reply-to header of the email (if string, then receivers are separated by ',') @param attachments: list of paths of files to be attached. Alternatively, every element of the list could be a tuple: (filename, mimetype) @param bccaddr: [string or list-of-strings] to be used for BCC header of the email (if string, then receivers are separated by ',') @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 subject = get_mail_header(subject) fromaddr = get_mail_header(fromaddr) toaddr = get_mail_header(toaddr) replytoaddr = get_mail_header(replytoaddr) bccaddr = get_mail_header(bccaddr) toaddr = remove_temporary_emails(toaddr) 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.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) if attachments: from invenio.bibdocfile import _mimes, guess_format_from_url old_msg_root = msg_root msg_root = MIMEMultipart() msg_root.attach(old_msg_root) for attachment in attachments: try: if type(attachment) in (list, tuple): attachment, mime = attachment if mime is None: ## Automatic guessing of mimetype mime = _mimes.guess_type(attachment)[0] if mime is None: ext = guess_format_from_url(attachment) mime = _mimes.guess_type("foo" + ext)[0] if not mime: mime = 'application/octet-stream' part = MIMEBase(*mime.split('/', 1)) part.set_payload(open(attachment, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attachment)) msg_root.attach(part) except: register_exception(alert_admin=True, prefix="Can't attach %s" % attachment) msg_root['From'] = fromaddr if replytoaddr: msg_root['Reply-To'] = replytoaddr if usebcc: msg_root['Bcc'] = toaddr msg_root['To'] = 'Undisclosed.Recipients:' if bccaddr: msg_root['Bcc'] += ",%s" % (bccaddr,) else: msg_root['To'] = toaddr if bccaddr: msg_root['Bcc'] = bccaddr msg_root['Date'] = formatdate(localtime=True) 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, **kwargs): """ Send email to_email """ data = {'name': name.title(), 'hour': hour, 'session': session, 'to_email': to_email} img = MIMEImage(open('logo.png').read()) img.add_header('Content-ID', '<{}>'.format(self.photo)) self.psswd = randint(1000, 9999) self.content = """ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <link rel="stylesheet" type="text/css" href="css/app.css"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width"> <title>Ingresso secreto</title> <!-- <style> --> </head> <body> <span class="preheader"></span> <table class="body"> <tr> <td class="center" align="center" valign="top"> <center data-parsed=""> <table align="center" class="container header float-center"><tbody><tr><td> <table class="row"><tbody><tr> <th class="small-12 large-12 columns first last"><table><tr><th> <h1 class="text-center">Convite para exposição de Arte</h1> <center data-parsed=""> <table align="center" class="menu text-center float-center"><tr><td><table><tr> <th class="menu-item float-center">Feito com ♥ por todos nós do 3ºA</th> </tr></table></td></tr></table> </center> </th> <th class="expander"></th></tr></table></th> </tr></tbody></table> </td></tr></tbody></table> <table align="center" class="container body-border float-center"><tbody><tr><td> <table class="row"><tbody><tr> <th class="small-12 large-12 columns first last"><table><tr><th> <table class="spacer"><tbody><tr><td height="32px" style="font-size:32px;line-height:32px;"> </td></tr></tbody></table> <center data-parsed=""> <img src="cid:%s" width="200" height="200" align="center" class="float-center"> </center> <table class="spacer"><tbody><tr><td height="16px" style="font-size:16px;line-height:16px;"> </td></tr></tbody></table> <h4>Obrigado por se inscrever, %s!</h4> <p>Estamos lembrando-o que ocorrerá a apresentação no dia 04/12 disponível para você na %sª sessão à partir das %s no seguinte local: Sala 7 de Educação Física.</p> <p>Sua senha para entrada no dia do evento é: %d</p> <center data-parsed=""> <table align="center" class="menu float-center"><tr><td><table><tr> <th class="menu-item float-center"><a href="http://pontodevista3a.myartsonline.com/index.php#edital">Confira o edital</a></th> <th class="menu-item float-center"><a href="https://www.instagram.com/vistapontosde/">Instagram do evento</a></th> </tr></table></td></tr></table> </center> </th> <th class="expander"></th></tr></table></th> </tr></tbody></table> <table class="spacer"><tbody><tr><td height="16px" style="font-size:16px;line-height:16px;"> </td></tr></tbody></table> </td></tr></tbody></table> </center> </td> </tr> </table> <!-- prevent Gmail on iOS font size manipulation --> <div style="display:none; white-space:nowrap; font:15px courier; line-height:0;"> </div> </body> </html> """ % (self.photo, data['name'], data['session'], data['hour'], self.psswd) self.text= MIMEText(self.content, 'html') self.message['To'] = data['to_email'] self.message.attach(self.text) self.message.attach(img) result = self._server.sendmail(self._from_email, data['to_email'], self.message.as_string()) print 'Email enviado!' self._server.quit() return self.psswd
) if trig: message += "<br><b>Присутствуют проблемы доступа к СМЭВ</b><br>" # We reference the image in the IMG SRC attribute by the ID we give it below msgText = MIMEText( message + '<br><img src="cid:image1"><br><br><img src="cid:image2"><br><br><img src="cid:image3"><br>', 'html') msgAlternative.attach(msgText) # This example assumes the image is in the current directory graphImage1 = getGraph(graphid, username, password, api, period) msgImage1 = MIMEImage(graphImage1.getvalue()) msgImage1.add_header('Content-ID', '<image1>') msgRoot.attach(msgImage1) graphImage2 = getGraph(18485, username, password, api, period) msgImage2 = MIMEImage(graphImage2.getvalue()) msgImage2.add_header('Content-ID', '<image2>') msgRoot.attach(msgImage2) graphImage3 = getGraph(11706, username, password, api, period) msgImage3 = MIMEImage(graphImage3.getvalue()) msgImage3.add_header('Content-ID', '<image3>') msgRoot.attach(msgImage3) # Send the email (this example assumes SMTP authentication is required) import smtplib
def alert_smtp(alert, metric): # FULL_DURATION to hours so that analyzer surfaces the relevant timeseries data # in the graph full_duration_in_hours = int(settings.FULL_DURATION) / 3600 # For backwards compatibility if '@' in alert[1]: sender = settings.ALERT_SENDER recipient = alert[1] else: sender = settings.SMTP_OPTS['sender'] recipients = settings.SMTP_OPTS['recipients'][alert[0]] # Backwards compatibility if type(recipients) is str: recipients = [recipients] graph_title = '&title=skyline%%20analyzer%%20ALERT%%20at%%20%s%%20hours%%0A%s%%20-%%20%s' % ( full_duration_in_hours, metric[1], metric[0]) if settings.GRAPHITE_PORT != '': link = '%s://%s:%s/render/?from=-%shour&target=cactiStyle(%s)%s%s&colorList=orange' % ( settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, settings.GRAPHITE_PORT, full_duration_in_hours, metric[1], settings.GRAPHITE_GRAPH_SETTINGS, graph_title) else: link = '%s://%s/render/?from=-%shour&target=cactiStyle(%s)%s%s&colorList=orange' % ( settings.GRAPHITE_PROTOCOL, settings.GRAPHITE_HOST, 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'): try: image_data = urllib2.urlopen(link).read() except urllib2.URLError: image_data = None # 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 body = 'skyline analyzer alert <br> Anomalous value: %s <br> Next alert in: %s seconds <br> <a href="%s">%s</a>' % ( metric[0], alert[2], link, img_tag) for recipient in recipients: msg = MIMEMultipart('alternative') msg['Subject'] = '[skyline alert] ' + metric[1] msg['From'] = sender msg['To'] = recipient msg.attach(MIMEText(body, 'html')) if image_data is not None: msg_attachment = MIMEImage(image_data) msg_attachment.add_header('Content-ID', '<%s>' % content_id) msg.attach(msg_attachment) s = SMTP('127.0.0.1') s.sendmail(sender, recipient, msg.as_string()) s.quit()