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 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 _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 send_mail(self): """ sends a schedueled email to all participants """ subject = self.title sender = self.owner.email to_mail = self.email_list context = {'query_list': [v for k, v in self.return_dict.iteritems()]} html_content = render_to_string( os.path.join('email/email_report.html'), context ) text_content = render_to_string( os.path.join('email/email_report.txt'), context ) msg = EmailMultiAlternatives(subject, text_content, sender, to_mail) msg.attach_alternative(html_content, "text/html") msg.mixed_subtype = 'related' # print subject, text_content, sender, to_mail for k, f in self.return_dict.iteritems(): f = f['img'] if f is not None: fp = open(os.path.join(os.path.dirname(__file__), f), 'rb') msg_img = MIMEImage(fp.read()) fp.close() msg_img.add_header('Content-ID', '<{}>'.format(f)) msg.attach(msg_img) msg.send() return msg
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 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 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 _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 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_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 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 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 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 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 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 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_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 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 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 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 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 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 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 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 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 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 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 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 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 create_message_with_attachment(params, subject, message_text, file_dir, filename): """ Create the message with an attachment """ # create a message to send message = MIMEMultipart() message['to'] = params['to'] message['from'] = params['sender'] message['subject'] = subject msg = MIMEText(message_text) message.attach(msg) path = os.path.join(file_dir, filename) content_type, encoding = mimetypes.guess_type(path) main_type, sub_type = content_type.split('/', 1) fp = open(path, 'rb') msg = MIMEImage(fp.read(), _subtype=sub_type) fp.close() msg.add_header('Content-Disposition', 'attachment', filename=filename) message.attach(msg) return {'raw': base64.urlsafe_b64encode(message.as_string())}
def getAttachments(msg, attachmentDirPath): for filename in os.listdir(attachmentDirPath): path = os.path.join(attachmentDirPath, filename) if not os.path.isfile(path): continue contentType, encoding = mimetypes.guess_type(path) if contentType is None or encoding is not None: contentType = 'application/octet-stream' mainType, subType = contentType.split('/', 1) fp = open(path, 'rb') if mainType == 'text': attachment = MIMEText(fp.read()) elif mainType == 'image': attachment = MIMEImage(fp.read(), _subType=subType) elif mainType == 'audio': attachment = MIMEAudio(fp.read(), _subType=subType) else: attachment = MIMEBase(mainType, subType) attachment.set_payload(fp.read()) encode_base64(attachment) fp.close() attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(path)) msg.attach(attachment)
def SendSMS( server, phone, msg_text, attach_file ): if len( msg_text ) <= MAX_TEXT_LENGTH: # Send to all gateways, since a phone number # can only be specific to one carrier. for gateway in SmsGateways: destination = phone + '@' + gateway msg = MIMEMultipart() msg.attach( MIMEText(msg_text, 'plain') ) # Check if valid attachment if attach_file != '': fp = open( attach_file, 'rb' ) msg_img = MIMEImage( fp.read() ) fp.close() msg.attach( msg_img ) server.sendmail( '', destination, msg.as_string() ) else: print 'Message is too long. SMS not sent.' server.quit()
def craft_email(from_address, to, location=None): """Create an email message from <from_address> to <to> Args: from_address: the email address that the email will be from to: the list of addresses to send the email to location: if specified, the location of the image to attach """ MSG_SUBJECT = "ALERT! {}".format(datetime.now()) msg = MIMEMultipart() msg['Subject'] = MSG_SUBJECT msg['From'] = from_address msg['To'] = ", ".join(to) MSG_BODY = MSG_SUBJECT msg_text = MIMEText(MSG_BODY) msg.attach(msg_text) if location and os.path.isfile(location): try: with open(location, 'rb') as image: msg_image = MIMEImage(image.read()) msg.attach(msg_image) except Exception: print "Unable to open file {}".format(location) else: print "Unable to find file {}".format(location) return msg
def write_email(self): fromaddr = "*****@*****.**" toaddr = "*****@*****.**" msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "aliviara - patient update" with open('instructs/ex%s.txt' % (self.e), 'r') as myfile: instr = myfile.read().replace('\n', ' ') body = "\ Hello: \n\n We have been recording performance on hand exercises from Chance the Rapper. The data is suggesting that their performance on some exercises is degrading, which may be early signs of Rheumatoid Arthritis. \n\n The exercises that Chance is failing to complete at the standard of healthy controls is Exercise %s. The instructions for these tasks can be viewed below and a schematic of the exercise is attached to this message. \n \ \n \ \n \ %s \ \n \ \n \ \n \ Best,\n \ The Aliviara Team \n \n \n \ " % (self.e, instr) msg.attach(MIMEText(body, 'plain')) msg.attach( MIMEImage(file("final_figs/ex%s.jpg" % (str(self.e))).read())) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(fromaddr, 'password420') text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit() print 'email sent'
def send(name, passwd, subject, body, addrto, q): msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = name + '@gmail.com' msg['To'] = addrto text = MIMEText(body) msg.attach(text) if (q == "y"): img = askopenfilename() img_data = open(img, 'rb').read() image = MIMEImage(img_data, name=os.path.basename(img)) msg.attach(image) print("connecting") s = smtplib.SMTP('smtp.gmail.com', '587') s.ehlo() s.starttls() s.ehlo() s.login(name, passwd) print("connected") s.sendemail(name + '@gmail.com', addrto, msg.as_string()) print("sent") s.quit()
def mailImages(self, addressList=[], imagePaths=[]): ''' @fn mailImage @brief : Creates MIME image and queues it. @return : Boolean @param addressList : List of the email addresses to send this email to. @param images : List of image paths ''' try: # MIME setup mime = MIMEMultipart() mime['From'] = "TempNetZ {} <".format( self.deviceName) + self.config['User'] + ">" mime['To'] = ", ".join(addressList) mime['Subject'] = "Screenshots" for imagePath in imagePaths: if os.path.exists(imagePath): imageData = open(imagePath, "rb").read() image = MIMEImage(imageData, name=os.path.basename(imagePath)) mime.attach(image) # put in queue return self.queueMessage(self.config['User'], addressList, mime.as_string()) except Exception as e: logging.error('Email: Send images error {0}.'.format(e)) return False
def sendEmail(predicted, confidence, image): server = smtplib.SMTP_SSL('smtp.gmail.com', 465) #SSL port for Gmail server.ehlo( ) #identify ourselves to the server, Gmail prefers EHLO rather than HELO server.login("pivision2017", "vision2017" ) #username, password (tester address [email protected]) originaddress = "*****@*****.**" #From: destaddress = "*****@*****.**" #To: message = MIMEMultipart() #compose a composite email message["From"], message["To"], message[ "Subject"] = originaddress, destaddress, "New entry detected!" entrant = database[predicted] if confidence < 100: body = entrant + " has entered, with a confidence level of " + str( confidence) else: body = "Unknown entrant detected. I think it's " + entrant + " but my confidence is " + str( confidence) body = MIMEText(body) #convert the string we just generated to MIME message.attach(body) #attach to email message if image is not None: encoded = cv2.imencode('.jpg', image)[1].tostring() attachment = MIMEImage(encoded, _subtype='jpeg') message.attach(attachment) text = message.as_string() server.sendmail(originaddress, destaddress, text) server.close()
def sendEmail(): grab_cam = subprocess.Popen(“sudo fswebcam - p YUYV image1.jpeg”, shell = True) grab_cam.wait() image_path = ‘image1.jpeg’ username = “cemakdemir99 @ gmail.com” # gönderilen mail hesabın adını yazıyoruz password = “#######” # gönderilen mail hesabın şifresini yazıyoruz COMMASPACE = ‘, ’ message = MIMEMultipart() message[‘Subject’] = ‘Hareket Algilandi’ me = ‘####### @ gmail.com’ # gönderilecek mail hesabın adını yazıyoruz receivers = ‘########@ gmail.com’ # gönderilecek mail hesabın adını yazıyoruz message[‘From’] = me message[‘To’] = COMMASPACE.join(receivers) message.preamble = ‘Hareket’ fp = open(‘image1.jpeg’, ‘rb’) img = MIMEImage(fp.read()) fp.close() message.attach(img) try: server = smtplib.SMTP(“smtp.gmail.com”, 587) # portu mail servis saglayacisi server.ehlo() server.starttls() server.login(username, password) server.sendmail(me, receivers.split(“, ”), message.as_string()) server.close() print ‘mail gonderildi’ except: print “mail gonderilemedi”
def file2msg(file): ## TODO: check if file exists ctype, encoding = mimetypes.guess_type(file) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/') print "==> Adding file [%s] using [%s]" % (file, ctype) if maintype == "text": fp = open(file) msg = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == "image": fp = open(file, 'rb') msg = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == "audio": fp = open(file, 'rb') msg = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(file, 'rb') msg = MIMEBase(maintype, subtype) msg.set_payload(fp.read()) fp.close() Encoders.encode_base64(msg) return msg
def sendMail(recipient, subject, text, attachment): gmailUser = '******' gmailPassword = '******' msg = MIMEMultipart() msg['From'] = "FareBeast" #gmailUser msg['To'] = recipient msg['Subject'] = subject msg.attach(MIMEText(text)) # for attachmentFilePath in attachmentFilePaths: # msg.attach(getAttachment(attachmentFilePath)) #Open the files in binary mode. Let the MIMEImage class automatically # guess the specific image type. fp = open(attachment, 'rb') img = MIMEImage(fp.read()) fp.close() msg.attach(img) mailServer = smtplib.SMTP('smtp.gmail.com', 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(gmailUser, gmailPassword) mailServer.sendmail(gmailUser, recipient, msg.as_string()) mailServer.close() print('Sent email to %s' % recipient)
def Send(image): cv2.imread(image) cv2.imwrite('detected' + str(i).jpg, image) filee = 'detected' + str(i) + ".jpg" #create message object instance msg = MIMEMultipart() # setup the parameters of the message password = fromEmailPassword msg['From'] = fromEmail msg['To'] = toEmail msg['Subject'] = "Security update by Rpi. AI Cam!" msg.attach(MIMEImage(file(fille).read())) # create server server = smtplib.SMTP('smtp.gmail.com: 587') server.starttls() # Login Credentials for sending the mail server.login(msg['From'], password) # send the message via the server. server.sendmail(msg['From'], msg['To'], msg.as_string()) server.quit() print "successfully sent email to %s:" % (msg['To']) i += 1
def sendEmail(name, pictureString): import smtplib from email.MIMEImage import MIMEImage from email.MIMEMultipart import MIMEMultipart COMMASPACE = ', ' SMTP_SERVER = 'smtp.gmail.com' SMTP_PORT = 587 msg = MIMEMultipart() msg['Subject'] = 'The name of the burglar is ' + name + "." msg['From'] = '*****@*****.**' msg['To'] = COMMASPACE.join('*****@*****.**') msg.preamble = 'The name of the burglar is ' # + str(name) + "." fp = open(pictureString, 'rb') img = MIMEImage(fp.read()) fp.close() msg.attach(img) s = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) s.ehlo() s.starttls() s.ehlo() s.login('*****@*****.**', '$anFi3rro') s.sendmail('*****@*****.**', '*****@*****.**', msg.as_string()) s.quit() return
def get_content_data(self, data, filename, charset=None): "Vrátí data jako instanci třídy odvozené od MIMEBase." # Guess the content type based on the file's extension. Encoding # will be ignored, although we should check for simple things like # gzip'd or compressed files. ctype, encoding = mimetypes.guess_type(filename) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': # Note: we should handle calculating the charset if not charset: charset = self.charset content = MIMEText(data, _subtype=subtype, _charset=charset) elif maintype == 'image': content = MIMEImage(data, _subtype=subtype) elif maintype == 'audio': content = MIMEAudio(data, _subtype=subtype) else: content = MIMEBase(maintype, subtype) content.set_payload(data) email.Encoders.encode_base64(content) return content
def getAttachment(self, attachmentFilePath): contentType, encoding = mimetypes.guess_type(attachmentFilePath) if contentType is None or encoding is not None: contentType = 'application/octet-stream' mainType, subType = contentType.split('/', 1) file = open(attachmentFilePath, 'rb') if mainType == 'text': attachment = MIMEText(file.read()) # elif mainType == 'html': # attachment = MIMEText(file.read(), 'html') elif mainType == 'message': attachment = email.message_from_file(file) elif mainType == 'image': attachment = MIMEImage(file.read(), _subType=subType) elif mainType == 'audio': attachment = MIMEAudio(file.read(), _subType=subType) else: attachment = MIMEBase(mainType, subType) attachment.set_payload(file.read()) encode_base64(attachment) file.close() attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachmentFilePath)) return attachment
def _add_attachment(outer, filename): import sys import os ctype, encoding = mimetypes.guess_type(filename) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) fp = open(filename, 'rb') if maintype == 'text': # Note: we should handle calculating the charset msg = MIMEText(fp.read(), _subtype=subtype) elif maintype == 'image': msg = MIMEImage(fp.read(), _subtype=subtype) elif maintype == 'audio': msg = MIMEAudio(fp.read(), _subtype=subtype) else: msg = MIMEBase(maintype, subtype) msg.set_payload(fp.read()) # Encode the payload using Base64 encoders.encode_base64(msg) fp.close() # Set the filename parameter msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(filename)) outer.attach(msg)
def attach_files(msg): filename = raw_input('File name: ') try: f = open(filename, 'rb') except IOError: print 'Attachment not found' return msg ctype, encoding = mimetypes.guess_type(filename) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': part = MIMEText(f.read(), _subtype=subtype) elif maintype == 'image': part = MIMEImage(f.read(), _subtype=subtype) elif maintype == 'audio': part = MIMEAudio(f.read(), _subtype=subtype) else: part = MIMEBase(maintype, subtype) msg.set_payload(f.read()) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(filename)) msg.attach(part) f.close() return msg
def send_email(recipient, nodarb, timedate, code_uuid): # Define these once; use them twice! strFrom = '*****@*****.**' strTo = recipient new_time = timedate + timedelta(hours=dst(timedate)) time = new_time.strftime("%Y/%m/%d %H:%M") code = 'http://pieraksts.vfabrika.lv/atcelt/' + str(code_uuid) + '/' # Create the root message and fill in the from, to, and subject headers msgRoot = MIMEMultipart('related') msgRoot['Subject'] = u'"Veselības Fabrika" pieraksts' 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) 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 content = u'<b><p>Paldies par veikto rezervāciju uz nodarbību – <i>' + time + ', ' + nodarb + u'</i></b></p><br><p>Rezervācijas atcelšanai lūdzam izmantot šo saiti:<br>' + code + u'</p><br><p>Jūsu sporta klubs <b><i> “</i>Veselības Fabrika<i>”</i></b></p><img src="cid:image1">' msgText = MIMEText(content.encode('utf-8'), 'html', 'utf-8') msgAlternative.attach(msgText) # This example assumes the image is in the current directory fp = open('/pieraksts/static/logo.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 (SMTP authentication is required) import smtplib smtp = smtplib.SMTP("smtp.gmail.com", 587) smtp.ehlo() smtp.starttls() smtp.login(strFrom, 'fabrika2017') smtp.sendmail(strFrom, strTo, msgRoot.as_string()) smtp.quit()
def send_cancel(recipient, datums, nos): # Define these once; use them twice! strFrom = '*****@*****.**' strTo = recipient new_time = datums + timedelta(hours=dst(datums)) time = new_time.strftime("%Y/%m/%d %H:%M") # Create the root message and fill in the from, to, and subject headers msgRoot = MIMEMultipart('related') msgRoot['Subject'] = u'"Veselības Fabrika" pieraksts' 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) 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 content = u'<p><b>' + time + u' paredzētā nodarbība ' + nos + u' atceļas.</b></p><p> Aicinām pieteikties uz citu nodarbību vai vingrot mūsu trenažieru zālē.</p><p>Atvainojamies par neērtībām.</p><p>Jūsu sporta klubs <b><i> “</i>Veselības Fabrika<i>”</i></b></p><img src="cid:image1">' msgText = MIMEText(content.encode('utf-8'), 'html', 'utf-8') msgAlternative.attach(msgText) # This example assumes the image is in the current directory fp = open('/pieraksts/static/logo.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 (SMTP authentication is required) import smtplib smtp = smtplib.SMTP("smtp.gmail.com", 587) smtp.ehlo() smtp.starttls() smtp.login(strFrom, 'fabrika2017') smtp.sendmail(strFrom, strTo, msgRoot.as_string()) smtp.quit()
def sendMessage(url, number, carrier): # Define these once; use them twice! strFrom = '*****@*****.**' strTo = str(number) + carrier # Create the root message and fill in the from, to, and subject headers msgRoot = MIMEMultipart('related') 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) # We reference the image in the IMG SRC attribute by the ID we give it below msgText = MIMEText('<img src="cid:image1">', 'html') msgAlternative.attach(msgText) response = requests.get(url) size = 900, 900 #Can go higher it only took up 45kb img = StringIO(response.content) newImg = cStringIO.StringIO() #open with PILL now im = Image.open(img) #Resize Image im = im.resize(size, Image.ANTIALIAS) #Try to get best quality quality_val = 100 im.save(newImg, "JPEG", quality=quality_val) # MIMEImage msgImage = MIMEImage(newImg.getvalue()) # Define the image's ID as referenced above msgImage.add_header('Content-ID', '<image1>') msgRoot.attach(msgImage) #start emailing server = smtplib.SMTP("smtp.gmail.com", 587) # Send the email (this example assumes SMTP authentication is required) server.starttls() server.login(os.getenv('email'), os.getenv('password')) server.sendmail(strFrom, strTo, msgRoot.as_string()) server.quit()
def send_email(today_statistic,this_month_statistic,this_year_statistic,error_matrix,to_emails,folder_images): #---email body msg_1 = '\n Risultati programma *human torch* eseguito il:\t' + str(datetime.datetime.today()) + '\n' + '\n' + '\n' msg_2 = 'Produzione giornaliera --- Prodotta:\t' + '%1.2f' % (today_statistic[0]) + '\tkWh' +'\n' msg_3 = 'Stimata da Solarimetro:\t' + '%1.2f' % (today_statistic[1]) + '\tkWh' + '\n' msg_4 = 'Stimata da PVGIS:\t' + '%1.2f' % (today_statistic[2]) + '\tkWh' + '\n' msg_5 = 'Percentuale [prodotta/stimata_solarimetro]:\t' + '%1.2f%%' % (today_statistic[0]/today_statistic[1]*100.) + '\n' msg_6 = 'Percentuale [prodotta/stimata_PVGIS]:\t' + '%1.2f%%' % (today_statistic[0]/today_statistic[2]*100.) + '\n'+ '\n'+ '\n' msg_7 = 'Produzione Mensile (ad oggi) --- Prodotta:\t' + '%1.2f' % (this_month_statistic[0]) + '\tkWh' + '\n' msg_8 = 'Stimata da Solarimetro:\t' + '%1.2f' % (this_month_statistic[1]) + '\tkWh' + '\n' msg_9 = 'Stimata da PVGIS:\t' + '%1.2f' % (this_month_statistic[2]) + '\tkWh' + '\n' msg_10= 'Percentuale [prodotta/stimata_PVGIS]:\t' + '%1.2f%%' % (this_month_statistic[0]/this_month_statistic[2]*100.) + '\n'+ '\n'+ '\n' msg_11= 'Produzione Annuale (ad oggi) --- Prodotta:\t' + '%1.2f' % (this_year_statistic[0]) + '\tkWh' + '\n' msg_12= 'Stimata da PVGIS:\t' + '%1.2f' % (this_year_statistic[1]) + '\tkWh' + '\n' msg_13= 'Percentuale [prodotta/stimata_PVGIS]:\t' + '%1.2f%%' % (this_year_statistic[0]/this_year_statistic[1]*100.) + '\n'+ '\n'+ '\n' body_text = msg_1 + msg_2 + msg_3 + msg_4 + msg_5 + msg_6 + msg_7 + msg_8 + msg_9 + msg_10 + msg_11 + msg_12 + msg_13 #- I am adding here the error report -# message_errors = '\n\n\n\n\n' message_errors = message_errors + 'Errori di produzione riscontrati oggi:\n' for i in range(0,len(error_matrix)): # print ['Inverter = ', error_matrix[i][3], '-- Produzione Stimata =',error_matrix[i][2], '-- Produzione Effettiva',error_matrix[i][1], 'Ore:',error_matrix[i][0]] message_errors = message_errors + 'Inverter = ' + str(error_matrix[i][3]) + ' -- Produzione Stimata = ' + str(error_matrix[i][2]) + ' -- Produzione Effettiva = ' + str(error_matrix[i][1]) + ' Ore: ' + str(error_matrix[i][0]) message_errors = message_errors + '\n' body_text = body_text + message_errors #---< end msg = MIMEMultipart() msg['From'] = gmail_user msg['Subject'] = 'fotovoltaico - impianto ' + os.path.split(os.getcwd())[1] + ' - statistica al ' + str(datetime.datetime.today()) msg.attach(MIMEText(body_text)) png_folder = os.path.join(folder_images,datetime.date.today().strftime('%Y')) png_folder = os.path.join(png_folder,datetime.date.today().strftime('%m')) png_folder = os.path.join(png_folder,datetime.date.today().strftime('%d')) for (root, dirs, files) in os.walk(png_folder): for file in files: fp = open(os.path.join(root,file), 'rb') img = MIMEImage(fp.read()) fp.close() msg.attach(img) for to_email in to_emails: msg['To'] = to_email mailServer = smtplib.SMTP('smtp.gmail.com', 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(gmail_user, gmail_pwd) mailServer.sendmail(gmail_user, to_email, msg.as_string()) mailServer.close()
def send_mail(x, i): msgRoot = MIMEMultipart('related') msgRoot['Subject'] = subject msgRoot['From'] = email_from msgRoot['To'] = sys.argv[1] msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) if x == '0' or x == '3': msgText = MIMEText( '<p>%s,<p/><p>%s</p><br><img src="cid:image1">' % (salutation, body), 'html') msgAlternative.attach(msgText) msgImage = MIMEImage(i) msgImage.add_header('Content-ID', '<image1>') msgRoot.attach(msgImage) else: msgText = MIMEText('<p>%s,<p/><p>%s</p>', 'html') msgAlternative.attach(msgText) try: #smtp = smtplib.SMTP('localhost') # smtp.connect(smtp_server) smtp = smtplib.SMTP(smtp_server[0], smtp_server[1]) smtp.ehlo() smtp.starttls() smtp.login(mail_user, mail_pass) smtp.sendmail(email_from, sys.argv[1], msgRoot.as_string()) logout_api() print( "Successfully sent email | Email enviado com sucesso ({0})".format( sys.argv[1])) log.writelog( 'Successfully sent email | Email enviado com sucesso ({0})'.format( sys.argv[1]), arqLog, "INFO") smtp.quit() except smtplib.SMTPException: print( "Error: Unable to send email | Não foi possível enviar o e-mail ({0})" .format(sys.argv[1])) log.writelog( 'Error: Unable to send email | Não foi possível enviar o e-mail ({0})' .format(sys.argv[1]), arqLog, "WARNING")
def send_multi(self, subject, text, text_type, attachs): # 邮件对象 msg = MIMEMultipart() msg['From'] = self.__format__addr( u'股票小助手<%s>' % (self.account + self.postfix)) #发送邮箱地址 # msg['To'] = to_ #接收邮箱地址 msg['Subject'] = Header(subject, 'UTF-8') #邮件主题,注意此处使用了UTF-8编码,不然发送中文乱码 msg['Date'] = email.Utils.formatdate() #发送时间 # msg['To'] = to # 接收邮箱地址 # 邮件正文是MIMEText msg.attach(MIMEText(text, text_type, 'utf-8')) #添加附件 for attach in attachs: with open(attach, 'rb') as f: #设置附件的MIME和文件名,扩展名 fileName = os.path.basename(attach).split('.')[0] # extenName = os.path.splitext(attach)[1] # print fileName img = MIMEImage(f.read()) img.add_header('Content-ID', fileName) msg.attach(img) # mime = MIMEBase('image', extenName, filename = fileName) # 加上必要的头信息: # mime.add_header('Content-Disposition', 'attachment', filename= fileName) # mime.add_header('Content-ID', '<0>') # mime.add_header('X-Attachment-Id', '0') # 把附件的内容读进来: # mime.set_payload(f.read()) # 用Base64编码: # encoders.encode_base64(mime) # 添加到MIMEMultipart: # msg.attach(mime) try: failed = self.server.sendmail(self.account + self.postfix, self.receiveAccounts, msg.as_string()) except Exception, ex: print Exception, ex print 'Error - send failed'
def sendEmail(msgTo, content, subject, file_list): (attachment, html) = content msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = '*****@*****.**' msg['To'] = msgTo html_att = MIMEText(html, 'html', 'utf-8') att = MIMEText(attachment, 'plain', 'utf-8') msg.attach(html_att) for file in file_list: try: fp = open("/home/blackhole/" + file[0], 'rb') img = MIMEImage(fp.read(), _subtype="png") img.add_header('Content-ID', file[1].replace('.png', '')) msg.attach(img) except Exception, e: return False
def sendEmailUser(self, user, server): msg = MIMEMultipart('related') msg['From'] = MAIL_USERNAME msg['To'] = user.email msg['Subject'] = 'Test email' msgAlternative = MIMEMultipart('alternative') msg.attach(msgAlternative) body, mediaDict = self.buildUserTemplate(user) body = MIMEText(body, 'html') msgAlternative.attach(body) for cidUUID, mediaPath in mediaDict.items(): with open(os.path.join(os.getcwd() + '/app/', mediaPath), 'rb') as myImage: msgImage = MIMEImage(myImage.read()) msgImage.add_header('Content-ID', '<{}>'.format(cidUUID)) msg.attach(msgImage)
def save(self, domain_override=None, subject_template_name='registration/password_reset_subject.txt', email_template_name='registration/password_reset_email.html', use_https=True, token_generator=default_token_generator, from_email=None, request=None): """ Generates a one-use only link for resetting password and sends to the user. """ for user in self.users_cache: if not domain_override: current_site = get_current_site(request) site_name = current_site.name domain = current_site.domain else: site_name = domain = domain_override c = { 'email': user.email, 'domain': 'tecs.herokuapp.com', 'site_name': 'tecs.herokuapp.com', 'uid': int_to_base36(user.pk), 'user': user, 'token': token_generator.make_token(user), 'protocol': use_https and 'https' or 'http', } subject = render_to_string(subject_template_name, c) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) email = render_to_string(email_template_name, c) fp = open('./static/base/img/icons/password_manager.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image1>') mailSend = EmailMessage(subject, email, '*****@*****.**', [user.email]) mailSend.content_subtype = "html" # Main content is now text/html mailSend.attach(msgImage) mailSend.send()
def getMailPicture(filename): msgImage=None if os.path.exists(filename): fp = open(filename, 'rb') msgImage = MIMEImage(fp.read(),_subtype='jpeg') fp.close() return msgImage
def sendEmail(authInfo, fromAdd, toAdd, subject, plainText, htmlText,picture): server = authInfo.get('server') user = authInfo.get('user') passwd = authInfo.get('passwd') if not (server and user and passwd) : print 'need set server and user and passwd ' return False msgRoot = MIMEMultipart('related') msgRoot['Subject'] = subject msgRoot['From'] = fromAdd msgRoot['To'] = ', '.join( toAdd ) msgRoot.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgRoot.attach( msgAlternative ) if plainText: msgText = MIMEText(plainText, 'plain','utf-8') msgAlternative.attach(msgText) if htmlText: msgText = MIMEText(htmlText, 'html','utf-8') msgAlternative.attach(msgText) #if need send picture . if picture: fp = open(picture, 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID','<image1>') msgRoot.attach(msgImage) smtp = smtplib.SMTP() smtp.set_debuglevel(0) try: smtp.connect(server) smtp.login(user, passwd) smtp.sendmail( msgRoot['From'], toAdd , msgRoot.as_string()) smtp.quit() except Exception,ex: print ex return False
def _send(self): if not self.sent: self.last_attempt = timezone.now() subject, from_email = self.subject, self.from_address text_content = self.content msg = EmailMultiAlternatives(subject, text_content, from_email) if getattr(settings, "EMAIL_TEST_MODE", None): msg.to = settings.MAIL_ADMINS else: msg.to = [email.strip() for email in self.to_address.split(',') if email.strip()] msg.bcc = [email.strip() for email in self.bcc_address.split(',') if email.strip()] # Add any additional attachments for attachment in self.attachment_set.all(): filename = os.path.join(settings.MEDIA_ROOT, attachment.file_attachment.name) if attachment.inline_content_id: try: with open(filename, 'rb') as fo: to_attach = MIMEImage(fo.read()) except TypeError: # invalid image, skip continue to_attach.add_header('Content-ID', '<%s>' % attachment.inline_content_id) msg.attach(to_attach) msg.mixed_subtype = 'related' elif attachment.name: with open(filename, 'rb') as fo: msg.attach(attachment.name, fo.read()) else: msg.attach_file(filename) if self.html_content: html_content = self.html_content msg.attach_alternative(html_content, "text/html") try: msg.send() self.sent = True except Exception as e: self.do_not_send = True logger.error('Mail Queue Exception: {0}'.format(e)) self.save()
def embedImage(msg, embedImageDirPath): for filename in os.listdir(embedImageDirPath): path = os.path.join(embedImageDirPath, filename) if not os.path.isfile(path): continue contentType, encoding = mimetypes.guess_type(path) mainType, subType = contentType.split('/', 1) if mainType == 'image': fp = open(path, 'rb') msgImage = MIMEImage(fp.read()) fp.close msgImage.add_header('Content-ID', '<image1>') msg.attach(msgImage) break