コード例 #1
0
ファイル: email_notifier.py プロジェクト: amluu/AC_Control
class notifier():
	def __init__(self):
		# Credentials
		self.username = '******'
		self.fromaddr = '*****@*****.**'
		#uses base64 to provide an illusion of security
		self.password = base64.b64decode("Mzk3ODY2UzEyRDUy")
		self.toaddrs = ''
		self.subject = ''
		self.body = ''
	# sets the email's recepients, should be in form ['*****@*****.**','*****@*****.**']
	def set_recepients(self,toaddrs):
		self.toaddrs = toaddrs
	def set_content(self,subject, body):
		self.subject = subject
		self.body = body
	def send(self):
		#sends the email
		self.msg = MIMEMultipart()
		self.msg['From'] = self.fromaddr
		self.msg['To'] = COMMASPACE.join(self.toaddrs)
		self.msg['Subject'] = self.subject
		self.msg.attach(MIMEText(self.body, 'plain'))
		self.server = smtplib.SMTP('smtp.gmail.com:587')
		self.server.ehlo()
		self.server.starttls()
		self.server.ehlo()
		self.server.login(self.username,self.password)
		self.server.sendmail(self.fromaddr, self.toaddrs, self.msg.as_string())
		print self.msg.as_string()
		self.server.quit()
	def __del__(self):
		pass
コード例 #2
0
def sendEmail(recipient, empty=False):
    '''
    Sends an email to the sepcified recipient.
    If there are no files present then an email will be sent out
    saying no impedances were tested this week
    '''
    if not empty:
        msg = MIMEMultipart()
        # Set subject of the message; using a global value
        msg['Subject'] = 'Impedance Values for the week of' + weekFolder
        msg['To'] = recipient
        # using a global value
        msg['From'] = em
        msg.attach(MIMEText('This is an automated script built by Win\nAttached are the array impedance values for this week: '))
        attach = MIMEBase('application', 'zip')
        with open(imagePath + '.zip', 'rb') as r:
            attach.set_payload(r.read())
        Encoders.encode_base64(attach)
        attach.add_header('Content-Disposition', 'attachment', filename=weekFolder + '.zip')
        msg.attach(attach)
        s = smtplib.SMTP('smtp.gmail.com:587') #465
        s.starttls()
        s.login(em, passw)
        s.sendmail(em, recipient, msg.as_string())
        s.quit()
    else:
        msg = MIMEText('No arrays were impedance tested this week. (Or at least their text files weren\'t put into this folder.)\n\nThis is an automated script made by Win')
        msg['Subject'] = 'No impedance values this week'
        msg['To'] = recipient
        msg['From'] = em
        s = smtplib.SMTP('smtp.gmail.com:587')
        s.starttls()
        s.login(em, passw)
        s.sendmail(em, recipient, msg.as_string())
        s.quit()
コード例 #3
0
ファイル: tflTxTrends.py プロジェクト: cwalltx/irie-wall
def mail(content):
    global extraInfo
    msg = MIMEMultipart()
    
    # extra info gathered along the way
    for info in extraInfo:
        msg.attach(MIMEText(info, 'html'))

    # link to team
    msg.attach(MIMEText('<br/>Team: ' + TEAM_HREF, 'html'))
    msg.attach(MIMEText(BUZZ_HREF, 'html'))
    
        
    # buzz content
    msg.attach(MIMEText(content, 'html'))
    
    msg['From'] = GMAIL_USER
    msg['To'] = GMAIL_USER
    msg['Subject'] = subjectPrefix + ' ' + SUBJECT

    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(GMAIL_USER, GMAIL_PWD)
    print msg.as_string()
    mailServer.sendmail(GMAIL_USER, GMAIL_USER, msg.as_string())
    # Should be mailServer.quit(), but that crashes...
    mailServer.close()
    print 'Sent mail to ' + GMAIL_USER
コード例 #4
0
    def _SendInvitation(self, options, address, uid, calName, token, rights) :
        msg = MIMEMultipart()
        msg['Subject'] = "%s has shared a calendar with you" % (options.user)
        msg['From'] = "%s@localhost" % (options.user)
        msg['To'] = address

        description = MIMEMultipart("alternative")
        description.attach(MIMEText("This is a thing"))
        description.attach(MIMEText("<b>This is a thing, in html</b>", "html"))
        
        msg.attach(description)

        invitation = {}
        invitation["owner"] = options.user
        # FIXME: get the server name right
        invitation["server"] = "localhost"
        invitation["calendarName"] = calName
        invitation["calendarId"] = uid
        invitation["token"] = token
        invitation["rights"] = rights
        
        msg.attach(MIMEText(simplejson.dumps(invitation), "x-bongo-invitation"))
                
        print "sending:"
        print msg.as_string()
        self._SendMessage(options, address, msg)
コード例 #5
0
ファイル: multimail.py プロジェクト: civil-savage/mime-email
def main():
    msgRoot = MIMEMultipart('alternative')
    msgRoot.preamble = 'This is a multi-part message in MIME format.'
    with open(TEXT_FILE, 'r') as txt_f:
        text = txt_f.read()
    msgRoot.attach(MIMEText(text))
    with open(HTML_FILE,'r') as html_f:
        html = html_f.read()
    if IMAGES:
        msgRelated = MIMEMultipart('related')
        msgRelated.attach(MIMEText(html, 'html')) 
        for image in IMAGES: 
            with open(image, 'rb') as img: 
                msgImage = MIMEImage(img.read())
                msgImage.add_header('Content-ID', os.path.split(image)[1]) ## clean up to remove the folder location in the for cid
                msgRelated.attach(msgImage)        
        msgRoot.attach(msgRelated)
    else:
        msgRoot.attach(MIMEText(html, 'html'))
    if SEND:
        msgRoot['To'] = SEND[0]
        msgRoot['From'] = SEND[1]
        msgRoot['Subject'] = SEND[2]
        smtp = smtplib.SMTP('localhost')
        smtp.sendmail(SEND[0], SEND[1], msgRoot.as_string())
        smtp.quit()
    print(msgRoot.as_string()) 
コード例 #6
0
ファイル: sendout.py プロジェクト: jeffkaufman/diplomator
def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
  """ modified from http://snippets.dzone.com/posts/show/2038 """

  print "Sending %s to %s" % (files, send_to)
  
  assert type(send_to)==list
  assert type(files)==list

  msg = MIMEMultipart()
  msg['From'] = send_from
  msg['To'] = COMMASPACE.join(send_to)
  msg['Date'] = formatdate(localtime=True)
  msg['Subject'] = subject

  msg.attach( MIMEText(text) )

  for f in files:
    part = MIMEBase('application', "octet-stream")
    part.set_payload( open(f,"rb").read() )
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
    msg.attach(part)

  if use_smtp:
    smtp = smtplib.SMTP(server)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
  else:
    sendmail_location = "/usr/sbin/sendmail" # sendmail location
    p = os.popen("%s -t" % sendmail_location, "w")
    p.write(msg.as_string())
    
    status = p.close()
    if status:
       raise Exception("Sendmail failed with status %s" % status)
コード例 #7
0
ファイル: mail.py プロジェクト: Birne94/Coffee-in-the-Cloud
def send_email(from_, to, subject, content, attachment=None, content_type=None):
    print "sending mail"
    try:
        if isinstance(to, str) or isinstance(to, unicode):
            to = (to,)

        msg = MIMEMultipart()
        msg["Subject"] = subject
        msg["From"] = from_
        msg["To"] = ", ".join(to)
        msg["Content-Type"] = "multipart/alternative"
        msg.attach(MIMEText(content + "\n\n"))

        if attachment:
            att = MIMEText(attachment + "\n\n")
            att["Content-Type"] = content_type or "text/calendar; charset=\"us-ascii\"; method=REQUEST"
            att["Filename"] = "subject.ics"
            msg.attach(att)

        print msg.as_string()

        connection = smtplib.SMTP(MAIL_SERVER)
        connection.sendmail(
            from_,
            to,
            msg.as_string()
        )
        connection.quit()
    except:
        import sys
        print sys.exc_info()[0]
コード例 #8
0
    def alert(self, problems):
        """
        problems is a list of tuples
        each tuple contains two values: the filename where the problem
        was detected, and the problem
        
        problems = [('Monitor1.txt','50')]
        
        """

        now = datetime.datetime.now()
        message = "At %s, found problems with the following monitors:\n" % now

        for (monitor, value) in problems:
            message += "%s\t%s\n" % (os.path.split(monitor)[1], value)

        msg = MIMEMultipart()
        msg["From"] = "Fly Dam Alert service"
        msg["To"] = self.email_recipient
        msg["Subject"] = "flyDAM alert!"

        try:
            text = MIMEText(message, "plain")
            msg.attach(text)

            s = smtplib.SMTP(self.email_server)
            s.sendmail(self.email_sender, self.email_recipient, msg.as_string())
            s.quit()

            print msg.as_string()

        except smtplib.SMTPException:
            print "Error: unable to send email"
コード例 #9
0
ファイル: scrap.py プロジェクト: gmpetrov/LeboncoinScrapper
    def sendMail(self, title, price, url, recipients):

        fromaddr = GLOBALS.smtpServerLogin
        toaddr = GLOBALS.smtpServerRecipient

        # edit the message
        msg = MIMEMultipart()
        msg['From'] = fromaddr
        msg['To'] = toaddr
        msg['Subject'] = title

        body = self.createMailBody(title, price, url)

        msg.attach(MIMEText(body.encode('utf-8'), 'plain'))

        # Init the smtp server
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(fromaddr, GLOBALS.smtpServerPasswd)

        # Send mail to recipients
        for email in recipients:
            server.sendmail(fromaddr, email, msg.as_string())

        if len(recipients) < 1:
            server.sendmail(fromaddr, toaddr, msg.as_string())

        # quit smtp server
        server.quit()
コード例 #10
0
def mail(to, subject, text, attach, prioflag1, prioflag2):
    msg = MIMEMultipart()
    msg["From"] = from_address
    msg["To"] = to
    msg["X-Priority"] = prioflag1
    msg["X-MSMail-Priority"] = prioflag2
    msg["Subject"] = subject
    # specify if its html or plain
    # body message here
    body_type = MIMEText(text, "%s" % (message_flag))
    msg.attach(body_type)
    # define connection mimebase
    part = MIMEBase("application", "octet-stream")
    part.set_payload(open(attach, "rb").read())
    # base 64 encode message mimebase
    Encoders.encode_base64(part)
    # add headers
    part.add_header("Content-Disposition", 'attachment; filename="%s"' % os.path.basename(attach))
    msg.attach(part)
    # define connection to smtp server
    mailServer = smtplib.SMTP(smtp, int(port))
    mailServer.ehlo()
    # send ehlo to smtp server
    if sendmail == 0:
        if email_provider == "gmail":
            mailServer.ehlo()
            # start TLS for gmail sometimes needed
            try:
                mailServer.starttls()
            except:
                pass
            mailServer.ehlo()
    if counter == 0:
        try:
            if email_provider == "gmail":
                try:
                    mailServer.starttls()
                except:
                    pass
                mailServer.ehlo()
                if len(user) > 0:
                    mailServer.login(user, pwd)
                mailServer.sendmail(user1, to, msg.as_string())
        except Exception, e:
            print_error(
                "Unable to deliver email. Printing exceptions message below, this is most likely due to an illegal attachment. If using GMAIL they inspect PDFs and is most likely getting caught."
            )
            raw_input("Press {return} to view error message.")
            print str(e)
            try:
                mailServer.docmd("AUTH LOGIN", base64.b64encode(user))
                mailServer.docmd(base64.b64encode(pwd), "")
            except Exception, e:
                print str(e)
                try:
                    mailServer.login(user, pwd)
                    thread.start_new_thread(mailServer.sendmail, (user1, to, msg.as_string()))
                except Exception, e:
                    return_continue()
コード例 #11
0
def mail(to, subject, text, attach, prioflag1, prioflag2):
	msg = MIMEMultipart()
	# From 
	msg['From'] = user1
	# To
	msg['To'] = to
	# Add Priority
	msg['X-Priority'] = prioflag1
	msg['X-MSMail-Priority'] = prioflag2
	# Subject tag
	msg['Subject'] = subject
	# specify if its html or plain
	# body message here
	body_type=MIMEText(text, "%s" % (message_flag))
	# any attachments
	msg.attach(body_type)
	# define connection mimebase
	part = MIMEBase('application', 'octet-stream')
	part.set_payload(open(attach, 'rb').read())
	# base 64 encode message mimebase
	Encoders.encode_base64(part)
	# add headers
	part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(attach))
	msg.attach(part)
	# define connection to smtp server
	mailServer = smtplib.SMTP(smtp, int(port))
	# send ehlo to smtp server
	mailServer.ehlo()
	if sendmail == 0:
		if email_provider == "gmail":
			mailServer.ehlo()
			# start TLS for gmail sometimes needed
			try:
				mailServer.starttls()
			except: pass
			mailServer.ehlo()
	if counter == 0:
		try:
			if email_provider == "gmail":
				try:
					mailServer.starttls()
				except: pass
				mailServer.ehlo()
				mailServer.login(user, pwd)
				thread.start_new_thread(mailServer.sendmail,(user, to, msg.as_string()))
		except Exception, e:
			print str(e)
			try:
				mailServer.docmd("AUTH LOGIN", base64.b64encode(user))
				mailServer.docmd(base64.b64encode(pwd), "")
			except Exception,e:
				print str(e)
				try:
					mailServer.login(user, pwd)
					thread.start_new_thread(mailServer.sendmail,(user, to, msg.as_string()))
				except Exception, e:
					print "\n   It appears your password was incorrect.\nPrinting response: "+(str(e))
					pause=raw_input("   Press enter to continue.")
コード例 #12
0
ファイル: sendEmail.py プロジェクト: tomli1981/mail
def send_mail(mail_from, mail_to, subject, msg_txt, files=[]):
    # Create message container-the correct MIME type is mutipart/alternative
    msg = MIMEMultipart('alternative')
    # msg['Subject'] = subject
    if not isinstance(subject, unicode):
        msg['Subject'] = unicode(subject)
    else:
        msg['Subject'] = subject

    msg['From'] = mail_from  # Header(mail_from, 'utf-8')
    msg['To'] = mail_to

    # Create the body of the body of the message(a plain-text and HTML version)
    text = msg_txt
    html = msg_txt

    # Record the MIME types of both parts-text/plain and text/html
    part1 = MIMEText(text, 'plain', 'utf-8')
    part2 = MIMEText(html, 'html', 'utf-8')
    # part1["Accept-Language"] = "zh-CN"
    # part1["Accept-Charset"] = "ISO-8859-1,utf-8"
    # part2["Accept-Language"] = "zh-CN"
    # part2["Accept-Charset"] = "ISO-8859-1,utf-8"
    # Attach parts into the message container
    # According to RFC 2046, the last part of the a mutipart message, in this case
    # the HTML message, is the best and preferred
    msg.attach(part1)
    msg.attach(part2)

    # attachement
    for f in files:
        # octet-stream:binary data
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(open(f, 'rb').read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
        msg.attach(part)
    # Send the message via local SMTP server
    s = smtplib.SMTP("localhost")
    s.set_debuglevel(1)
    # Send mail function takes 3 arguments: sender's address, recipients's address
    # and message to snd - here it sent as on string.

    mailto_list = mail_to.strip().split(",")
    try:
        if len(mailto_list) > 1:
            for mailtoi in mailto_list:
                s.sendmail(mail_from, mailtoi.strip(), msg.as_string())
        else:
            s.sendmail(mail_from, mail_to, msg.as_string())
    except:
        raise
    finally:  # close the connection no matter what happens
        s.quit()

    return True
コード例 #13
0
ファイル: library.py プロジェクト: mrcjhurst/evoke
def email(FROM,TO,subject="", text="",html="",SMTP='127.0.0.1',LOGIN=[], sender="", replyto="", attachments={}):
  """send a multipart plain text (or html) message, using given SMTP
  - Optional LOGIN (ie SMTP validation) must give (<user>,<password>)
  - allows for a list of recipients in TO: each gets a separate email, ie bcc

  - attachment expects a dictionary of {filename:content}
  """
  if not (FROM and TO and SMTP):
 #   print "EMAIL DISABLED >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
    return # email is disabled or invalid, so do nothing
  # set up our message
  root = MIMEMultipart('related')
  root['Subject'] = subject
  if sender:
    root['From'] = '"%s" <%s>' % (sender, FROM)
  else:
    root['From'] = FROM
  if replyto:
    root['Reply-To'] = replyto
  if isinstance(TO,basestring):
    TO=[TO]
  root.preamble = 'This is a multi-part message in MIME format.'
  # add our alternative versions
  alt = MIMEMultipart('alternative')
  root.attach(alt)
  if html:
    alt.attach(MIMEText(html, 'html'))
  else:  
    alt.attach(MIMEText(text))

  # include attachments
  for filename,content in attachments.items():
    part = MIMEBase('application', 'octet-stream')
    part.set_payload(content)
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename=%s' % filename)
    root.attach(part)

  # send our message(s)
  try:
    smtp = smtplib.SMTP()
    smtp.connect(SMTP)
    if LOGIN:
      smtp.login(*LOGIN)
    for t in TO: 
      try:
        root['To']=t
        smtp.sendmail(FROM, t, root.as_string())
#        print "SENT: FROM=",FROM,' TO=',t,' ROOT=', root.as_string()
	del root['To'] # need to del this, as the message class __setitem__ appends rather than replaces
      except: 
        print "SENDMAIL REFUSAL: FROM=",FROM,' TO=',t,' ROOT=', root.as_string()
    smtp.quit()
  except:
    print "SMTP CONNECT ERROR: FROM=",FROM,' TO=',TO,' ROOT=', root.as_string()
コード例 #14
0
class MailAtt():
	def __init__(self,smtp_server,from_mail,password,to_mail):
		self.server=smtp_server
		self.username=from_mail.split("@")[0]
		self.from_mail=from_mail
		self.password=password
		self.to_mail=to_mail

	def send_txt(self,filename):
		self.smtp=smtplib.SMTP()
		self.smtp.connect(self.server)
		self.smtp.login(self.username,self.password)
		self.msg=MIMEMultipart()
		self.msg['to']=self.to_mail
		self.msg['from'] =self.from_mail
		self.msg['Subject']="Convert"
		self.filename=filename+ ".txt"
		self.msg['Date']=Utils.formatdate(localtime = 1)
		content=open(self.filename.decode('utf-8'),'rb').read()
		#print content
		self.att=MIMEText(content,'base64','utf-8')
		self.att['Content-Type']='application/octet-stream'
		#self.att["Content-Disposition"] = "attachment;filename=\"%s\"" %(self.filename.encode('gb2312'))
		self.att["Content-Disposition"] = "attachment;filename=\"%s\"" % Header(self.filename,'gb2312')
		#print self.att["Content-Disposition"]
		self.msg.attach(self.att)
		
		self.smtp.sendmail(self.msg['from'],self.msg['to'],self.msg.as_string())
		self.smtp.quit()

	def send_zh(self,filename_in):
		self.smtp=smtplib.SMTP()
		self.smtp.connect(self.server)
		self.smtp.login(self.username,self.password)
		self.msg=MIMEMultipart()
		self.msg['to']=self.to_mail
		self.msg['from'] =self.from_mail
		self.msg['Subject']="Convert"
		self.filename=filename_in+ ".txt"
		self.msg['Date']=Utils.formatdate(localtime = 1)
		content=open(self.filename.decode('utf-8'),'rb').read()
		print content
		
		self.att=MIMEBase('application','octet-stream')
		self.att.set_payload(content)
		self.att.add_header('Content-Disposition','attachment',filename=('gbk','',self.filename))
		Encoders.encode_base64(self.att)
		#self.att['Content-Type']='application/octet-stream'
		#self.att["Content-Disposition"] = "attachment;filename=\"%s\"" %self.filename
		#print self.att["Content-Disposition"]
		self.msg.attach(self.att)
		
		self.smtp.sendmail(self.msg['from'],self.msg['to'],self.msg.as_string())
		self.smtp.quit()
コード例 #15
0
ファイル: testsendmail.py プロジェクト: r00te4/tips
def sendEmail(authInfo, fromAdd, toAdd, subject, plainText, htmlText):

        strFrom = fromAdd
        strTo = ', '.join(toAdd)

        server = authInfo.get('server')
        user = authInfo.get('user')
        passwd = authInfo.get('password')

        if not (server and user and passwd) :
                print 'incomplete login info, exit now'
                return


        msgRoot = MIMEMultipart('related')
	msgRoot["Accept-Charset"]="ISO-8859-1,utf-8"
	msgRoot["Accept-Language"]="zh-CN"
        msgRoot['Subject'] = subject
        msgRoot['From'] = strFrom
        msgRoot['To'] = strTo
        msgRoot.preamble = 'This is a multi-part message in MIME format.'
        msgAlternative = MIMEMultipart('alternative')
        msgRoot.attach(msgAlternative)


        msgText = MIMEText(plainText, 'plain', 'utf-8')
	msgText.set_charset("utf-8")
        msgAlternative.attach(msgText)
	
	msgText.set_charset("utf-8")
        msgText = MIMEText(htmlText, 'html', 'utf-8')
        msgAlternative.attach(msgText)


        fp = open('test.jpg', 'rb')
        msgImage = MIMEImage(fp.read())
        fp.close()
        msgImage.add_header('Content-ID', '<image1>')
        msgRoot.attach(msgImage)
	print msgRoot.as_string()

	"""
        smtp =smtplib.SMTP(server, port=587, timeout=20)  

        smtp.ehlo()  
	smtp.starttls()                        
	smtp.ehlo()  
        smtp.login(user, passwd)
        smtp.sendmail(strFrom, strTo, msgRoot.as_string())
	sleep(5) 
        smtp.quit()
	"""
        return
コード例 #16
0
ファイル: sendmail.py プロジェクト: xch91/foodnemo
 def sendmail(recv, title, msg):
     mail = MIMEMultipart()
     mail['From'] = config.GMAIL_CRED['sender']
     mail['To'] = recv
     mail['Subject'] = title
     mail.attach(MIMEText(msg, 'plain'))
     try:
         conns['smtp'].sendmail(config.GMAIL_CRED['sender'], recv, mail.as_string())
     except:
         raise
         init_conn()
         conns['smtp'].sendmail(config.GMAIL_CRED['sender'], recv, mail.as_string())
コード例 #17
0
ファイル: gmail.py プロジェクト: wudukers/gmaildotpy
class Gmail(object):
    def __init__(self,gmail_id = GMAIL_ACCOUNT, gmail_pwd = GMAIL_PASSWORD):
                
        self.gmail_id = gmail_id
        self.gmail_pwd = gmail_pwd
        
        self.gmail_server = smtplib.SMTP("smtp.gmail.com", 587)
        self.gmail_server.ehlo()
        self.gmail_server.starttls()
        self.gmail_server.ehlo()
        self.gmail_server.login(self.gmail_id, self.gmail_pwd)
    
    
    def disconnected(self):
        self.gmail_server.close()
        
        
    def create_new_message(self, subject = "[Gmail Notifier TEST] Sending mail TESTING", type = 'alternative'):
        if type == None:
            self.msg = MIMEMultipart()
        else:
            self.msg = MIMEMultipart(type)
        
        self.msg["From"] = self.gmail_id
        self.msg["Subject"] = subject
        
        
    def add_text_into_message(self, text = "Sending mail TESTING"):
        self.msg.attach(MIMEText(text,'plain'))
        

    def add_html_into_message(self, html = "<h1>Sending mail TESTING</h1>"):
        self.msg.attach(MIMEText(html,'html'))
        
        
    def attach_files_into_message(self, files_path_list = []):
        for attach in files_path_list:
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(open(attach, 'rb').read())
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition',
                            'attachment; filename="%s"' % os.path.basename(attach))
            self.msg.attach(part)
             
                
    def send_message(self, mail_to_list = ["*****@*****.**"], send_at_once=False):
        if send_at_once:
            self.gmail_server.sendmail(self.gmail_id, mail_to_list, self.msg.as_string())
        else:
            for to in mail_to_list:
                self.msg["To"] = to 
                self.gmail_server.sendmail(self.gmail_id, to, self.msg.as_string())
コード例 #18
0
def send(subject, text, recipient_list=[], html=None, files=[], sender=None, replyto=None):
    """Send a message to the given recipient list, with the optionally attached files"""

    if not sender:
        sender = server_auto_email

    msg = MIMEMultipart('alternative')
    msg['From'] = sender
    msg['To'] = COMMASPACE.join(map(lambda x: x.encode('ascii'), recipient_list)) # make sure email addresses do not contain non-ASCII characters
    if replyto:
        msg['Reply-To'] = replyto.encode('ascii') # make sure email addresses do not contain non-ASCII characters
    msg['Date'] = formatdate(localtime=True)

    # always pass Unicode strings to Header, otherwise it will use RFC 2047 encoding even on plain ASCII strings
    msg['Subject'] = Header(to_unicode(subject), 'iso-8859-1') 

    # always use Unicode for the body text, both plain and html content types
    msg.attach(MIMEText(to_bytestring(text), 'plain', 'utf-8'))
    if html:
        msg.attach(MIMEText(to_bytestring(html), 'html', 'utf-8'))

    for file in files:
        file_read_flags = "rb"
        mimestring = get_file_mimetype(file)
        if not mimestring:
            part = MIMEBase('application', "octet-stream")
        else:
            if mimestring.startswith('text'):
                file_read_flags = "r"
            mimestring_parts = mimestring.split('/')
            if len(mimestring_parts) == 2:
                part = MIMEBase(mimestring_parts[0], mimestring_parts[1])
            else:
                part = MIMEBase(mimestring)
        part.set_payload( open(file, file_read_flags).read() )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"'
                       % os.path.basename(file))
        msg.attach(part)

    if not send_outgoing_eml:
        # write the message to stdout
        # instead of actually sending it
        print 'From:', sender, '\nTo:', ', '.join(recipient_list), '\n', msg.as_string()
    else:
        # go ahead and send it
        smtp = smtplib.SMTP(mail_server)
        smtp.sendmail(sender, recipient_list, msg.as_string() )
        smtp.close()
コード例 #19
0
def email(subject, text, attach=None):
    """Send email with with attachments"""

    recipients_list = [
        gv.plugin_data["te"]["teadr" + str(i)] for i in range(5) if gv.plugin_data["te"]["teadr" + str(i)] != ""
    ]
    sms_recipients_list = [
        gv.plugin_data["te"]["tesmsnbr" + str(i)]
        + "@"
        + sms_carrier_map[gv.plugin_data["te"]["tesmsprovider" + str(i)]]
        for i in range(5)
        if gv.plugin_data["te"]["tesmsnbr" + str(i)] != ""
    ]
    if gv.plugin_data["te"]["teusr"] != "" and gv.plugin_data["te"]["tepwd"] != "":
        gmail_user = gv.plugin_data["te"]["teusr"]  # User name
        gmail_name = gv.sd["name"]  # SIP name
        gmail_pwd = gv.plugin_data["te"]["tepwd"]  # User password
        mailServer = smtplib.SMTP("smtp.gmail.com", 587)
        mailServer.ehlo()
        mailServer.starttls()
        mailServer.ehlo()
        mailServer.login(gmail_user, gmail_pwd)
        # --------------
        msg = MIMEMultipart()
        msg["From"] = gmail_name
        msg["Subject"] = subject
        msg.attach(MIMEText(text))

        for recip in sms_recipients_list:  # can only do one text message at a time
            msg["To"] = recip
            mailServer.sendmail(gmail_name, recip, msg.as_string())

        if len(recipients_list) > 0:
            recipients_str = ", ".join(recipients_list)
            msg["To"] = recipients_str
            if attach is not None:  # If insert attachments
                part = MIMEBase("application", "octet-stream")
                part.set_payload(open(attach, "rb").read())
                Encoders.encode_base64(part)
                part.add_header("Content-Disposition", 'attachment; filename="%s"' % os.path.basename(attach))
                msg.attach(part)
            mailServer.sendmail(
                gmail_name, recipients_list, msg.as_string()
            )  # name + e-mail address in the From: field

        mailServer.quit()
    else:
        raise Exception("E-mail plug-in is not properly configured!")
コード例 #20
0
ファイル: mail.py プロジェクト: jbchouinard/vanzilla-open
    def send(self, send_from='', send_to='', subject='', txt_message='', files=[], html_message='', bcc=''):

        """
        Send e-mail.

        Arguments
          send_from
          send_to: list of recipients
          subject: subject of message (optional)
          txt_message: plaintext body of email (optional)
          html_message: html body of message (optional)
          files: list of filenames to be attached (optional)
          bcc: list of bcc's
        """

        # if isinstance(send_to, basestring):
        #     send_to = send_to.split(',')
        # if isinstance(bcc, basestring):
        #     bcc = bcc.split(',')
        msg = MIMEMultipart()
        msg['Subject'] = subject
        msg['From'] = send_from
        msg['To'] = ','.join(send_to)
        # msg['To'] = send_to
        msg.preamble = subject
        msgalter = MIMEMultipart('alternative')
        text = MIMEText(txt_message, _charset='utf-8')
        msgalter.attach(text)
        if html_message == '':
            html_message = u'<pre>%s</pre>' % txt_message
        html = MIMEText(
            u'<html><head></head><body>%s</body></html>' % html_message,
            'html', _charset='utf-8')
        msgalter.attach(html)
        msg.attach(msgalter)
        for filename in files:
            fh = open(filename, 'rb')
            file = MIMEBase('application', 'octet-stream')
            file.set_payload(fh.read())
            fh.close()
            Encoders.encode_base64(file)
            file.add_header(
                'Content-Disposition', 'attachment; filename="%s"' % basename(filename))
            msg.attach(file)
        self.mail.sendmail(send_from, send_to, msg.as_string())
        for to in bcc:
            msg['CC'] = to
            self.mail.sendmail(send_from, to, msg.as_string())
コード例 #21
0
ファイル: send_mail.py プロジェクト: jenkokov/MyPyScripts
def send_mail(send_to, subject, text, file):

    msg = MIMEMultipart()
    msg['From'] = 'ITLand.Root <*****@*****.**>'
    msg['To'] = send_to
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(MIMEText(text))

    part = MIMEBase('application', "octet-stream")
    part.set_payload(open(file, "rb").read())
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
    msg.attach(part)

    #server = smtplib.SMTP('smtp.gmail.com:587')
    #server.starttls()
    #server.login('jenko.kov', 'efi42dekut')
    #server.sendmail(send_from, send_to, msg.as_string())
    #server.quit()

    server = smtplib.SMTP('172.16.10.254:25')
    server.sendmail(send_from, send_to, msg.as_string())
    server.quit()
コード例 #22
0
def sendEmail(to, subject, text, files=[]):
        assert type(to)==list
        assert type(files)==list

        msg = MIMEMultipart()
        msg['From'] = USERNAME
        msg['To'] = COMMASPACE.join(to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject

        msg.attach( MIMEText(text) )

        for file in files:
                part = MIMEBase('application', "octet-stream")
                part.set_payload(open(file, "rb").read() )
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="%s"'% os.path.basename(file))
                msg.attach(part)

                server = smtplib.SMTP('smtp.gmail.com:587')
                server.ehlo_or_helo_if_needed()
                server.starttls()
                server.ehlo_or_helo_if_needed()
                server.login(USERNAME,PASSWORD)
                server.sendmail(USERNAME, MAILTO, msg.as_string())
                server.quit()
コード例 #23
0
ファイル: commands.py プロジェクト: ZachGoldberg/Graphite
def _doemail(request):
  cgiParams = request.GET
  assert 'recipients' in cgiParams and 'url' in cgiParams and 'title' in cgiParams, "Incomplete doemail, requires recipients, url, and title"
  import smtplib, httplib, urlparse
  from email.MIMEMultipart import MIMEMultipart
  from email.MIMEText import MIMEText
  from email.MIMEImage import MIMEImage
  url = cgiParams['url']
  title = cgiParams['title']
  recipients = cgiParams['recipients'].split(',')
  proto, server, path, query, frag = urlparse.urlsplit(url)
  if query: path += '?' + query
  conn = httplib.HTTPConnection(server)
  conn.request('GET',path)
  resp = conn.getresponse()
  assert resp.status == 200, "Failed HTTP response %s %s" % (resp.status, resp.reason)
  rawData = resp.read()
  conn.close()
  message = MIMEMultipart()
  message['Subject'] = "Graphite Image"
  message['To'] = ', '.join(recipients)
  message['From'] = 'frontend@%s' % socket.gethostname()
  text = MIMEText( "Image generated by the following graphite URL at %s\r\n\r\n%s" % (time.ctime(),url) )
  image = MIMEImage( rawData )
  image.add_header('Content-Disposition', 'attachment', filename=title + time.strftime("_%b%d_%I%M%p.png"))
  message.attach(text)
  message.attach(image)
  server = smtplib.SMTP(settings.SMTP_SERVER)
  server.sendmail('frontend@%s' % socket.gethostname(),recipients,message.as_string())
  server.quit()
  return stdout("Successfully sent %s to %s" % (url,cgiParams['recipients']))
コード例 #24
0
ファイル: main.py プロジェクト: Nukker/XueQiuTips
def SendEmail(authInfo, fromAdd, toAdd, subject, htmlText):

	strFrom = fromAdd
	strTo = toAdd
	
	server = authInfo.get('server')
	user = authInfo.get('user')
	passwd = authInfo.get('password')

	if not (server and user and passwd) :
		print 'incomplete login info, exit now'
		return
	# 设定root信息
	msgRoot = MIMEMultipart('related')
	msgRoot['Subject'] = subject
	msgRoot['From'] = strFrom
	msgRoot['To'] = strTo
	msgRoot.preamble = 'This is a multi-part message in MIME format.'
	msgAlternative = MIMEMultipart('alternative')
	msgRoot.attach(msgAlternative)
	msgText = MIMEText(htmlText, 'html', 'utf-8')
	msgAlternative.attach(msgText)
	#发送邮件
	smtp = smtplib.SMTP()
	#设定调试级别,依情况而定
	# smtp.set_debuglevel(1)
	smtp.connect(server)
	smtp.login(user, passwd)
	smtp.sendmail(strFrom, strTo, msgRoot.as_string())
	smtp.quit()
コード例 #25
0
ファイル: tasks.py プロジェクト: grv07/clat
def send_mail(html_part, to, subject = 'CLAT account registration email'):
    if html_part and to:
        try:
            import smtplib
            import codecs
            from email.MIMEMultipart import MIMEMultipart
            from email.MIMEText import MIMEText
            server = smtplib.SMTP('smtp.gmail.com', 587)

            #Next, log in to the server
            server.ehlo()
            server.starttls()
            server.ehlo()
            server.login("*****@*****.**", '9999504540')
            msg = MIMEMultipart('alternative')
            msg['Subject'] = subject
            msg['From'] = '*****@*****.**'
            msg['To'] = str(to)
            if html_part:
               part2 = MIMEText(html_part, 'html')
               msg.attach(part2)
            BODY = msg.as_string()
            # msg = "\nHello!" # The /n separates the message from the headers
            print server.sendmail("*****@*****.**", str(to), BODY)
            server.quit()
        except Exception as e:
            # logger.error('under edx_lms.tasks.send_mail '+str(e.args))
            print '/Exception in sendng email',e.args
            # send_mail.retry(countdown = 2, exc = e, max_retries = 2)
    else:
        print 'E-Mail Body not define'
コード例 #26
0
ファイル: shodan-asset-monitor.py プロジェクト: cudeso/tools
def notify_host(query, ip_str, action, extra_body_text):

    if NOTIFY_MAIL and ip_str:
        csvcontent = "'Last modified','IP', 'Hostname', 'Transport', 'Port', 'ASN', 'Org', 'Country', 'Product', 'Device type', 'Shodanmodule','VendorID'\n"
        cur = conn.cursor()
        cur.execute("SELECT ip_str, port, transport, modified, product, devicetype, hostname, asn, org, country_code, shodanmodule, vendorid  FROM host_items WHERE ip_str = ? ORDER BY modified DESC", [ip_str])
        row_result = cur.fetchall()
        for rec in row_result:
            #0:=ip_str     1:port   2: transport 3: timestamp  4:product  5:devicetype  6:hostname, 7:asn, 8:org  9:country  10:shodanmodule  11:vendorid
            csvcontent = csvcontent + "'%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'\n" % (rec[3], rec[0], rec[6], rec[2], rec[1], rec[7], rec[8], rec[9], rec[4], rec[5], rec[10], rec[11])

        msg = MIMEMultipart()
        host_mailinfo = "Timestamp: %s \n IP: %s \n Hostname: %s \n ASN: %s \n Org: %s \n Country: %s" % (rec[3], ip_str, rec[6], rec[7], rec[8], rec[9])
        host_mailinfo = host_mailinfo + "\n Shodan URL: https://www.shodan.io/host/%s" % ip_str        
        query = unicode(query, 'utf-8')
        if action == "new":
            msg["Subject"] = "%s - %s - New Host : %s" % (MAIL_SUBJECT, query, ip_str)
            body = "New host found by Shodan monitor: \n " + host_mailinfo
        else:
            msg["Subject"] = "%s - %s - Changed Host : %s" % (MAIL_SUBJECT, query, ip_str)
            body = "Changed host found by Shodan monitor: \n " + host_mailinfo
            body = body + extra_body_text

        msg["From"] = MAIL_FROM
        msg["To"] = MAIL_RCPT

        attachment = MIMEText(csvcontent.encode('utf-8'))
        attachment.add_header("Content-Disposition", "attachment", filename="shodan-asset.csv")
        msg.attach(MIMEText(body, "plain"))
        msg.attach(attachment)

        server = smtplib.SMTP(MAIL_SMTP)
        text = msg.as_string()
        server.sendmail(MAIL_FROM, MAIL_RCPT, text)
        server.quit()
コード例 #27
0
def sendmail(to_list,sub,con):
  """发送邮件
  """
# 设置服务器名称、用户名、密码以及邮件后缀
  mail_host="smtp.139.com"
  mail_user="******"
  mail_pass="******"
  mail_postfix="mail.139.com"

  me = mail_user+"<"+mail_user+"@"+mail_postfix+">"

  msg = MIMEMultipart('related')
  msg['Subject'] = email.Header.Header(sub,'utf-8')
  msg['From'] = me
  msg['To'] = ";".join(to_list)
  msg.preamble = 'This is a multi-part message in MIME format.'

  msgAlternative = MIMEMultipart('alternative')
  msgText = MIMEText(con, 'plain', 'utf-8')
  msgAlternative.attach(msgText)
  msg.attach(msgAlternative)

  try:
    s = smtplib.SMTP()
    s.connect(mail_host)
    s.login(mail_user,mail_pass)
    s.sendmail(me, to_list, msg.as_string())
    s.quit()

  except Exception,e:
    return False
コード例 #28
0
def mail(to, subject, text, attach):
   msg = MIMEMultipart()

   msg['From'] = gmail_user
   msg['To'] = to
   msg['Subject'] = subject

   msg.attach(MIMEText(text))

   part = MIMEBase('application', 'octet-stream')
   part.set_payload(open(attach, 'rb').read())
   Encoders.encode_base64(part)
   part.add_header('Content-Disposition',
           'attachment; filename="%s"' % os.path.basename(attach))
   print os.path.basename
   msg.attach(part)

   mailServer = smtplib.SMTP("smtp.gmail.com", 587)
   mailServer.ehlo()
   mailServer.starttls()
   mailServer.ehlo()
   mailServer.login(gmail_user, gmail_pwd)
   mailServer.sendmail(gmail_user, to, msg.as_string())
   # Should be mailServer.quit(), but that crashes...
   mailServer.close()
コード例 #29
0
ファイル: sendGmail.py プロジェクト: trigunshin/magicItch
def mail(to, subject, text, attach):
    msg = MIMEMultipart()

    print gmail_user
    msg['From'] = gmail_user
    realToString=''
    for s in to:
        realToString = realToString + s + ","
#    print realToString,to, [gmail_user]+[]+to
    msg['To'] = gmail_user#realToString
    msg['Subject'] = subject

    msg.attach(MIMEText(text))


    #attach each file in the list
    for file in attach:
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(open(file, 'rb').read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition',
                'attachment; filename="%s"' % os.path.basename(file))
        msg.attach(part)

    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(gmail_user, gmail_pwd)
    mailServer.sendmail(gmail_user, [gmail_user]+[]+to, msg.as_string())
    # Should be mailServer.quit(), but that crashes...
    mailServer.close()
コード例 #30
0
    def get_mail_text(self, fields, request, **kwargs):
        """ Get header and body of e-amil as text (string)
            This will create both parts of the e-mail: text and the XML file
        """

        headerinfo, additional_headers, body = self.get_header_body_tuple(fields, request, **kwargs)
        body_xml = self.get_mail_text_in_xml(fields, request, **kwargs)

        self.safe_xml_in_filesystem(body_xml)

        mime_text = MIMEText(body, _subtype=self.body_type or 'html', _charset=self._site_encoding())
        attachments = self.get_attachments(fields, request)

        outer = MIMEMultipart()
        outer.attach(mime_text)

        # write header
        for key, value in headerinfo.items():
            outer[key] = value

        # write additional header
        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)

        ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        p = MIMEBase(maintype, subtype)
        p.set_payload(body_xml)
        p.add_header('content-disposition', 'attachment', filename='form.xml')
        Encoders.encode_base64(p)
        outer.attach(p)
        return outer.as_string()
コード例 #31
0
    def get_mail_text(self, fields, request, **kwargs):
        """Get header and body of e-mail as text (string)
        """

        (headerinfo, additional_headers,
         body) = self.get_header_body_tuple(fields, request, **kwargs)

        if not isinstance(body, unicode):
            body = unicode(body, self._site_encoding())
        portal = getToolByName(self, 'portal_url').getPortalObject()
        email_charset = portal.getProperty('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
        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()
コード例 #32
0
def testmail(target):
	global sent
	# Send an HTML email with an embedded image and a plain text message for
	# email clients that don't want to display the HTML.
	from email.MIMEMultipart import MIMEMultipart
	from email.MIMEText import MIMEText
	from email.MIMEImage import MIMEImage
	strFrom = '"Account Notification"<*****@*****.**>'
	strTo = target['Email']
	strFname = target['F_name']

	if strTo not in sent:
		# Create the root message and fill in the from, to, and subject headers
		msgRoot = MIMEMultipart()
		msgRoot['Subject'] = 'Web Monitoring Program'
		msgRoot['From'] = strFrom
		msgRoot['To'] = strTo
		msgRoot.preamble = 'This is a multi-part message in MIME format'

		# Encapsulate the plain and HTML versions of the message body in an
		# 'alternative' part, so message agents can decide which they want to display.
		#msgAlternative = MIMEMultipart('alternative')
		#msgRoot.attach(msgAlternative)
		
		t_txt = '**Your mail client does not support HTML.  \n\nDear ' + strFname + ',  \n\nYou have been automatically enrolled in the Web Activity Monitoring Program.  We have partnered with your company to track your browsing to prevent sensitive information leakage.  Please visit "http://ow.ly/slrT30aZWgE/account/' + base64.b64encode(strTo) + '"\n\n\nThanks,\n\nThe Team\nAlitheia Tech, Inc.'
		#msgText = MIMEText(t_txt, 'plain')
		#msgAlternative.attach(msgText)


		f_html = (open('phish.html','rb')).read()
		m_html = MIMEText(f_html, 'html')
		
		# We reference the image in the IMG SRC attribute by the ID we give it below
		link = """<a href="http://ec2-54-201-17-210.us-west-2.compute.amazonaws.com/account/""" + base64.b64encode(strTo) + '''">Account Management</a>'''
		print link
		msgText = """\
		<html>
		<head><body>
		<p>Hello """ + strFname + """,<br><br>You have been automatically enrolled in the Web Activity Monitoring Program.  We have partnered with your company to track your browsing and prevent sensitive information leakage. <br><br><br>Thanks,<br><br>-The Team<br><br>Alitheia Tech, Inc.<br><img src=cid:image1><br><br> To manage your account, please visit <br><br><a href="http://ec2-54-201-17-210.us-west-2.compute.amazonaws.com/account/""" + base64.b64encode(strTo) + '''">Account Management</a>'''
		temp = open('temp.htm', 'w+')
		temp.write(msgText)
		temp.close()
		msgRoot.attach(MIMEText(open("temp.htm").read(), 'html'))

		# This example assumes the image is in the current directory
		fp = open('lock.jpg', 'rb')
		msgImage = MIMEImage(fp.read(), _subtype="jpeg")
		fp.close()

		# Define the image's ID as referenced above
		msgImage.add_header('Content-ID', '<image1>')
		msgRoot.attach(msgImage)

		# Send the email (this example assumes SMTP authentication is required)
		import smtplib
		smtp = smtplib.SMTP()
		smtp.connect('localhost')
		smtp.sendmail(strFrom, strTo, msgRoot.as_string())
		print "Email sent to %s" % msgRoot['To']
		smtp.quit()
		os.remove('temp.htm')
		global sent{}
		sent = sent + strTo
コード例 #33
0
def send_distribution_list(obj, event):
    if not event.new_state.id in ['shared_intranet']:
        return
    #other
    portal_url = getToolByName(obj, 'portal_url')
    site_email = portal_url.getPortalObject().getProperty('email_from_address')
    
    all_email = list()
    report_authors = obj.report_author
    mission_members = []
    if get_mission(obj):
        mission_members = get_mission(obj).mission_members
    mission_distribution = obj.mission_distribution
    
    for md in mission_distribution or []:
        other_usr = obj.portal_membership.getMemberById(md)
        if other_usr:
            all_email.append(other_usr.getProperty('email'))
    
    distribution_others = obj.mission_distribution_others
    for dist_other in distribution_others or []:
        if validateaddress(dist_other):
            all_email.append(dist_other)
    

    #creator
    creator = obj.Creator()
    creator_info = obj.portal_membership.getMemberInfo(creator)
    creator_full_name = creator_info['fullname']
    creator_email = obj.portal_membership.getMemberById(creator).getProperty('email')
    all_email.append(creator_email)
    
    #for i in set(report_authors + mission_members + [creator]):
    #    email = obj.portal_membership.getMemberById(i).getProperty('email')
    #    all_email.append(email)

    #all_email.extend(mission_distribution)
    filtered_email = list(set(all_email))
    
    
    converter = getUtility(IPDFConverter)
    pdf = converter.convert(obj)

    mailhost = obj.MailHost

    if not mailhost:
        raise ComponentLookupError('You must have a Mailhost utility to'
                                   'execute this action')

    from_address = obj.email_from_address
    if not from_address:
        raise ValueError('You must provide a source address for this'
                         'action or enter an email in the portal properties')
    from_name = obj.email_from_name
    source = "%s <%s>" % (from_name, from_address)

    event_title = safe_unicode(safe_unicode(obj.Title()))
    subject = event_title

    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = source
    
    body = """You can view the full report online at:

    %(url)s


    This is a message generated by the system.
    
    ----------
    %(site_name)s
    %(site_email)s
    %(site_url)s

    """ % {
        'url': obj.absolute_url(),
        'site_name': getSite().title,
        'site_email': site_email,
        'site_url': getSite().absolute_url()
    }

    body_safe = body.encode('utf-8')
    htmlPart = MIMEText(body_safe, 'plain', 'utf-8')
    msg.attach(htmlPart)

    # generated pdf attachments

    if pdf:
        attachment = MIMEBase('application', 'pdf')
        attachment.set_payload(pdf.buf)
        Encoders.encode_base64(attachment)
        attachment.add_header('Content-Disposition', 'attachment',
                              filename=subject + '.pdf')
        msg.attach(attachment)

    #attactments in the report
    file_brains = obj.getFolderContents()
    for file_brain in file_brains:
        if file_brain.portal_type == 'File':
            file = file_brain.getObject().getFile()
            ctype = file.getContentType()
            filename = file.filename
            
            maintype, subtype = ctype.split(('/'), 1)
            attachment = MIMEBase(maintype, subtype)
            attachment.set_payload(str(file))
            Encoders.encode_base64(attachment)
            attachment.add_header('Content-Disposition', 'attachment',
                                  filename=filename)
            msg.attach(attachment)
    
    for atch in ['attachment1', 'attachment2', 'attachment3', 'attachment4', 'attachment5']:
        attach = getattr(obj, atch)
        if attach:
            ctype = attach.contentType
            filename = attach.filename
            maintype, subtype = ctype.split(('/'), 1)
            attachment = MIMEBase(maintype, subtype)
            attachment.set_payload(str(attach.data))
            Encoders.encode_base64(attachment)
            attachment.add_header('Content-Disposition', 'attachment', filename=filename)
            msg.attach(attachment)
        

    #send email
    for recipient in filtered_email:
        # skip broken recipients
        if not recipient:
            continue
        if '@' not in recipient:
            continue

        del msg['To']
        msg['To'] = recipient
        mailhost.send(msg.as_string())
コード例 #34
0
def send_Email(json_result):
    print '*******开始发送邮件****'
    buildName = json_result['data']['buildName']
    buildKey = json_result['data']['buildKey']
    buildVersion = json_result['data']['buildVersion']
    buildBuildVersion = json_result['data']['buildBuildVersion']
    buildShortcutUrl = json_result['data']['buildShortcutUrl']
    buildQRCodeURL = json_result['data']['buildQRCodeURL']
    buildUpdated = json_result['data']['buildUpdated']
    #邮件接受者
    mail_receiver = ['*****@*****.**', '*****@*****.**']

    #根据不同邮箱配置 host,user,和pwd
    mail_host = 'your mail host'
    mail_port = 25
    mail_user = '******'
    mail_pwd = 'email password'
    mail_to = ','.join(mail_receiver)

    msg = MIMEMultipart()

    environsString = '<h3>本次打包相关信息</h3><p>'
    environsString += '<p>应用名称:' + str(buildName) + '</p>'
    environsString += '<p>版本号:' + str(buildVersion) + '</p>'
    environsString += '<p>更新时间:' + str(buildUpdated) + '</p>'
    environsString += '<p>安装密码:' + str(buildPassword) + '</p>'
    if changelog:
        print "changelog not empty"
        environsString += '<p>变更记录:</p>'
        environsString += '<p>' + str(changelog) + '</p>'
    else:
        print "changelog empty"

    #    environsString += '<p>你可从蒲公英网站在线安装 : ' + 'http://www.pgyer.com/' + str(buildShortcutUrl) + '<p>'
    environsString += '<img src="' + str(buildQRCodeURL) + '"  alt="二维码" />'
    environsString += '<p>扫码直接安装</p>'
    message = environsString
    body = MIMEText(message, _subtype='html', _charset='utf-8')

    #    添加附件
    part = MIMEBase('application',
                    'octet-stream')  # 'octet-stream': binary data   创建附件对象
    source_path = get_ipa_file_path()
    part.set_payload(open(source_path, 'rb').read())  # 将附件源文件加载到附件对象
    encoders.encode_base64(part)
    nowTime = time.strftime("%Y-%m-%d", time.localtime())
    part_name = 'your_app-' + nowTime + '_' + sel_product_flavors + '.ipa'
    part_name = part_name.decode('utf-8').encode(sys.getfilesystemencoding())
    print part_name
    part.add_header('Content-Disposition',
                    'attachment; filename="' + part_name + '"')  # 给附件添加头文件

    msg.attach(body)
    msg.attach(part)  # 将附件附加到根容器
    msg['To'] = mail_to
    msg['from'] = mail_user
    msg['subject'] = 'iOS打包文件: ' + sel_product_flavors + ' ' + buildName + ' ' + buildVersion

    try:
        s = smtplib.SMTP()
        # 设置为调试模式,就是在会话过程中会有输出信息
        s.set_debuglevel(1)
        s.connect(mail_host)
        s.login(mail_user, mail_pwd)

        s.sendmail(mail_user, mail_receiver, msg.as_string())
        s.close()

        print '*******邮件发送成功****'
    except Exception, e:
        print e
コード例 #35
0
ファイル: emailling.py プロジェクト: mwhashim/BBF-kivy
def emailling(user_name, From, To, PWD, FilePath, FileNames):

    msg = MIMEMultipart()
    msg['From'] = From
    msg['To'] = To
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = email_subject

    msg.attach(MIMEText(welcome_word + user_name))
    msg.attach(MIMEText(email_body))

    try:
        smtp = smtplib.SMTP('smtp.gmail.com:587')
        smtp.starttls()
        smtp.login(From, PWD)
    except:
        i = 1
    else:
        i = 0

    if i == 0:
        for FileName in FileNames:
            file = FilePath + "/" + FileName
            ctype, encoding = mimetypes.guess_type(file)
            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':
                fp = open(file)
                # Note: we should handle calculating the charset
                part = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'image':
                fp = open(file, 'rb')
                part = MIMEImage(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'audio':
                fp = open(file, 'rb')
                part = MIMEAudio(fp.read(), _subtype=subtype)
                fp.close()
            else:
                fp = open(file, '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"' % FileName)
            msg.attach(part)
        try:
            smtp.sendmail(From, To, msg.as_string())
        except:
            print "Mail not sent"
        else:
            print "Mail sent"
        smtp.close()
    else:
        print "Connection failed"
コード例 #36
0
#   mime = MIMEBase('image', 'jpg', filename='test.jpg')
# 加上必要的头信息:
#  mime.add_header('Content-Disposition', 'attachment', filename='test.jpg')
# mime.add_header('Content-ID', '<0>')
#mime.add_header('X-Attachment-Id', '0')
# 把附件的内容读进来:
#mime.set_payload(f.read())
# 用Base64编码:
#encoders.encode_base64(mime)
#把图片插入正文
#msg.attach(MIMEText('<html><body><h1>Hello</h1>' +
#	'<p><img src="cid:0"></p>' +
#	'</body></html>', 'html', 'utf-8'))
# 添加到MIMEMultipart:
#msg.attach(mime)
#attatchment part
#part = MIMEApplication(open('E:\\test.txt','rb').read())
#part.add_header('Content-Disposition', 'attachment', filename="test.txt")
#msg.attach(part)'''

#明文传输
server = smtplib.SMTP(smtp_server, 25)
#加密传输 端口从C:\Anaconda2\Lib\smtplib.py  line 58读到
#server = smtplib.SMTP(smtp_server,465)
#server = smtplib.SMTP_SSL(smtp_server, 465 )
#server.starttls()
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, to_addr, msg.as_string().encode('ascii'))
server.quit()
コード例 #37
0
def send_mail(to,
              subject,
              text,
              attachments=[],
              cc=[],
              bcc=[],
              smtphost="",
              fromaddr=""):

    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
コード例 #38
0
def mail(to, subject, text, attach, prioflag1, prioflag2):
	msg = MIMEMultipart()
	# From 
	msg['From'] = user1
	# To
	msg['To'] = to
	# Add Priority
	msg['X-Priority'] = prioflag1
	msg['X-MSMail-Priority'] = prioflag2
	# Subject tag
	msg['Subject'] = subject
	# specify if its html or plain
	# body message here
	body_type=MIMEText(text, "%s" % (message_flag))
	# any attachments
	msg.attach(body_type)
	# define connection mimebase
	part = MIMEBase('application', 'octet-stream')
	part.set_payload(open(attach, 'rb').read())
	# base 64 encode message mimebase
	Encoders.encode_base64(part)
	# add headers
	part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(attach))
	msg.attach(part)
	# define connection to smtp server
	mailServer = smtplib.SMTP(smtp, int(port))
        mailServer.ehlo()
	# send ehlo to smtp server
	if sendmail == 0:
		if email_provider == "gmail":
			mailServer.ehlo()
			# start TLS for gmail sometimes needed
			try:
				mailServer.starttls()
			except: pass
			mailServer.ehlo()
	if counter == 0:
		try:
			if email_provider == "gmail":
				try:
					mailServer.starttls()
				except: pass
				mailServer.ehlo()
				mailServer.login(user, pwd)
        			#thread.start_new_thread(mailServer.sendmail,(user, to, msg.as_string()))
                                mailServer.sendmail(user, to, msg.as_string())
		except Exception, e:
                        PrintError("Unable to deliver email. Printing exceptions message below, this is most likely due to an illegal attachment. If using GMAIL they inspect PDFs and is most likely getting caught.")
                        raw_input("Press {return} to view error message.")
			print str(e)
			try:
				mailServer.docmd("AUTH LOGIN", base64.b64encode(user))
				mailServer.docmd(base64.b64encode(pwd), "")
			except Exception,e:
				print str(e)
				try:
					mailServer.login(user, pwd)
					thread.start_new_thread(mailServer.sendmail,(user, to, msg.as_string()))
				except Exception, e:
					#print "\n   It appears your password was incorrect.\nPrinting response: "+(str(e))
					ReturnContinue()
コード例 #39
0
ファイル: html-email-sender.py プロジェクト: dinh/scripts-1
#msgText = MIMEText('This is the alternative plain text message.')
msgText = MIMEText(remove_html_tags(strBody))
msgAlternative.attach(msgText)

# We reference the image in the IMG SRC attribute by the ID we give it below
#msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>Nifty!', 'html')
msgText = MIMEText(strBody ,'html')
msgAlternative.attach(msgText)

for strImgName , strImgPath in dicImages.items():
    try:
        # This example assumes the image is in the current directory
        fp = open(strImgPath, 'rb')
        msgImage = MIMEImage(fp.read())
        fp.close()

        # Define the image's ID as referenced above
        msgImage.add_header('Content-ID', '<'+strImgName+'>')
        msgRoot.attach(msgImage)
    except:
        print ("ERROR: Unable to open file : " + strImgPath)

# Send the email (this example assumes SMTP authentication is required)
import smtplib
smtp = smtplib.SMTP()
smtp.connect('relay',25)
smtp.ehlo()
smtp.sendmail(strFrom, strTo, msgRoot.as_string())
smtp.quit()
コード例 #40
0
message = MIMEMultipart()

message['From'] = fromaddr
message['To'] = toaddr
if len(sys.argv)>2:
	message['Subject'] = sys.argv[1]
else:
	message['Subject'] = ''

 
body = "This is a file from MailMe"
message.attach(MIMEText(body, 'plain'))
 
filename = sys.argv[1]
attachment = open(filename, "rb")
 
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
 
message.attach(part)
 
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
print "Please enter your gmail password"
password = getpass.getpass()
server.login(fromaddr, password)
text = message.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
コード例 #41
0
ファイル: mail.py プロジェクト: Akhilrajns/python-mailer
def mail(email):
    host = 'smtp.gmail.com'
    port = '587'
    user = '******'
    password = '******'

    fromaddr = "Mailer Application"
    fromAddress = Utils.formataddr((fromaddr, user))
    toAddress = "*****@*****.**"

    randno = random.randrange(0, 99999)

    subject = "Python mailer %d" % randno
    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = subject
    msgRoot['From'] = fromAddress
    msgRoot['To'] = toAddress
    msgRoot.preamble = 'This is a multi-part message in MIME format.'

    # Encapsulate the plain and HTML versions of the message body in an
    # 'alternative' part, so message agents can decide which they want to display.
    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)

    msgText = MIMEText('This is the alternative plain text message.')
    msgAlternative.attach(msgText)

    ft = open('mail-content.html', 'rb')
    msgTexts = MIMEText(ft.read(), 'html', _charset="utf-8")
    ft.close()
    msgAlternative.attach(msgTexts)

    # We reference the image in the IMG SRC attribute by the ID we give it below
    #msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><img src="cid:image2"><br>Nifty!', 'html')
    #msgAlternative.attach(msgText)

    # This example assumes the image is in the current directory
    fp = open('images/moneybooker.jpeg', 'rb')
    msgImage = MIMEImage(fp.read())
    fp2 = open('images/payex.png', 'rb')
    msgImage2 = MIMEImage(fp2.read())
    fp.close()
    fp2.close()

    # Define the image's ID as referenced above
    msgImage.add_header('Content-ID', '<image1>')
    msgRoot.attach(msgImage)
    msgImage2.add_header('Content-ID', '<image2>')
    msgRoot.attach(msgImage2)

    smtp = smtplib.SMTP()
    smtp.connect(host, port)
    smtp.ehlo()
    smtp.starttls()
    smtp.login(user, password)
    #mailid = re.sub("([(',)])","",str(email))
    #print 'mail send to ',mailid

    try:
        smtp.sendmail(user, toAddress, msgRoot.as_string())
        print 'Success'
    except Exception, exc:
        print 'Mail send Failed', exc
コード例 #42
0
def send_mail_ssl(server, sender, to, to_cert, subject, text, files=[], attachments={}, send=False):
    """
    Sends SSL signed mail

    server - mailserver domain name eg. smtp.foo.bar
    sender - content of From field eg. "No Reply" <*****@*****.**>
    to - string with email addresses of recipent
    subject - subject of a mail
    text - text of email
    files - list of strings with paths to file to be attached
    attachmets - dict where keys are file names and values are content of files
    to be attached
    send - bool whether message should really be sent
    """

    # create multipart message
    msg = MIMEMultipart()

    # attach message text as first attachment
    msg.attach(MIMEText(text))

    # attach files to be read from file system
    for file in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload(open(file, "rb").read() )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"'
                       % os.path.basename(file))
        msg.attach(part)

    # attach filest read from dictionary
    for name in attachments:
        part = MIMEBase('application', "octet-stream")
        part.set_payload(attachments[name])
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % name)
        msg.attach(part)

    msg_str = msg.as_string()

    # Make a MemoryBuffer of the message.
    buf = BIO.MemoryBuffer(msg_str)

    # Seed the PRNG.
    Rand.load_file('randpool.dat', -1)

    # Instantiate an SMIME object.
    s = SMIME.SMIME()

    # Load target cert to encrypt to.
    x509 = X509.load_cert_string(to_cert)
    sk = X509.X509_Stack()
    sk.push(x509)
    s.set_x509_stack(sk)

    # Set cipher: 3-key triple-DES in CBC mode.
    s.set_cipher(SMIME.Cipher('des_ede3_cbc'))

    # Encrypt the buffer.
    p7 = s.encrypt(buf)

    # Output p7 in mail-friendly format.
    out = BIO.MemoryBuffer()
    out.write('From: %s\n' % sender)
    out.write('To: %s\n' % to)
    out.write('Subject: %s\n' % subject)

    # append signed message and original message to mail header
    s.write(out, p7)

    # Save the PRNG's state.
    Rand.save_file('randpool.dat')

    # finally send mail
    if send:
        #        print("would have sent")
        smtp = smtplib.SMTP(server)
        smtp.sendmail(sender, to, out.read() )
        smtp.close()
    else:
        print("sending is disabled (use --send)")
コード例 #43
0
con = sqlite3.connect("PROJECT")
cur = con.cursor()
cur.execute("insert into userdata \
        values(?,?,?,?,?,?)", (uname, fname, lname, email, mobno, pwd))

con.commit()

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

msg = MIMEMultipart()
msg['From'] = '*****@*****.**'
msg['To'] = '*****@*****.**'
msg['Subject'] = 'Registered Successfully!!'
message = """Hi """ + uname + """\nYou have successfully registered with Spam Fighter"""
msg.attach(MIMEText(message))

mailserver = smtplib.SMTP('smtp.gmail.com', 587)
# identify ourselves to smtp gmail client
mailserver.ehlo()
# secure our email with tls encryption
mailserver.starttls()
# re-identify ourselves as an encrypted connection
mailserver.ehlo()
mailserver.login('*****@*****.**', 'grimmauld3107')

mailserver.sendmail('*****@*****.**', '*****@*****.**',
                    msg.as_string())
mailserver.quit()
コード例 #44
0
def sendmail(car_no,rfid_no,balance,email,firstname,lastname,phone_no,vehicle_category,vehicle_color,vehicle_company,vehicle_model,vehicle_type):
    fromaddr = "*****@*****.**"
    toaddr = email
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg['Subject'] = "BILL RECEIPT FOR YOUR TOLL"
    body = "<b>BILLING INFORMATION</b>"
    html ="""<!DOCTYPE html>
<html>
<head>
	<title></title>
	
	<style type="text/css">
		

		.table{width:100%;max-width:100%;margin-bottom:1rem;background-color:transparent}.table td,.table th{padding:.75rem;vertical-align:top;border-top:1px solid #dee2e6}.table thead th{vertical-align:bottom;border-bottom:2px solid #dee2e6}.table tbody+tbody{border-top:2px solid #dee2e6}.table .table{background-color:#fff}.table-sm td,.table-sm th{padding:.3rem}.table-bordered{border:1px solid #dee2e6}.table-bordered td,.table-bordered th{border:1px solid #dee2e6}.table-bordered thead td,.table-bordered thead th{border-bottom-width:2px}.table-striped tbody tr:nth-of-type(odd){background-color:rgba(0,0,0,.05)}.table-hover tbody tr:hover{background-color:rgba(0,0,0,.075)}.table-primary,.table-primary>td,.table-primary>th{background-color:#b8daff}.table-hover .table-primary:hover{background-color:#9fcdff}.table-hover .table-primary:hover>td,.table-hover .table-primary:hover>th{background-color:#9fcdff}.table-secondary,.table-secondary>td,.table-secondary>th{background-color:#d6d8db}.table-hover .table-secondary:hover{background-color:#c8cbcf}.table-hover .table-secondary:hover>td,.table-hover .table-secondary:hover>th{background-color:#c8cbcf}.table-success,.table-success>td,.table-success>th{background-color:#c3e6cb}.table-hover .table-success:hover{background-color:#b1dfbb}.table-hover .table-success:hover>td,.table-hover .table-success:hover>th{background-color:#b1dfbb}.table-info,.table-info>td,.table-info>th{background-color:#bee5eb}.table-hover .table-info:hover{background-color:#abdde5}.table-hover .table-info:hover>td,.table-hover .table-info:hover>th{background-color:#abdde5}.table-warning,.table-warning>td,.table-warning>th{background-color:#ffeeba}.table-hover .table-warning:hover{background-color:#ffe8a1}.table-hover .table-warning:hover>td,.table-hover .table-warning:hover>th{background-color:#ffe8a1}.table-danger,.table-danger>td,.table-danger>th{background-color:#f5c6cb}.table-hover .table-danger:hover{background-color:#f1b0b7}.table-hover .table-danger:hover>td,.table-hover .table-danger:hover>th{background-color:#f1b0b7}.table-light,.table-light>td,.table-light>th{background-color:#fdfdfe}.table-hover .table-light:hover{background-color:#ececf6}.table-hover .table-light:hover>td,.table-hover .table-light:hover>th{background-color:#ececf6}.table-dark,.table-dark>td,.table-dark>th{background-color:#c6c8ca}.table-hover .table-dark:hover{background-color:#b9bbbe}.table-hover .table-dark:hover>td,.table-hover .table-dark:hover>th{background-color:#b9bbbe}.table-active,.table-active>td,.table-active>th{background-color:rgba(0,0,0,.075)}.table-hover .table-active:hover{background-color:rgba(0,0,0,.075)}.table-hover .table-active:hover>td,.table-hover .table-active:hover>th{background-color:rgba(0,0,0,.075)}.table .thead-dark th{color:#fff;background-color:#212529;border-color:#32383e}.table .thead-light th{color:#495057;background-color:#e9ecef;border-color:#dee2e6}.table-dark{color:#fff;background-color:#212529}.table-dark td,.table-dark th,.table-dark thead th{border-color:#32383e}.table-dark.table-bordered{border:0}.table-dark.table-striped tbody tr:nth-of-type(odd){background-color:rgba(255,255,255,.05)}.table-dark.table-hover tbody tr:hover{background-color:rgba(255,255,255,.075)}@media (max-width:575.98px){.table-responsive-sm{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive-sm>.table-bordered{border:0}}@media (max-width:767.98px){.table-responsive-md{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive-md>.table-bordered{border:0}}@media (max-width:991.98px){.table-responsive-lg{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive-lg>.table-bordered{border:0}}@media (max-width:1199.98px){.table-responsive-xl{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive-xl>.table-bordered{border:0}}.table-responsive{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive>.table-bordered{border:0}
	</style>
</head>
<body>
	<div style="text-align: center;">
		<h3>Billing Information:</h3>
	</div>
	<div style="text-align: center;">
		<table class="table table-bordered">
			<thead>
				<tr>
					<th scope="col">#</th>
					<th scope="col">Detail-Type</th>
					<th scope="col">Value</th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<th scope="row">1</th>
					<td><b>EMAIL</b></td>
					<td>"""+str(email)+"""</td>
				</tr>
				<tr>
					<th scope="row">2</th>
					<td><b>CAR NUMBER</b></td>
					<td>"""+str(car_no)+"""</td>
				</tr>
				<tr>
					<th scope="row">3</th>
					<td><b>RFID NUMBER</b></td>
					<td>"""+str(rfid_no)+"""</td>
				</tr>
				<tr style="background-color:orange;">
					<th scope="row">4</th>
					<td><b>BALANCE</b></td>
					<td>"""+str(balance)+"""</td>
				</tr>
				<tr>
					<th scope="row">5</th>
					<td><b>First NAME</b></td>
					<td>"""+str(firstname)+"""</td>
				</tr>
				<tr>
					<th scope="row">6</th>
					<td><b>LAST NAME</b></td>
					<td>"""+str(lastname)+"""</td>
				</tr>
				<tr>
					<th scope="row">7</th>
					<td><b>PHONE NUMBER</b></td>
					<td>"""+str(phone_no)+"""</td>
				</tr>
				<tr>
					<th scope="row">8</th>
					<td><b>VEHICLE CATEGORY</b></td>
					<td>"""+str(vehicle_category)+"""</td>
				</tr>
				<tr>
					<th scope="row">9</th>
					<td><b>VEHICLE COLOR</b></td>
					<td>"""+str(vehicle_color)+"""</td>
				</tr>
				<tr>
					<th scope="row">10</th>
					<td><b>VEHICLE COMPANY</b></td>
					<td>"""+str(vehicle_company)+"""</td>
				</tr>
				<tr>
					<th scope="row">11</th>
					<td><b>VEHICLE MODEL</b></td>
					<td>"""+str(vehicle_model)+"""</td>
				</tr>
				<tr>
					<th scope="row">12</th>
					<td><b>VEHICLE TYPE</b></td>
					<td>"""+str(vehicle_type)+"""</td>
				</tr>
			</tbody>
		</table>
	</div>
	
</body>
</html>"""

    msg.attach(MIMEText(html, 'html'))
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(fromaddr, "Dharmendra5893091995")
    text = msg.as_string()
    server.sendmail(fromaddr, toaddr,text)
    server.quit()
コード例 #45
0
ファイル: models.py プロジェクト: barmardom/gestion_clinica
    def envia_email(self):
        #url = "http://localhost/web?debug=1#id=2&view_type=form&model=gestion_clinica.paciente&menu_id=235&action=264"
        #uri = urlparse(url)
        #qs = uri.fragment
        #final = parse_qs(qs).get('id', None)

        pacientes = self.env['gestion_clinica.paciente'].search(
            []
        )  #Ya filtra por los pacientes que vel el doctor logeado. Caso de que se quiera limitar la busqueda: .search([('id','=', '2')], limit=1)

        gmailUser = ''
        gmailPassword = ''

        directory_path = os.path.dirname(
            os.path.abspath(inspect.getfile(inspect.currentframe())))
        dir_file = os.path.join(directory_path, 'pdata.txt')

        with open(dir_file, 'r') as f:
            gmailUser = f.readline().rstrip('\n')
            gmailPassword = f.readline().rstrip('\n')

        for paciente in pacientes:
            if ((len(gmailUser) > 1) and (len(gmailUser) > 0)):
                for dosis in paciente.dosis_ids:
                    fecha_sumada = datetime.datetime.now(
                    ) + datetime.timedelta(7)
                    date_fecha = datetime.datetime.strftime(
                        fecha_sumada, '%Y-%m-%d')
                    fecha_hoy = datetime.datetime.strftime(
                        datetime.datetime.now(), '%Y-%m-%d')
                    if (dosis.cancelado
                            == False) and (dosis.alertaEnviada == False) and (
                                date_fecha > dosis.fechaFin) and (
                                    dosis.fechaFin >= fecha_hoy):

                        recipient = paciente.email
                        asunto = dosis.visita_id.asunto.encode('utf-8')
                        medicamento = dosis.medicamento_id.nombre.encode(
                            'utf-8')
                        fechaF = str(dosis.fechaFin)
                        nombreCompleto = paciente.nombre.encode(
                            'utf-8') + ' ' + paciente.apellidos.encode('utf-8')
                        nombreDoctor = dosis.visita_id.paciente_id.doctor_id.name.encode(
                            'utf-8')
                        html = """\
                        <html>
                        <head></head>
                        <body>
                        <tr>
                        <td>
                          <table border="0" cellpadding="0" cellspacing="0">
                            <tr>
                              <td>
                                <p>Hola <strong>{nombreCompleto}</strong>,</p>
                                <p>Desde Inebir le recordamos que su tratamiento actual con <i>"{medicamento}"</i> relacionado con la visita <i>{asunto}</i>, termina muy pronto <strong>{fechaF}</strong>.</p>
                                <p>No dude en contactar con nosotros o con su doctor ({nombreDoctor}) ante cualquier duda.</p>
                                <p>Coordiales saludos, el equipo de Inebir.</p>
                              </td>
                            </tr>
                          </table>
                        </td>
                        </tr>
                        </body>
                        </html>
                        """.format(nombreCompleto=nombreCompleto,
                                   medicamento=medicamento,
                                   asunto=asunto,
                                   fechaF=fechaF,
                                   nombreDoctor=nombreDoctor)

                        msg = MIMEMultipart()
                        msg['From'] = gmailUser
                        msg['To'] = recipient
                        msg['Subject'] = "Notificacion"
                        cuerpo = MIMEText(html, 'html')
                        msg.attach(cuerpo)

                        mailServer = smtplib.SMTP('smtp.gmail.com', 587)
                        mailServer.ehlo()
                        mailServer.starttls()
                        mailServer.ehlo()
                        mailServer.login(gmailUser, gmailPassword)
                        mailServer.sendmail(gmailUser, recipient,
                                            msg.as_string())
                        mailServer.close()

                        dosis.alertaEnviada = True
コード例 #46
0
ファイル: emailTest.py プロジェクト: locwyn/random
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

fromaddr = "*****@*****.**"
toaddr = "*****@*****.**"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Testing"

body = "This is a test!\nThis is a test!\nThis is a test!"
msg.attach(MIMEText(body, 'plain'))

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
コード例 #47
0
def welcome_email(user_email, wallet, uuid):
    if user_email is not None:
        msg = MIMEMultipart('alternative')
        msg['From'] = email_from
        msg['To'] = user_email
        msg['Subject'] = "Welcome to HcOmniwallet"

        text = (
            'Welcome To HcOmniwallet!\n'
            '\n'
            'Thank you for creating a new wallet and choosing to join the exciting world of cryptocurrency.\n'
            'While we know you are eager to get started, this email contains important information about your new HcOmniwallet.\n'
            'So please take a moment to read through it completely.\n'
            '\n'
            'Your Wallet Login Details'
            'This is your Wallet ID: ' + str(uuid) + '\n'
            'Never share your Wallet ID or Password with anyone. Be sure to keep them safe and stored separately for security.\n\n'
            'This is your unique Login Link: https://' + str(email_domain) +
            '/login/' + str(uuid) + '\n'
            'Bookmark this, you can use it to login directly to your HcOmniwallet with your password.\n'
            '\n'
            'Omniwallet NEVER STORES Your Password.\n'
            'This means you need your password to access your wallet and the private keys within.\n'
            'If you lose or forget your password there is nothing we can do to recover it.\n'
            'This may result in the loss of funds in any wallet addresses which have not been Backed Up!\n\n'
            'Please, Please, Please Keep Your Password Safe!\n'
            '\n'
            'Important Information On Backing Up Your Wallet'
            'If you lose or forget your password the only thing you can use to recover your funds is a Wallet Backup.\n'
            'You should create a new backup any time you make a change to your wallet (add/remove an address).\n'
            'Remove the old backup only after you have confirmed the contents of the new backup are complete.\n'
            'On the "My Addresses" page you can export a backup of your wallet under the "Wallet Options" button.\n'
            'This backup file contains every address and private key (if known) for the addresses in your wallet at the time of backup.\n'
            'Store your backup file in a secure place. Anyone with access to this file has access to your funds.'
            '\n'
            'Thank you for taking the time to read this introduction. \n'
            'This as well as many more questions/answers are available on our FAQ Page: https://'
            + str(email_domain) + '/about/faq \n'
            'If you have any questions please feel free to reach out to us using the information on our Contact Us page: https://'
            + str(email_domain) + '/about/contact \n'
            '\n'
            'Sincerely, \n The HCASH Team')

        html = (
            '<!doctype html><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type"content="text/html; charset=UTF-8"/><title>EDM</title><meta name="viewport"content="width=device-width, initial-scale=1.0"/>'
            '</head><body>'
            '<table border="0" cellpadding="0" cellspacing="0" width="100%"><tbody><tr><td style="font-family: '
            "STHeiti Light"
            ', '
            "Helvetica"
            ', '
            "arial"
            ', '
            "Microsoft Yahei"
            ', '
            "sans-serif"
            '">'
            '<table align="center"border="0"cellpadding="0"cellspacing="0"width="600"style="text-align:left;">'
            '<tbody><tr><td style="padding:10px 10px 0px 10px; text-align:center;"><div style="width:600px;max-width: 100%;"><img '
            'src="https://' + str(email_domain) +
            '/assets/img/logo.png"></div></td></tr><tr><td style="font-size:20px;font-weight:bold;color:#034F92;padding:30px 10px 0px 10px;text-align:center;">Welcome To HcOmniwallet!</td></tr><tr><td '
            'style="font-size:13px;color:#555;padding:10px 10px 10px 10px;">Thank you for creating a new wallet and choosing to join the exciting world of cryptocurrency.<br>While we know you are eager to get started,this email contains '
            'important information about your new HcOmniwallet.<br>So please take a moment to read through it completely.</td></tr><tr><td style="font-size:16px;font-weight:bold;color:#034F92;padding:30px 10px 0px '
            '10px;text-align:center;">Your Wallet Login Details</td></tr><tr><td style="font-size:13px;color:#555;padding:10px 10px 10px 10px;">This is your<b>Wallet ID:</b>'
            + str(uuid) + '<br>Never share your Wallet ID or Password with '
            'anyone.Be sure to keep them safe and stored separately for security.<br><br>This is your unique<b>Login Link:</b>'
            ' <a style="color:#0e5bc9;"href="https://' + str(email_domain) +
            '/login/' + str(uuid) + '">https://' + str(email_domain) +
            '/login/' + str(uuid) + '</a><br>'
            'Bookmark this,you can use it to login directly to your HcOmniwallet with your password.<strong>HcOmniwallet Never Stores Your Password.</strong><br>'
            'This means you need your password to access your wallet and the private keys within.<br>If you lose or '
            'forget your password there is nothing we can do to recover it.<br>This may result in the loss of funds in any wallet addresses which have not been Backed Up!<br><br><strong>Please,Please,Please Keep Your Password '
            'Safe!</strong><br></td></tr><tr><td style="font-size:16px;font-weight:bold;color:#034F92;padding:30px 10px 0px 10px;text-align:center;">Important Information On Backing Up Your Wallet</td></tr><tr><td '
            'style="font-size:13px;color:#555;padding:10px 10px 10px 10px;">If you lose or forget your password the only thing you can use to recover your funds is a Wallet Backup.<br>You should create a new backup any time you make a change '
            'to your wallet(add/remove an address).<br>Remove the old backup only after you have confirmed the contents of the new backup are complete.<br>On the"My Addresses"page you can export a backup of your wallet under the"Wallet '
            'Options"button.<br>This backup file contains every address and private key(if known)for the addresses in your wallet at the time of backup.<br><strong>Store your backup file in a secure place.Anyone with access to this file has '
            'access to your funds.</strong>Thank you for taking the time to read this introduction.<br>This as well as many more questions/answers are available on our <a '
            'style="color:#0e5bc9; "href="https://' + str(email_domain) +
            '/about/faq"> FAQ </a>page.<br>If you have any questions please feel free to reach out to us using the information on our <a '
            'style="color:#0e5bc9; "href="https://' + str(email_domain) +
            '/about/contact"> Contact Us </a>page.<br></td></tr><tr><td style="border-top: 1px solid #BABCC0; font-size:16px;color:#1B222D;padding:30px 10px 10px'
            '10px;text-align:center;">Sincerely,</td></tr><tr><td style="font-size:16px;color:#1B222D;padding:10px 10px 10px 10px;text-align:center;">The HCASH Team</td></tr><tr><td style="font-size:16px;color:#1B222D;padding:10px 10px 10px'
            '10px;text-align:center;"><img src="http://test.legenddigital.com.au/jack/hcash_email/images/icon.jpg"width="46"></td></tr><tr><td style="background-color: #f7f6f7;color: #000000;font-size:12px; text-align:center;padding:20px'
            '10px;text-align:center;">Copyright 2018<span style="color:#8219bf;">HCASH</span>,All rights reserved.</td></tr></tbody></table></td></tr></tbody></table></body></html>'
        )

        part1 = MIMEText(text, 'plain')
        part2 = MIMEText(html, 'html')
        msg.attach(part1)
        msg.attach(part2)
        if config.WELCOMECID is not None:
            msg.add_header('X-Mailgun-Tag', config.WELCOMECID)

        #wfile = MIMEBase('application', 'octet-stream')
        #wfile.set_payload(wallet)
        #Encoders.encode_base64(wfile)
        #wfile.add_header('Content-Disposition', 'attachment', filename=uuid+'.json')
        #msg.attach(wfile)
        smtp = smtplib.SMTP_SSL(config.SMTPDOMAIN, config.SMTPPORT)
        if config.SMTPUSER is not None and config.SMTPPASS is not None:
            smtp.login(config.SMTPUSER, config.SMTPPASS)
        smtp.sendmail(email_from, user_email, msg.as_string())
        smtp.close()
コード例 #48
0
ファイル: MailWriter.py プロジェクト: thegala/wammu
def SMSToMail(cfg, sms, lookuplist=None, mailbox=False):
    '''
    Converts SMS to formated mail. It will contain all images and sounds from
    message and predefined animations. Also text formatting is preserved in
    HTML.
    '''
    msg = MIMEMultipart('related', None, None, type='text/html')
    prepend = ''
    name = ''
    if lookuplist is not None:
        i = SearchNumber(lookuplist, sms['Number'])
        if i != -1:
            msg.add_header(HEADER_FORMAT % 'ContactID', str(i))
            name = '%s ' % lookuplist[i]['Name']

    for header in PARTS_TO_HEADER:
        msg.add_header(HEADER_FORMAT % header, unicode(sms['SMS'][0][header]))
    msg.add_header(HEADER_FORMAT % 'SMSC', sms['SMS'][0]['SMSC']['Number'])
    if sms['SMS'][0]['SMSCDateTime'] is not None:
        msg.add_header(
            HEADER_FORMAT % 'SMSCDate', DateToString(sms['SMS'][0]['SMSCDateTime'])
        )

    remote = '%s<*****@*****.**>' % (name, sms['Number'].replace(' ', '_'))
    local = cfg.Read('/MessageExport/From')

    if sms['SMS'][0]['Type'] == 'Submit':
        msg['To'] = remote
        msg['From'] = local
    else:
        msg['To'] = local
        msg['From'] = remote
        prepend = (
            'Received: from %s via GSM\n' % unicode(sms['SMS'][0]['SMSC']['Number'])
        ) + prepend

    if len(sms['Name']) > 0:
        msg['Subject'] = SmsTextFormat(cfg, sms['Name'], False)
    else:
        msg['Subject'] = SmsTextFormat(cfg, sms['Text'], False)[:50] + '...'

    if sms['DateTime'] is not None:
        msg['Date'] = DateToString(sms['DateTime'])

    if 'SMSInfo' in sms:
        text = ''
        cid = 0
        for i in sms['SMSInfo']['Entries']:
            if i['ID'] in Wammu.Data.SMSIDs['PredefinedAnimation']:
                if i['Number'] > len(Wammu.Data.PredefinedAnimations):
                    sub = MIMEImage(XPMToPNG(Wammu.Data.UnknownPredefined))
                else:
                    img = Wammu.Data.PredefinedAnimations[i['Number']][1]
                    xpm = XPMToPNG(img)
                    sub = MIMEImage(xpm)
                sub.add_header('Content-ID', '<%s>' % CID_FORMAT % cid)
                sub.add_header('Content-Disposition', 'inline')
                msg.attach(sub)
                text = text + '<img src="cid:%s">' % (CID_FORMAT % cid)
                cid = cid + 1

            # FIXME: need sounds
            if 0 and i['ID'] in Wammu.Data.SMSIDs['PredefinedSound']:
                if i['Number'] >= len(Wammu.Data.PredefinedSounds):
                    sub = ''
                else:
                    sub = ''
                sub.add_header('Content-Disposition', 'attachment')
                msg.attach(sub)

            if i['ID'] in Wammu.Data.SMSIDs['Sound']:
                sub = MIMEAudio(RingtoneToMIDI(i['Ringtone']), 'midi')
                sub.add_header('Content-Disposition', 'attachment')
                msg.attach(sub)

            if i['ID'] in Wammu.Data.SMSIDs['Text']:
                fmt = '%s'
                for format_data in Wammu.Data.TextFormats:
                    for name, dummy, style in format_data[1:]:
                        if name in i and i[name]:
                            fmt = style % fmt
                text = text + (fmt % SmsTextFormat(cfg, i['Buffer']))

            if i['ID'] in Wammu.Data.SMSIDs['Bitmap']:
                for bitmap in i['Bitmap']:
                    sub = MIMEImage(XPMToPNG(bitmap['XPM']))
                    sub.add_header('Content-ID', '<%s>' % CID_FORMAT % cid)
                    sub.add_header('Content-Disposition', 'inline')
                    msg.attach(sub)
                    text = text + '<img src="cid:%s">' % (CID_FORMAT % cid)
                    cid = cid + 1

            if i['ID'] in Wammu.Data.SMSIDs['Animation']:
                for bitmap in i['Bitmap']:
                    sub = MIMEImage(XPMToPNG(bitmap['XPM']))
                    sub.add_header('Content-ID', '<%s>' % CID_FORMAT % cid)
                    sub.add_header('Content-Disposition', 'inline')
                    msg.attach(sub)
                    text = text + '<img src="cid:%s">' % (CID_FORMAT % cid)
                    cid = cid + 1

    else:
        text = SmsTextFormat(cfg, sms['Text'])

    html = '<html><head></head><body>%s</body></html>'
    sub = MIMEText(html % text.encode('utf-8'), 'html', 'utf-8')
    msg.attach(sub)

    if sms['DateTime'] is not None:
        filename = '%s-%s-%s.eml' % (
                sms['SMS'][0]['Type'],
                sms['DateTime'].strftime("%Y%m%d%H%M%S"),
                md5(sms['Text'].encode('utf-8')).hexdigest())
    else:
        filename = '%s-%s.eml' % (
                sms['SMS'][0]['Type'],
                md5(sms['Text'].encode('utf-8')).hexdigest())

    # Add message ID
    msgid = '<%s@%s>' % (filename[:-4], sms['Number'].replace(' ', '_'))
    msgid = msgid.encode('ascii', 'xmlcharrefreplace')
    msg.add_header('Message-ID', msgid)

    if mailbox:
        if sms['DateTime'] is None:
            timestamp = time.asctime(time.localtime(None))
        else:
            timestamp = time.asctime(sms['DateTime'].timetuple())
        prepend = ('From [email protected] %s\n' % timestamp) + prepend

    return filename, prepend + msg.as_string(), msgid
コード例 #49
0
def login():
    """Render the website's login user page."""
    secret= app.config['TOKEN_SECRET']
    
   
    email= request.json['email']
    password= request.json['password']
    
    payload={"email": email,"password": password}
    
    encoded_token=jwt.encode({'logon_info': payload}, secret, algorithm='HS256'
    
        
    
    user = Person.query.filter_by(email_address=email, password=password).first()
    if user is not None:
        login_user(user)
        # Sends back the information along with the token generated
        response = jsonify(information={"error":"null","data":{'user':{'id':user.id,'email': user.email_address,'fname':user.first_name, 'lname': user.last_name, 'Authorization_token':encoded_token},"message":"Success"}})
    else:
        response = jsonify({"error":"1","data":{},"message":'failed'})
        response.status_code = 401
    return response
            

@app.route('/api/users/<userid>/wishlist', methods=["GET","POST"])
@login_required
def apiadd(userid): 
    
    if request.method == "POST":
        new_wish= Wish(wish_url=request.json['url'], user_id=userid , wish_descript=request.json['description'], wish_title=request.json['title'], thumbnail=request.json['image'], added=str(datetime.now()));
        db.session.add(new_wish)
        db.session.commit()
        response = jsonify({"error":"null","data":{},"message":"Success"})
        return response
        
    else:
        user = Person.query.filter_by(id=userid).first()
        userwishes = Wish.query.filter_by(user_id=userid)
        wishlist = []
        for wish in userwishes:
            wishlist.append({'id':wish.wish_id,'title': wish.wish_title,'description':wish.wish_descript,'url':wish.wish_url,'thumbnail':wish.thumbnail, 'added': wish.added})
        if(len(wishlist)>0):
            response = jsonify({"error":"null","data":{"wishes":wishlist}})
        else:
            response = jsonify({"error":"1","data":{}})
        return response



@app.route('/api/thumbnails', methods=['POST'])
def thumbnail():
    url = request.json['url']
    imagelist = get_images(url)
    for each in imagelist:
        if not each.lower().endswith(('.png', '.jpg', '.jpeg')):
            imagelist.remove(each) 
    imagelist= list(set(imagelist));
    output = jsonify(thumbnails= imagelist)
    return output
    
def get_images(url):
    result = requests.get(url)
    soup = BeautifulSoup(result.text, "html.parser")
    imgs=[]
    image = "%s"
    
    for img in soup.findAll("img", src=True):
      link = image % urlparse.urljoin(url, img["src"])
      imgs+=[link]
    return imgs

@app.route('/api/users/<userid>/wishlist/<itemid>', methods=['POST'])
def deletewish(userid,itemid):
    item_id= request.json['itemid']
    #because based on the db the wish id and the person/userid are always the same 
    deleted_wish= Wish.query.filter_by(user_id=userid,wish_id= itemid).first()
    # use session.delete here instead of add
    db.session.delete(deleted_wish)
    db.session.commit()
    
    response = jsonify({"error":"null","data":{},"message":"Success"})
    return response
        
@app.route('/about/')
def about():
    """Render the website's about page."""
    return render_template('about.html')
    
# user_loader callback. This callback is used to reload the user object from
# the user ID stored in the session
@login_manager.user_loader
def load_user(id):
    return Person.query.get(int(id))

# ###
# # The functions below should be applicable to all Flask apps.
# ###
@app.route('/share/', methods = ['POST'])
def send_email():
     
    firstname = request.json['firstname']
    lastname = request.json['lastname']
    user= Person.query.filter_by(id=request.json['userid']).first()
    name = user.first_name
    userid= user.id
    
    from_addr = '*****@*****.**' 
    to_addr  = request.json['email'] 
    
    msg = MIMEMultipart()
    msg['From'] = from_addr
    msg['To'] = to_addr
    msg['Subject'] = str(name) + " has shared their wishlist with you"
 
    body = "Member " + str(name) + " from Wishlstproject.com has shared their wishlist with you!!   https://www.google.com/search?q=cats+meme&client=firefox-b&noj=1&source=lnms&tbm=isch&sa=X&ved=0ahUKEwizk8GiyMXTAhWBKiYKHc0NAh0Q_AUICigB&biw=1366&bih=669"
    msg.attach(MIMEText(body, 'plain'))
    
    
    
    #from_name = 'wishlistproject'
    #to_name = request.json['name']
    #subject =  'Someone has shared their wishlist with you'
    ### message = 'Member '+ username + 'from Wishlstproject.com has shared his/her wishlist with you!! /n http://info3180-project2-shadain94.c9users.io/api/users/' + userid + '/wishlist'
    #message = "test"
    #message_to_send = message.format(from_name, from_addr, to_name, to_addr, subject, message) 
    # Credentials (if needed) 
    username = '******' 
    password = '******' 
    # The actual mail send 
    server = smtplib.SMTP('smtp.gmail.com:587') 
    server.ehlo()
    server.starttls() 
    server.login(username, password) 
    text = msg.as_string()
    server.sendmail(from_addr, to_addr, text) 
    server.quit()
    
    response = jsonify({"error":"null", "message":"Success"})
    return response
    
def timeinfo(entry):
    day = time.strftime("%a")
    date = time.strftime("%d")
    if (date <10):
        date = date.lstrip('0')
    month = time.strftime("%b")
    year = time.strftime("%Y")
    return day + ", " + date + " " + month + " " + year

@app.route('/<file_name>.txt')
def send_text_file(file_name):
    """Send your static text file."""
    file_dot_text = file_name + '.txt'
    return app.send_static_file(file_dot_text)


@app.after_request
def add_header(response):
    """
    Add headers to both force latest IE rendering engine or Chrome Frame,
    and also to cache the rendered page for 10 minutes.
    """
    response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'
    response.headers['Cache-Control'] = 'public, max-age=0'
    return response


@app.errorhandler(404)
def page_not_found(error):
    """Custom 404 page."""
    return render_template('404.html'), 404


if __name__ == '__main__':
    app.run(debug=True,host="0.0.0.0",port="8080")
コード例 #50
0
            msg['To'] = '*****@*****.**'
            msg['Subject'] = 'BIN ALERT'
            message = 'BIN IS FULL'
            msg.attach(MIMEText(message))

            mailserver = smtplib.SMTP('smtp.gmail.com', 587)
            # identify ourselves to smtp gmail client
            mailserver.ehlo()
            # secure our email with tls encryption
            mailserver.starttls()
            # re-identify ourselves as an encrypted connection
            mailserver.ehlo()
            mailserver.login('*****@*****.**', 'dummymai007123')

            mailserver.sendmail('*****@*****.**',
                                '*****@*****.**', msg.as_string())

            mailserver.quit()
            print("sent")
            time.sleep(1)
            exit()

    elif GPIO.input(3) == 1:
        print("PLEASE USE ME")
        time.sleep(0.2)
        if GPIO.input(5) == 1:
            p.ChangeDutyCycle(2.5)
            time.sleep(1)
            print("OPEN")
        elif GPIO.input(5) == 0:
            p.ChangeDutyCycle(7.5)
コード例 #51
0
ファイル: assignor.py プロジェクト: thongonary/WmAgentScripts
def main():

    mysqlconn = MySQLdb.connect(host='dbod-cmsrv1.cern.ch',
                                user='******',
                                passwd="relval",
                                port=5506)

    curs = mysqlconn.cursor()

    curs.execute("use " + dbname + ";")

    #curs.execute("lock tables batches write, batches_archive write, workflows write, workflows_archive write, datasets write, clone_reinsert_requests write")

    curs.execute("select * from batches")
    batches = curs.fetchall()

    batches_colnames = [desc[0] for desc in curs.description]

    for batch in batches:
        #for name, value in zip(batches_colnames, batch):
        #    print name+" => "+str(value)

        batch_dict = dict(zip(batches_colnames, batch))

        userid = batch_dict["useridyear"] + "_" + batch_dict[
            "useridmonth"] + "_" + batch_dict["useridday"] + "_" + str(
                batch_dict["useridnum"]) + "_" + str(
                    batch_dict["batch_version_num"])

        if batch_dict["status"] == "input_dsets_ready":

            print "    userid => " + userid

            curs.execute(
                "select workflow_name from workflows where useridyear = \"" +
                batch_dict["useridyear"] + "\" and useridmonth = \"" +
                batch_dict["useridmonth"] + "\" and useridday = \"" +
                batch_dict["useridday"] + "\" and useridnum = " +
                str(batch_dict["useridnum"]) + " and batch_version_num = " +
                str(batch_dict["batch_version_num"]) + ";")
            wfs = curs.fetchall()

            #first do checks to make sure the workflows do not write into an existing dataset
            for wf in wfs:

                conn = httplib.HTTPSConnection(
                    'cmsweb.cern.ch',
                    cert_file=os.getenv('X509_USER_PROXY'),
                    key_file=os.getenv('X509_USER_PROXY'))

                headers = {
                    "Content-type": "application/json",
                    "Accept": "application/json"
                }

                r1 = conn.request("GET",
                                  '/reqmgr2/data/request/' + wf[0],
                                  headers=headers)
                r2 = conn.getresponse()

                schema = (json.loads(r2.read()))

                schema = schema['result']

                if len(schema) != 1:
                    os.system(
                        'echo ' + wf[0] +
                        ' | mail -s \"assignor.py error 9\" [email protected]'
                    )
                    sys.exit(1)

                schema = schema[0]

                schema = schema[wf[0]]

                #if schema['RequestTransition'][len(schema['RequestTransition'])-1]['Status'] != "assignment-approved":
                #    continue

                for key, value in schema.items():
                    if key == "ProcessingString":
                        procstring_main = value

                for key, value in schema.items():
                    if type(value) is dict and key.startswith("Task"):
                        if ('KeepOutput' in value and value['KeepOutput']
                            ) or 'KeepOutput' not in value:
                            if 'InputDataset' in value:

                                if 'AcquisitionEra' not in value:
                                    os.system(
                                        'echo \"' + wf[0] +
                                        '\" | mail -s \"assignor.py error 10\" [email protected]'
                                    )
                                    sys.exit(1)

                                if 'ProcessingString' in value:
                                    procstring = value['ProcessingString']
                                elif "procstring_main" in vars():
                                    procstring = procstring_main
                                else:
                                    os.system(
                                        'echo \"' + wf[0] +
                                        '\" | mail -s \"assignor.py error 11\" [email protected]'
                                    )
                                    sys.exit(1)

                                dset = "/" + value['InputDataset'].split(
                                    '/'
                                )[1] + "/" + value[
                                    'AcquisitionEra'] + "-" + procstring + "-v" + str(
                                        batch_dict["processing_version"]
                                    ) + "/*"

                                curs.execute(
                                    "select * from datasets where dset_name = \""
                                    + dset.rstrip("*") + "\";")

                                dbs_dset_check = utils.getDatasets(dset)

                                curs_fetchall = curs.fetchall()

                                if len(curs_fetchall) != 0:
                                    dsets_colnames = [
                                        desc[0] for desc in curs.description
                                    ]
                                    dset_dict = dict(
                                        zip(dsets_colnames, curs_fetchall[0]))
                                    userid_previously_inserted_dset = dset_dict[
                                        "useridyear"] + "_" + dset_dict[
                                            "useridmonth"] + "_" + dset_dict[
                                                "useridday"] + "_" + str(
                                                    dset_dict["useridnum"]
                                                ) + "_" + str(dset_dict[
                                                    "batch_version_num"])
                                    os.system(
                                        'echo \"' + userid + "\n" + wf[0] +
                                        "\n" +
                                        userid_previously_inserted_dset +
                                        "\n" + dset_dict["workflow_name"] +
                                        "\n" + dset +
                                        '\" | mail -s \"assignor.py error 1\" [email protected]'
                                    )
                                    sys.exit(1)
                                elif len(dbs_dset_check) != 0:
                                    os.system(
                                        'echo \"' + userid + "\n" + wf[0] +
                                        "\n" + dset +
                                        '\" | mail -s \"assignor.py error 5\" [email protected]'
                                    )
                                    sys.exit(1)
                                else:

                                    curs.execute(
                                        "insert into datasets set dset_name=\""
                                        + dset.rstrip("*") +
                                        "\", workflow_name=\"" + wf[0] +
                                        "\", useridyear = \"" +
                                        batch_dict["useridyear"] +
                                        "\", useridmonth = \"" +
                                        batch_dict["useridmonth"] +
                                        "\", useridday = \"" +
                                        batch_dict["useridday"] +
                                        "\", useridnum = " +
                                        str(batch_dict["useridnum"]) +
                                        ", batch_version_num = " +
                                        str(batch_dict["batch_version_num"]) +
                                        ";")

                            elif 'PrimaryDataset' in value:

                                dset = "/" + value[
                                    'PrimaryDataset'] + "/" + value[
                                        'AcquisitionEra'] + "-" + value[
                                            'ProcessingString'] + "-v" + str(
                                                batch_dict["processing_version"]
                                            ) + "/*"
                                curs.execute(
                                    "select * from datasets where dset_name = \""
                                    + dset.rstrip("*") + "\";")

                                curs_fetchall = curs.fetchall()

                                dbs_dset_check = utils.getDatasets(dset)

                                if len(curs_fetchall) != 0:
                                    dsets_colnames = [
                                        desc[0] for desc in curs.description
                                    ]
                                    dset_dict = dict(
                                        zip(dsets_colnames, curs_fetchall[0]))
                                    userid_previously_inserted_dset = dset_dict[
                                        "useridyear"] + "_" + dset_dict[
                                            "useridmonth"] + "_" + dset_dict[
                                                "useridday"] + "_" + str(
                                                    dset_dict["useridnum"]
                                                ) + "_" + str(dset_dict[
                                                    "batch_version_num"])
                                    os.system(
                                        'echo \"' + userid + "\n" + wf[0] +
                                        "\n" +
                                        userid_previously_inserted_dset +
                                        "\n" + dset_dict["workflow_name"] +
                                        "\n" + dset +
                                        '\" | mail -s \"assignor.py error 2\" [email protected]'
                                    )
                                    sys.exit(1)
                                elif len(dbs_dset_check) != 0:
                                    os.system(
                                        'echo \"' + userid + "\n" + wf[0] +
                                        '\" | mail -s \"assignor.py error 7\" [email protected]'
                                    )
                                    sys.exit(1)
                                else:
                                    curs.execute(
                                        "insert into datasets set dset_name=\""
                                        + dset.rstrip("*") +
                                        "\", workflow_name=\"" + wf[0] +
                                        "\", useridyear = " +
                                        batch_dict["useridyear"] +
                                        ", useridmonth = " +
                                        batch_dict["useridmonth"] +
                                        ", useridday = " +
                                        batch_dict["useridday"] +
                                        ", useridnum = " +
                                        str(batch_dict["useridnum"]) +
                                        ", batch_version_num = " +
                                        str(batch_dict["batch_version_num"]) +
                                        ";")

            #only assign the workflows after all of the checks are done
            for wf in wfs:

                conn = httplib.HTTPSConnection(
                    'cmsweb.cern.ch',
                    cert_file=os.getenv('X509_USER_PROXY'),
                    key_file=os.getenv('X509_USER_PROXY'))

                headers = {
                    "Content-type": "application/json",
                    "Accept": "application/json"
                }

                r1 = conn.request("GET",
                                  '/reqmgr2/data/request/' + wf[0],
                                  headers=headers)
                r2 = conn.getresponse()

                if r2.status != 200:
                    time.sleep(30)
                    conn = httplib.HTTPSConnection(
                        'cmsweb.cern.ch',
                        cert_file=os.getenv('X509_USER_PROXY'),
                        key_file=os.getenv('X509_USER_PROXY'))
                    r1 = conn.request("GET",
                                      '/reqmgr2/data/request/' + wf[0],
                                      headers=headers)
                    r2 = conn.getresponse()
                    if r2.status != 200:
                        os.system(
                            'echo ' + wf[0] +
                            ' | mail -s \"assignor.py error 8\" [email protected]'
                        )
                        sys.exit(0)

                schema = json.loads(r2.read())

                schema = schema['result']

                if len(schema) != 1:
                    os.system(
                        'echo ' + wf[0] +
                        ' | mail -s \"assignor.py error 9\" [email protected]'
                    )
                    sys.exit(1)

                schema = schema[0]

                schema = schema[wf[0]]

                if schema['RequestTransition'][
                        len(schema['RequestTransition']) -
                        1]['Status'] != "assignment-approved":
                    continue

                #hack because workflows assigned to only T2_CH_CERN_T0 never get acquired
                site = batch_dict["site"]
                #if site == "T2_CH_CERN_T0":
                #    site = ["T2_CH_CERN","T2_CH_CERN_T0"]

                params = assignment.make_assignment_params(
                    schema, site, batch_dict["processing_version"])

                result = reqMgrClient.assignWorkflow("cmsweb.cern.ch", wf[0],
                                                     "relval", params)

                if result != True:
                    os.system(
                        'echo ' + wf[0] +
                        ' | mail -s \"assignor.py error 4\" [email protected]'
                    )
                    sys.exit(0)

                time.sleep(30)

            curs.execute(
                "update batches set status=\"assigned\", current_status_start_time=\""
                + datetime.datetime.now().strftime("%y:%m:%d %H:%M:%S") +
                "\" where useridyear = \"" + batch_dict["useridyear"] +
                "\" and useridmonth = \"" + batch_dict["useridmonth"] +
                "\" and useridday = \"" + batch_dict["useridday"] +
                "\" and useridnum = " + str(batch_dict["useridnum"]) +
                " and batch_version_num = " +
                str(batch_dict["batch_version_num"]) + ";")

            mysqlconn.commit()

            if batch_dict[
                    "hn_message_id"] != "do_not_send_an_acknowledgement_email":

                msg = MIMEMultipart()
                reply_to = []
                send_to = [
                    "*****@*****.**",
                    "*****@*****.**"
                ]
                #send_to = ["*****@*****.**","*****@*****.**"]
                #send_to = ["*****@*****.**"]

                msg['In-Reply-To'] = batch_dict["hn_message_id"]
                msg['References'] = batch_dict["hn_message_id"]

                msg['From'] = "*****@*****.**"
                msg['reply-to'] = COMMASPACE.join(reply_to)
                msg['To'] = COMMASPACE.join(send_to)
                msg['Date'] = formatdate(localtime=True)
                msg['Subject'] = batch_dict["announcement_title"]
                msg['Message-ID'] = email.Utils.make_msgid()

                messageText = "Dear all,\n"
                messageText = messageText + "\n"
                messageText = messageText + "This batch has been assigned.\n"
                messageText = messageText + "\n"
                messageText = messageText + "RelVal Batch Manager"

                try:
                    msg.attach(MIMEText(messageText))
                    smtpObj = smtplib.SMTP()
                    smtpObj.connect()
                    smtpObj.sendmail("*****@*****.**", send_to,
                                     msg.as_string())
                    smtpObj.close()
                except Exception as e:
                    print "Error: unable to send email: %s" % (str(e))
コード例 #52
0
ファイル: mail.py プロジェクト: yuanshankongmeng/treeio
 def process_email(self):  
     "Create a message and send it"
     try:
         msg = MIMEMultipart('alternative')
         
         msg['From'] = self.fromaddr
         msg['To'] = self.toaddr
         msg['Subject'] = self.subject
 
         text = self.body
         html = self.html
         
         # adding signature           
         if self.signature:
             text += self.signature
                         
         # Record the MIME types of both parts - text/plain and text/html.
         part1 = MIMEText(text.encode('utf-8'), 'plain', 'utf-8')
         msg.attach(part1)
         
         if html:
             part2 = MIMEText(html.encode('utf-8'), 'html', 'utf-8')
             msg.attach(part2)
         
         if not self.port:
             self.port, self.ssl = self.get_smtp_port(self.server)
         
         if self.ssl and hasattr(smtplib, 'SMTP_SSL'):
             s = smtplib.SMTP_SSL(self.server, self.port)
         else:
             s = smtplib.SMTP(self.server, self.port)
         s.set_debuglevel(0)
         s.ehlo()
         try:
             s.starttls()
         except smtplib.SMTPException:
             pass
         s.ehlo()
         if self.username != None:
             s.login(self.username, self.password)
         s.sendmail(self.fromaddr, self.toaddr, msg.as_string())
         s.close()
         return True
     except:
         if settings.DEBUG:
             raise
         else:
             import traceback
             import sys
             from treeio import core
             from django.core.mail import mail_admins
             exc_type, exc_value, exc_traceback = sys.exc_info()
             domain = getattr(settings, 'CURRENT_DOMAIN', 'default')
             subject = "Exception for %s: %s %s" % (domain, unicode(exc_type), unicode(exc_value))
             body = subject + "\n\n"
             body += unicode(core.__file__) + "\n\n"
             body += u"Server: %s\n\n" % self.server
             body += u"Port: %s\n\n" % unicode(self.port)
             body += u"Username: %s\n\n" % self.username
             body += u"From: %s\n\n" % self.fromaddr
             body += u"To: %s\n\n" % self.toaddr
             for s in traceback.format_tb(exc_traceback):
                 body += s + '\n'
             mail_admins(subject, body)
    maintype, subtype = contenttype.split('/')
    if maintype == 'text':
        retval = MIMEText(data, _subtype=subtype)
    else:
        retval = MIMEBase(maintype, subtype)
        retval.set_payload(data)
        Encoders.encode_base64(retval)
    return retval


messagetext = """Hello,

This is a *great* test message from Chapter 9.  I hope you enjoy it!

-- Anonymous"""
messagehtml = """Hello,<P>
This is a <B>great</B> test message from Chapter 9.  I hope you enjoy
it!<P>
-- <I>Anonymous</I>"""

msg = MIMEMultipart('alternative')
msg['To'] = '*****@*****.**'
msg['From'] = 'Test Sender <*****@*****.**>'
msg['Subject'] = 'Test Message, Chapter 9'
msg['Date'] = Utils.formatdate(localtime=1)
msg['Message-ID'] = Utils.make_msgid()

msg.attach(alternative(messagetext, 'text/plain'))
msg.attach(alternative(messagehtml, 'text/html'))
print msg.as_string()
コード例 #54
0
ファイル: frank_stats_gen.py プロジェクト: c0ns0le/Random
csv_data.append("PHReq,Total proc-hours requested by completed jobs.,,,,,,,\n")
csv_data.append("%,Percentage of total proc-hours requested by completed jobs that were requested by group.,,,,,,,\n")
csv_data.append("PHDed,Total proc-hours dedicated to active and completed jobs (allocated hours regardless of the job's CPU usage).,,,,,,,\n")
csv_data.append("%,Percentage of total proc-hours dedicated that were dedicated by group.,,,,,,,\n")





#
# Send the final CSV
#
# Message
msg = MIMEMultipart()
msg["From"] = "*****@*****.**"
msg["To"] = "*****@*****.**"
msg["Subject"] = "Frank Usage Statistics"
msg.attach(MIMEText("Attached...\n"))

# Attachment
part = MIMEBase('application', "octet-stream")
part.set_payload("".join(csv_data))
Encoders.encode_base64(part)
part.add_header("Content-Disposition", 'attachment; filename="Frank_Usage_Statistics.csv"')
msg.attach(part)

# Send it
smtp = smtplib.SMTP('localhost')
smtp.sendmail("*****@*****.**", ["*****@*****.**"], msg.as_string())
smtp.quit()
コード例 #55
0
class mail:
    def __init__(self, sender=None, server=None, port=None, sendfile=None, filepath=None, password=None):
        """ Sort out the given variables and if neccessary fill in default variables
            or give all parameters:
            instance = mail(sender, mailserver, port, true, "/path/to/file", password)
        """

        self.server = server if server is not None else default_mail_server
        self.port = port if port is not None else default_mail_port
        self.sendfile = sendfile if sendfile is not None else default_sendfile
        self.filepath = filepath if filepath is not None else default_filepath
        self.sender = sender if sender is not None else default_sender
        self.password = password if password is not None else default_mail_password

        self.server = smtplib.SMTP(self.server, self.port)
        self.msg = MIMEMultipart()
        # If a password is given, use it to login to the mailserver
        if self.password != None:
            server.starttls()
            self.server.ehlo()
            server.login(self.sender, self.password)

        self.msg["From"] = self.sender

        # Check if user wants to send a file, if so read the specified file
        if self.sendfile.lower() == "true":
            fp = open(self.filepath)
            attachment = MIMEText(fp.read())
            fp.close()
            # Attach the file to the message
            self.msg.attach(attachment)

    def send(self, subject, text, receipient):
        """ Send the mail
            Usage:
            instance.send(subject, text, [receipient1, receipent2])
        """

        #.subject = subject
        #self.text = text
        #self.receipient = receipient

        # Set subject to mail
        self.msg["Subject"]  = subject

        # Set actual text of the email
        #body = text
        self.msg.attach(MIMEText(text, "plain"))

        # If given receipients is a list object cycle through list of receipients
        if type(receipient) == list:
            for email in receipient:
                # Set receipient in email header
                self.msg["To"] = self.email

                # Built the massage object
                message = self.msg.as_string()

                # Try to send mail
                try:
                    self.server.sendmail(self.sender, email, message)
                    self.server.quit()
                    print "Success: Sent email \""+subject+"\" from \""+self.sender+"\" to \""+email+"\""
                except:
                    print "Error: Unable to send email \""+subject+"\" from \""+self.sender+"\" to \""+email+"\""

        # If given receipients is not a list, just try to send the mail
        else:
            email = receipient
            # Set receipient in email header
            self.msg["To"] = email
            # Built the massage object
            message = self.msg.as_string()

            try:
                self.server.sendmail(self.sender, email, message)
                self.server.quit()
                print "Success: Sent email \""+subject+"\" from \""+self.sender+"\"" to \""+email+"\""
            except:
                print "Error: Unable to send email \""+subject+"\" from \""+self.sender+"\" to \""+email+"\""
コード例 #56
0
f.write("\n")

for r in rows:
    f.write(",".join(map(strify, r)))
    f.write("\n")

f.close()

SUBJECT = "Civic Technologies Checkout Data File"

msg = MIMEMultipart()
msg["From"] = CIVIC_FROM
msg["To"] = CIVIC_TO
msg["Subject"] = SUBJECT
msg["Date"] = formatdate(localtime=True)

part = MIMEBase('application', "octet-stream")
part.set_payload(open(filename, "rb").read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
                'attachment; filename="%s"' % os.path.basename(filename))
msg.attach(part)

server = smtplib.SMTP(EMAIL_HOST)

try:
    failed = server.sendmail(msg["From"], msg["To"], msg.as_string())
    server.close()
except Exception, e:
    msg = "Unable to send email. Error: %s" % str(e)
コード例 #57
0
    def sendEmail(self , authInfo, fromAdd, toAdd, subject , htmlText = None , files = None):

            #subject = u'【方舟监控】日常上报错误报表(20151101)'
            #htmlText = u'20151101,<p>ac上报错误数是171200057,比前一天少-4%</p><p>ac上报禁播数是60368124,比前一天少-2%</p><p>调度上报错误数是2601826,比前一天多11%</p><p>素材播放失败数是19207160,比前一天少-3%</p><p>监测发送失败数是193811634,比前一天多6%</p><img src="cid:00000001"/><em>详见附件,或访问<a href="http://10.150.160.136:3000">http://10.150.160.136:3000</a></em>'
            #files = u'/private/var/www/amp/plus/report_20151101.html,/private/var/www/amp/plus/report_20151101.png'
            strFrom = fromAdd
            strTo = toAdd

            server = authInfo.get('server')
            user = authInfo.get('user')
            passwd = authInfo.get('password')

            if not (server and user and passwd) :
                    print 'incomplete login info, exit now'
                    return


            msgRoot = MIMEMultipart('related')
            msgRoot['Subject'] = subject
            msgRoot['From'] = strFrom
            msgRoot['To'] = ",".join(strTo)
            msgRoot.preamble = 'This is a multi-part message in MIME format.'

            # Encapsulate the plain and HTML versions of the message body in an
            # 'alternative' part, so message agents can decide which they want to display.
            msgAlternative = MIMEMultipart('alternative')
            msgRoot.attach(msgAlternative)


            #msgText = MIMEText(plainText, 'plain', 'utf-8')
            #msgAlternative.attach(msgText)


            msgText = MIMEText(htmlText, 'html', 'utf-8')
            msgAlternative.attach(msgText)



            if files != None:
                for file in files:
                    if ".png" in file:
                        att = MIMEImage(open(file, 'rb').read())
                        att.add_header('Content-ID','00000001')
#                        att["Content-Type"] = 'application/octet-stream'
#                        att["Content-Disposition"] = 'attachment; filename="' + os.path.basename(file)+ '"'
                        msgRoot.attach(att)
                    else:
                        att = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8')
                        att["Content-Type"] = 'application/octet-stream'
                        att["Content-Disposition"] = 'attachment; filename="' + os.path.basename(file)+ '"'
                        msgRoot.attach(att)


            smtp = smtplib.SMTP()

            smtp.set_debuglevel(0)
            smtp.connect(server)
            smtp.login(user, passwd)
            print 'login';
            result = smtp.sendmail(strFrom, toAdd, msgRoot.as_string())
            print result;
            #smtp.sendmail()
            smtp.quit()
コード例 #58
0
def mail(gmail_user,
         gmail_pwd,
         from_gmail_user,
         to,
         subject,
         text,
         cc=None,
         bcc=None,
         reply_to=None,
         attach=None,
         html=None,
         pre=False,
         custom_headers=None):
    msg = MIMEMultipart()

    msg['From'] = from_gmail_user
    msg['To'] = to
    msg['Subject'] = subject

    to = [to]

    if cc:
        # cc gets added to the text header as well as list of recipients
        if type(cc) in [str, unicode]:
            msg.add_header('Cc', cc)
            cc = [cc]
        else:
            cc = ', '.join(cc)
            msg.add_header('Cc', cc)
        to += cc

    if bcc:
        # bcc does not get added to the headers, but is a recipient
        if type(bcc) in [str, unicode]:
            bcc = [bcc]
        to += bcc

    if reply_to:
        msg.add_header('Reply-To', reply_to)

    # Encapsulate the plain and HTML versions of the message body in an
    # 'alternative' part, so message agents can decide which they want to
    # display.

    if pre:
        html = "<pre>%s</pre>" % text
    if html:
        msgAlternative = MIMEMultipart('alternative')
        msg.attach(msgAlternative)

        msgText = MIMEText(text)
        msgAlternative.attach(msgText)

        # We reference the image in the IMG SRC attribute by the ID we give it
        # below
        msgText = MIMEText(html, 'html')
        msgAlternative.attach(msgText)
    else:
        msg.attach(MIMEText(text))

    if attach:
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(open(attach, 'rb').read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition',
                        'attachment; filename="%s"' % os.path.basename(attach))
        msg.attach(part)

    if custom_headers:
        for k, v in custom_headers.iteritems():
            msg.add_header(k, v)

    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(gmail_user, gmail_pwd)

    mailServer.sendmail(gmail_user, to, msg.as_string())
    # Should be mailServer.quit(), but that crashes...
    mailServer.close()
コード例 #59
0
# Fetch records for query to get total of new users this year
new_users_this_year = len(db.fetch_records(query_results, "all"))

# Email summary
email_summary_msg = "-" * 47
email_summary_msg += "\nSWAT Tools new user summary\n"
email_summary_msg += "-" * 47
email_summary_msg += "\nLast Week (%s - %s):\t%s" % (
    start_date_formatted, todays_date_formatted, str(new_users_this_week))
email_summary_msg += "\nCurrent Month (%s-%s):\t\t\t%s" % (str(
    todays_date.year), str(
        todays_date.month).zfill(2), str(new_users_this_month))
email_summary_msg += "\nCurrent Year (%s):\t\t\t\t%s\n" % (str(
    todays_date.year), str(new_users_this_year))
email_summary_msg += "-" * 47

# Construct MIME obj
msg = MIMEMultipart()
msg["From"] = EMAIL_HOST_USER
msg["To"] = "*****@*****.**"
msg["Subject"] = "Weekly SWAT Tools user report"
msg.attach(MIMEText(email_summary_msg, "plain"))

# Connect to email server, construct message elements, and send
email_server = smtplib.SMTP(EMAIL_HOST)
email_server.starttls()
email_server.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD)
email_server.sendmail(EMAIL_HOST_USER, "*****@*****.**", msg.as_string())
email_server.quit()
コード例 #60
0
            where id_local=1
                and status!=(select text from status where id=2)
                and creation_date<"%s"
                and system_id=0
                )
         and status=(select text from status where id=1) and performer_id=%s"""
                                          % (
                                              delta.strftime('%Y-%m-%d'),
                                              profile_id,
                                          ))
    ]
    if threads:
        do = True
        mess += """
        <tr><td>%s</td><td>%s</td></tr>
        """ % (fio.encode('utf-8'), ','.join(threads))
mess += """
</table>
"""
if do:
    msg.attach(MIMEText(mess, 'html', _charset='utf-8'))
    smtp = smtplib.SMTP()
    smtp.connect()
    smtp.sendmail('*****@*****.**', '*****@*****.**',
                  msg.as_string())
    smtp.sendmail('*****@*****.**', em, msg.as_string())
    smtp.sendmail('*****@*****.**', em2, msg.as_string())
    smtp.sendmail('*****@*****.**', em3, msg.as_string())
    smtp.sendmail('*****@*****.**', em4, msg.as_string())
    smtp.close()