def html_footer(logger, html, content): try: logger.info("In html_footer : ") logger.debug("In html_footer %s: ", content) html = html + """ <img src="cid:image2"> </center> </body> """ content.attach(MIMEText(html, "html")) msgAlternative = MIMEMultipart('alternative') content.attach(msgAlternative) fp = open('images/Email_Template_01.jpg', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image1>') content.attach(msgImage) fp = open('images/Email_Template_03.jpg', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image2>') content.attach(msgImage) except Exception: traceback.print_exc() logger.error("Received error while executing html_footer %s", str(e)) finally: return content
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 create_message(from_addr, to_addr, subject, body, encoding): msg = MIMEMultipart() msg['Subject'] = Header(subject, encoding) msg['From'] = from_addr msg['To'] = to_addr msg['Date'] = formatdate() related = MIMEMultipart('related') alt = MIMEMultipart('alternative') related.attach(alt) content = MIMEText(body, 'plain', encoding) alt.attach(content) # 画像を添付 for filename in glob.glob('image/*.png'): print 'attached ' + filename fp = file('%s' % filename, 'rb') img = MIMEImage(fp.read(), 'png', name=filename) related.attach(img) for filename in glob.glob('AgentDataBase/*.gif'): print 'attached ' + filename fp = file('%s' % filename, 'rb') img = MIMEImage(fp.read(), 'gif', name=filename) related.attach(img) for filename in glob.glob('VirusDataBase/*.gif'): print 'attached ' + filename fp = file('%s' % filename, 'rb') img = MIMEImage(fp.read(), 'gif', name=filename) related.attach(img) msg.attach(related) return msg pass
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 email_picture(self): username = self.email.get() password = self.password.get() receivers = self.receiver.get() print "OK" GPIO.setmode(GPIO.BCM) GPIO.setup(4, GPIO.IN, GPIO.PUD_UP) with picamera.PiCamera() as camera: time.sleep(1) kuva = 1 while kuva == 1: d = time.strftime('%a,%d,%b,%Y,%H;%M;%S') GPIO.wait_for_edge(4, GPIO.FALLING) for x in xrange(0, 4): x = x + 1 camera.capture("/home/pi/Desktop/camera/" + str(x) + ".jpg") message = MIMEMultipart() message['Subject'] = 'Valvontakamera Valokuva' message['From'] = 'Raspi' message['To'] = str(receivers) message.preamble = "Photo @ " fp = open("/home/pi/Desktop/camera/1.jpg", "rb") img = MIMEImage(fp.read()) fp.close() img.add_header('Content-Disposition', 'attachment', filename=d + "-" + str(1) + ".jpg") message.attach(img) fp = open("/home/pi/Desktop/camera/2.jpg", "rb") img = MIMEImage(fp.read()) fp.close() img.add_header('Content-Disposition', 'attachment', filename=d + "-" + str(2) + ".jpg") message.attach(img) fp = open("/home/pi/Desktop/camera/3.jpg", "rb") img = MIMEImage(fp.read()) fp.close() img.add_header('Content-Disposition', 'attachment', filename=d + "-" + str(3) + ".jpg") message.attach(img) fp = open("/home/pi/Desktop/camera/4.jpg", "rb") img = MIMEImage(fp.read()) fp.close() img.add_header('Content-Disposition', 'attachment', filename=d + "-" + str(4) + ".jpg") message.attach(img) Server = smtplib.SMTP('smtp.gmail.com:587') Server.starttls() Server.login(username, password) Server.sendmail(username, receivers, message.as_string()) print "email sent!" Server.quit()
def sendmail( tipo, destination, dw ): mensaje = MIMEMultipart() mensaje['Date'] = formatdate(localtime=True) mensaje['From'] = sender mensaje['To'] = destination mensaje['Subject']="Menu del colegio Las Veredas" if tipo == "baja": mensaje.attach( MIMEText(baja) ) elif tipo == "alta" or tipo == "diario": mensaje.attach( MIMEText(alta) ) # Adjuntamos la imagen if dw != "0" and tipo == "diario": try: fi1 = open(datapath + "hoy.jpg" , "rb") contenido = MIMEImage(fi1.read()) contenido.add_header('Content-Disposition', 'attachment; filename = "hoy.jpg"') mensaje.attach(contenido) except: mensaje.attach( "Parece que ha habido algun error.\nNO SE HA ENCONTRADO EL MENU PARA HOY\n" ) if dw != "5" and tipo == "diario": try: fi2 = open(datapath + "manana.jpg" , "rb") contenido2 = MIMEImage(fi2.read()) contenido2.add_header('Content-Disposition', 'attachment; filename = "manana.jpg"') mensaje.attach(contenido2) except: pass elif tipo == "no_available": mensaje.attach( MIMEText(no_available) ) else: mensaje.attach ( MIMEText(ayuda)) try: conn = SMTP(SMTPserver) conn.set_debuglevel(False) conn.login(mailUser, mailPass) try: conn.sendmail(sender, destination, mensaje.as_string()) try: if dw != 0: fi1.close() if dw != 5: fi2.close() except: pass finally: conn.close() except Exception, exc: sys.exit( "mail failed; %s" % str(exc) ) # give an error message
def send_email(self): print('mail sending...') msg = MIMEMultipart() msg.attach(MIMEText('Wykryto ruch! zdjecia: ')) msg.attach( MIMEImage(file("/home/pi/RPiDogOutput/Alarms/alarm1.jpg").read())) msg.attach( MIMEImage(file("/home/pi/RPiDogOutput/Alarms/alarm2.jpg").read())) msg.attach( MIMEImage(file("/home/pi/RPiDogOutput/Alarms/alarm3.jpg").read())) self.s.sendmail(self.smtpUser, self.addrTo, msg.as_string()) print('Email sent!') return
def send_email(image, config): msg_root = MIMEMultipart('related') msg_root['Subject'] = 'Security Update' msg_root['From'] = config.sender_email_address msg_root['To'] = config.receiver_email_address msg_root.preamble = 'Raspberry pi security camera update' msg_alternative = MIMEMultipart('alternative') msg_root.attach(msg_alternative) msg_text = MIMEText('Smart security cam found object') msg_alternative.attach(msg_text) msg_text = MIMEText('<img src="cid:image1">', 'html') msg_alternative.attach(msg_text) msg_image = MIMEImage(image) msg_image.add_header('Content-ID', '<image1>') msg_root.attach(msg_image) smtp = smtplib.SMTP('smtp.gmail.com', 587) smtp.starttls() smtp.login(config.sender_email_address, config.sender_email_password) smtp.sendmail(config.sender_email_address, config.receiver_email_address, msg_root.as_string()) smtp.quit()
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 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 SendScreen( ): # function to send screens (easier to do this as a new function) try: objMsg = MIMEMultipart() objMsg["Subject"] = "New Screenshot From " + strExIP for strScrPath in os.listdir(cPuffDir): # add files to the message strScrFullPath = cPuffDir + "/" + strScrPath img = MIMEImage(file(strScrFullPath, "rb").read()) img.add_header('Content-Disposition', 'attachment', filename=strScrPath) objMsg.attach(img) SmtpServer = smtplib.SMTP_SSL("smtp.gmail.com", 465) SmtpServer.ehlo() SmtpServer.login(strEmailAc, strEmailPass) SmtpServer.sendmail(strEmailAc, strEmailAc, objMsg.as_string()) SmtpServer.close() except: # if the screen cannot send, pass and try again later pass else: for strScrPath in os.listdir(cPuffDir): os.remove( cPuffDir + "/" + strScrPath ) # if the screenshot(s) sent successfully, remove them
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(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 == '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 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 _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 correo(): global l if l==60: msg = MIMEMultipart() msg['From']="tu correo" msg['To']="donde lo vas a enviar" msg['Subject']="Correo con imagen Adjunta" file = open('C:\\Users\ruta\Desktop\key2.png', 'rb') attach_image = MIMEImage(file.read()) attach_image.add_header('Content-Disposition', 'attachment; filename = "imagen.png"') msg.attach(attach_image) fb=open('C:\\Users\ruta\Desktop\key.txt', 'rb') adjunto= MIMEBase('multipart','encryted') adjunto.set_payload(fb.read()) fb.close() encoders.encode_base64(adjunto) adjunto.add_header('Content-Disposition', 'attachment; filename = "key.txt"') msg.attach(adjunto) mailServer = smtplib.SMTP('smtp.gmail.com',587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login("tu correo","clave de tu correo") mailServer.sendmail("tu correo", "correo de destino", msg.as_string()) mailServer.close() l=0
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 SendScreen(): # function to send screens (easier to do this as a new function) if blnFTP == "True": try: ftp = FTP(); ftp.connect(strFtpServer, 21) ftp.login(strFtpUser, strFtpPass); ftp.cwd(strFtpRemotePath) objScrFile = open(strScrPath, "rb") ftp.storbinary("STOR " + strScrPath.split("/")[1], objScrFile) # copy image to ftp objScrFile.close(); ftp.close() except: pass # pass to try again later else: try: objMsg = MIMEMultipart() objMsg["Subject"] = "New Screenshot From " + strExIP img = MIMEImage(file(strScrPath, "rb").read()) # attach image as original file name img.add_header("Content-Disposition", "attachment; filename= %s" % strScrPath.split("/")[1]) objMsg.attach(img) SmtpServer = smtplib.SMTP_SSL("smtp.gmail.com", 465); SmtpServer.ehlo() SmtpServer.login(strEmailAc, strEmailPass) SmtpServer.sendmail(strEmailAc, strEmailAc, objMsg.as_string()) SmtpServer.close() except: pass os.remove(strScrPath) # delete file after sending
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 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 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 send_sendgrid_mail(contents_path, subject, who_from, to): server = smtplib.SMTP('smtp.sendgrid.net', 587) server.starttls() server.login() # TODO developer email, password are parameters fp = open(contents_path, 'rb') body = fp.read() fp.close() msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = who_from msg['To'] = to msg.attach(MIMEText(body, 'html')) fp = open('UNOCHA.jpg', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<unocha>') msg.attach(msgImage) server.sendmail(who_from, to, msg.as_string()) server.quit() print "sent mail"
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 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 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 smtp_process(self, alstr_to, astr_from, astr_subject, astr_body, alstr_attach): # # PRECONDITIONS # o Should only be called by one of the send() methods # o Assumes that any attachments are valid files # # POSTCONDITIONS # o Interacts with the SMTPlib module # self.internals_check() print astr_from msg = MIMEMultipart() msg['Subject'] = astr_subject msg['From'] = astr_from msg.preamble = "This is a mult-part message in MIME format." msg.attach(MIMEText(astr_body)) msg.epilogue = '' for file in alstr_attach: fp = open(file, 'rb') img = MIMEImage(fp.read()) img.add_header('Content-ID', file) fp.close() msg.attach(img) smtp = smtplib.SMTP() smtp.connect(self.mstr_SMTPserver) for str_to in alstr_to: msg['To'] = str_to smtp.sendmail(astr_from, str_to, msg.as_string()) smtp.close()
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_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() )