Exemplo n.º 1
0
 def test_is_fresh_while_within_maxage(self):
     httpretty.register_uri(httpretty.GET,"http://example.com/cats.png",
                            body=self.image_content, max_age=300, last_modified = formatdate(200.0))
     httpretty.register_uri(httpretty.HEAD,"http://example.com/cats.png",
                            max_age=300, last_modified = formatdate(300.0) )
     f = cache.WebImage('http://example.com/cats.png')
     time.time.tm=1200
     self.assertTrue(f.is_fresh())
Exemplo n.º 2
0
 def test_is_fresh_on_recheck_with_last_modified_changed(self):
     httpretty.register_uri(httpretty.GET,"http://example.com/cats.png",
                            body=self.image_content, max_age=300, last_modified = formatdate(200.0) )
     httpretty.register_uri(httpretty.HEAD,"http://example.com/cats.png",
                            max_age=300, last_modified = formatdate(300.0) )
     f = cache.WebImage('http://example.com/cats.png')
     time.time.tm=1400
     self.assertFalse(f.is_fresh())
Exemplo n.º 3
0
def to_rfc2822(dt):
    """Format a timetime or timestamp in RFC 2822 format
    eg 'Sun, 14 Jul 2013 20:14:30 -0000'"""
    try:
        return formatdate(float(dt.strftime('%s')))
    except AttributeError:
        # Wasn't a datetime.datetime() object
        return formatdate(float(dt))
Exemplo n.º 4
0
 def test_store_with_date_header_no_cc_but_valid_expires_header(self):
     storage = DummyStorage(store_result=True)
     policy = self._makeOne(storage)
     environ = self._makeEnviron()
     from email.Utils import formatdate
     then = formatdate(0)
     until = formatdate(400)
     headers = [('Expires', until), ('Date', then)]
     result = policy.store('200 OK', headers, environ)
     self.assertEqual(result, True)
     self.assertEqual(storage.url, 'http://example.com')
     self.assertEqual(storage.status, '200 OK')
     self.assertEqual(storage.headers, headers)
     self.assertEqual(storage.expires, 400)
Exemplo n.º 5
0
def send_mail(recipient, subject, body, attachments="", encoding='utf-8'):
    session = None
    if attachments == "":
        msg = MIMEText(body, 'plain', encoding)
        msg['Subject'] = Header(subject, encoding)
        msg['From'] = Header(u'"{0}" <{1}>'.format(SENDER_NAME, SENDER_EMAIL), encoding)
        msg['To'] = recipient
        msg['Date'] = formatdate()
    else:
        msg = MIMEMultipart()
        msg['Subject'] = Header(subject, encoding)
        msg['From'] = Header(u'"{0}" <{1}>'.format(SENDER_NAME, SENDER_EMAIL), encoding)
        msg['To'] = recipient
        msg['Date'] = formatdate()

        # This is the textual part:
        part = MIMEText(body)
        msg.attach(part)

        # That is what u see if dont have an email reader:
        msg.preamble = 'Multipart massage.\n'

        attachment_list = attachments.split(",")
        # Loop and print each city name.
        for attachment in attachment_list:
            print "attach file: ", attachment
            # This is the binary part(The Attachment):
            part = MIMEApplication(open(attachment,"rb").read())
            part.add_header('Content-Disposition', 'attachment', filename=attachment+".txt")
            msg.attach(part)

    try:
        if SMTP_SSL_TYPE == 'SMTP_SSL':
            session = smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT)
        else:
            session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
            if SMTP_SSL_TYPE == 'SMTP_TLS':
                session.ehlo()
                session.starttls()
                session.ehlo()
        session.login(SMTP_USERNAME, SMTP_PASSWORD)
        session.sendmail(SENDER_EMAIL, recipient, msg.as_string())
    except Exception as e:
        raise e
    finally:
        # close session
        if session:
            session.quit()
Exemplo n.º 6
0
 def send(self, sender, recipients, subject, text, attachments=None):
     To =[]
     for recipient in recipients.split(','):
         self.logger.debug('Appending to recipients list : {0}'.format(recipient))
         To.append(recipient)
     msg = MIMEMultipart()
     msg['From'] = sender
     self.logger.debug('Set sender to : {0}'.format(sender))
     msg['To'] = COMMASPACE.join(To)
     self.logger.debug('Set recipients to : {0}'.format(COMMASPACE.join(To)))
     msg['Date'] = formatdate(localtime=True)
     self.logger.debug('Set date to : {0}'.format(formatdate(localtime=True)))
     msg['Subject'] = subject.decode('utf-8')
     self.logger.debug('Set subject to : {0}'.format(subject.decode('utf-8')))
     msg.preamble = 'Multipart massage.\n'
     part = MIMEText(text, 'plain', 'UTF-8')
     msg.attach(part)
     # This is the binary part(The Attachment):
     if attachments:
         for attachment in attachments.split(','):            
             self.logger.debug('Appending to attachment list : {0}'.format(attachment))
             part = MIMEApplication(open(attachment,"rb").read())
             part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment))
             msg.attach(part)    
     # Could set tls for encryption
     #smtp.starttls()
     # Could use credentials for authentication
     #smtp.login('user','pass')
     try:
         self.logger.debug('Opening smtp connection with argument : {0}'.format(self.smtp))    
         smtp = smtplib.SMTP(self.smtp)
         self.logger.debug('Sending email report with attachments.')      
         smtp.sendmail(sender, To, msg.as_string() )
         self.logger.debug('Done sending email report.')
         result = True 
     except Exception:
         self.logger.warning('Sending of mail failed!')
         self.logger.warning('Traceback :', exc_info=True)
         result = False
     self.logger.debug('Closing smtp connection.')  
     try:  
         smtp.close()
         self.logger.debug('Done closing smtp connection.')
         result = True            
     except Exception:
         self.logger.warning('Smtp connection not closed properly. Propably the email sending failed.')
         result = False
     return result
def sendEmail(subject='Hello World', sender='*****@*****.**', receivers=['*****@*****.**'], mailbodytext='Testing!', attachmentlist=[] ):
    print "\n[INFO]Sending Email ... ...\n"

    #Account
    #NONE
    #Root
    EmailHandle            = MIMEMultipart('related')
    EmailHandle['Subject'] = Header( subject, charset='utf-8')#gb2312
    EmailHandle['Date']    = formatdate(localtime=True)
    EmailHandle['From']    = sender
    EmailHandle['To']      = COMMASPACE.join(receivers)
    #EmailHandle['Cc']     = '*****@*****.**'
    #EmailHandle['Bcc']    = ''
    EmailHandle['Date']    = formatdate()
    EmailHandle.preamble   = ''

    #Alternative
    msgAlternative = MIMEMultipart('alternative')
    EmailHandle.attach(msgAlternative)

    # Form HTML MAIL Body
    msgAlternative.attach( MIMEText(mailbodytext, 'html', 'utf-8') )
    # This example assumes the image is in the current directory
    EmbeddedImage = os.path.join( os.path.dirname( os.path.abspath(__file__)), "mail_embedded_image.png")
    if os.path.exists(EmbeddedImage):
        msgImage = MIMEImage(open(EmbeddedImage, 'rb').read())
        msgImage.add_header('Content-ID', '<embeddedimage>')
        EmailHandle.attach(msgImage)

    # For Attachment
    for file in attachmentlist:
        #
        if not os.path.exists(file):
            continue
        #
        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) )
        msgAlternative.attach(part)

    # Setting SMTP
    smtp = smtplib.SMTP('localhost', 25)
    # SendEmail
    try:
        smtp.sendmail(sender, receivers, EmailHandle.as_string())
    except Exception, e:
        print("SendEmail Exception: %s: %s\n" %(e.errno, e.strerror))
Exemplo n.º 8
0
Arquivo: utils.py Projeto: cmcc/boto
    def emit(self, record):
        """
        Emit a record.

        Format the record and send it to the specified addressees.
        It would be really nice if I could add authorization to this class
        without having to resort to cut and paste inheritance but, no.
        """
        try:
            port = self.mailport
            if not port:
                port = smtplib.SMTP_PORT
            smtp = smtplib.SMTP(self.mailhost, port)
            smtp.login(self.username, self.password)
            msg = self.format(record)
            msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
                            self.fromaddr,
                            ','.join(self.toaddrs),
                            self.getSubject(record),
                            formatdate(), msg)
            smtp.sendmail(self.fromaddr, self.toaddrs, msg)
            smtp.quit()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)
Exemplo n.º 9
0
 def computeSourceRevision(self, changes):
     if not changes:
         return None
     lastChange = max([c.when for c in changes])
     lastSubmit = max([br.submittedAt for br in self.build.requests])
     when = (lastChange + lastSubmit) / 2
     return formatdate(when)
Exemplo n.º 10
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()
Exemplo n.º 11
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()
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()
Exemplo n.º 13
0
    def emit(self, record):
        """
        Emit a record.

        Format the record and send it to the specified addressees.
        """
        try:
            import smtplib

            try:
                from email.Utils import formatdate
            except:
                formatdate = self.date_time
            port = self.mailport
            if not port:
                port = smtplib.SMTP_PORT
            smtp = smtplib.SMTP(self.mailhost, port)
            msg = self.format(record)
            msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
                self.fromaddr,
                string.join(self.toaddrs, ","),
                self.getSubject(record),
                formatdate(),
                msg,
            )
            smtp.sendmail(self.fromaddr, self.toaddrs, msg)
            smtp.quit()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)
Exemplo n.º 14
0
    def emit(self, record):
        """
        Emit a record.

        Format the record and send it to the specified addressees.
        """
        try:
            import smtplib
            import string # for tls add this line
            try:
                from email.utils import formatdate
            except ImportError:
                formatdate = self.date_time
            port = self.mailport
            if not port:
                port = smtplib.SMTP_PORT
            smtp = smtplib.SMTP(self.mailhost, port)
            msg = self.format(record)
            msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
                            self.fromaddr,
                            string.join(self.toaddrs, ","),
                            self.getSubject(record),
                            formatdate(), msg)
            if self.username:
                smtp.ehlo() # for tls add this line
                smtp.starttls() # for tls add this line
                smtp.ehlo() # for tls add this line
                smtp.login(self.username, self.password)
            smtp.sendmail(self.fromaddr, self.toaddrs, msg)
            smtp.quit()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)
Exemplo n.º 15
0
 def end_headers(self):
     """overload the default end_headers, inserting expires header"""
     if self.expires:
         now = time.time()
         expires = now + self.expires
         self.send_header('Expires', formatdate(expires))
     SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)
Exemplo n.º 16
0
 def flush(self,Nmin):
     res=[]
     with locker.lock('accumulating_notifcations'):
         for key in self.cache.keys():
             (subject,sender,addressee)=key
             if self.cache[key]['N'] <= Nmin: 
                 ## flush only above a certain amount of messages
                 continue
             destination = addressee.split(COMMASPACE)
             text = self.cache[key]['Text']
             msg = MIMEMultipart()
             
             msg['From'] = sender
             msg['To'] = addressee
             msg['Date'] = formatdate(localtime=True)
             new_msg_ID = make_msgid()  
             msg['Message-ID'] = new_msg_ID 
             msg['Subject'] = subject
             
             ## add a signature automatically
             text += '\n\n'
             text += 'McM Announcing service'
             #self.logger.log('Sending a message from cache \n%s'% (text))
             try:
                 msg.attach(MIMEText(text))
                 smtpObj = smtplib.SMTP()
                 smtpObj.connect()
                 smtpObj.sendmail(sender, destination, msg.as_string())
                 smtpObj.quit()
                 self.cache.pop(key)
                 res.append( subject )
             except Exception as e:
                 print "Error: unable to send email", e.__class__
         return res
Exemplo n.º 17
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()
Exemplo n.º 18
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()
Exemplo n.º 19
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")
Exemplo n.º 20
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()
Exemplo n.º 21
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()
Exemplo n.º 22
0
def send_mail(send_from, send_to, subject, text, files=[], server='smtp.typa.ru'):
	from smtplib import SMTP
	from os import path
	from email.MIMEMultipart import MIMEMultipart
	from email.MIMEBase import MIMEBase
	from email.MIMEText import MIMEText
	from email.Utils import COMMASPACE, formatdate
	from email import Encoders
	from email.header import Header

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

	for f in files:
		part = MIMEBase('application', "octet-stream")
		part.set_payload( open(f,"rb").read() )
		Encoders.encode_base64(part)
		part.add_header('Content-Disposition', 'attachment; filename="%s"' % path.basename(f))
		msg.attach(part)
	smtp = SMTP(server, 25)
	smtp.sendmail(send_from, send_to, msg.as_string())
	smtp.close()		
Exemplo n.º 23
0
 def formatMessage(self):
     self.msg = MIMEMultipart()
     
     try:
         self.fromaddr = self.settings.SMTPSENDER
         # SMTPRECIPTIENTS is where these values come from 
         self.toaddrs = self.SMTPRECIPIENTS['SMTPTOADDRESS']
         self.ccaddrs = self.SMTPRECIPIENTS['SMTPTOADDRESSCC']
         self.bccaddrs = self.SMTPRECIPIENTS['SMTPTOADDRESSBCC']
     except KeyError:
         self.log.logger.exception('Unable to locate an Address')
         
     self.log.logger.info("self.toaddrs")
     self.log.logger.info(self.toaddrs)
     
     # Add the From: and To: headers at the start!
     #self.msg = ("From: %s\r\nTo: %s\r\n\r\n"
     #       % (self.fromaddr, ", ".join(self.toaddrs)))
     self.msg['From'] = self.fromaddr
     self.msg['To'] = ", ".join(self.toaddrs)
     self.msg['CC'] = ", ".join(self.ccaddrs)
     self.msg['BCC'] = ", ".join(self.bccaddrs)
     self.msg['Date'] = formatdate(localtime=True)
     self.msg['Subject'] = self.messageSubject 
     self.msg.attach(MIMEText(self.message))
     # Guarantees the message ends in a newline
     self.msg.epilogue = ''
Exemplo n.º 24
0
def send_mail(send_from, send_to, subject, text, files=[], server="localhost", port=25):
    assert type(send_to)==list
    assert type(files)==list

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

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

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

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

    smtp = smtplib.SMTP(host=server, port=port, local_hostname='cked.es')
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
Exemplo n.º 25
0
def send_mail(send_from, send_to, subject, text, files=[], html=None, server="localhost"):
  assert type(send_to)==list
  assert type(files)==list

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

  msg['From'] = send_from
  msg['To'] = COMMASPACE.join(send_to)
  msg['Date'] = formatdate(localtime=True)
  msg['Subject'] = subject
  
  for f in files:
    part = MIMEBase('application', "octet-stream")
    part.set_payload( open(f,"rb").read() )
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
    msg.attach(part)

  smtp = smtplib.SMTP(server)
  smtp.sendmail(send_from, send_to, msg.as_string())
  smtp.close()
Exemplo n.º 26
0
 def _send(to, subject, message):
     if MAIL_SERVER == 'logging':
         from gluon.tools import Mail
         mail = Mail()   
         mail.settings.server = MAIL_SERVER
         mail.settings.sender = MAIL_SENDER
         mail.settings.login = MAIL_LOGIN
         return mail.send(to=to, subject=subject, message=message)
     else:
         import smtplib
         from email.MIMEText import MIMEText
         from email.Utils import formatdate
         
         msg = MIMEText(message)
         msg['Subject'] = subject
         msg['From'] = MAIL_SENDER
         msg['To'] = to
         msg['Date'] = formatdate()
         
         s = smtplib.SMTP(MAIL_SERVER)
         try:
             s.sendmail(MAIL_SENDER, [to], msg.as_string())
             return True
         finally:
             s.close()
         return False
Exemplo n.º 27
0
def send_mail(to, fro, subject, text, files=[],server="localhost"):
    assert type(to)==list
    assert type(files)==list
 
    msg = MIMEMultipart()
    msg['From'] = fro
    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)
 
    # now deal with connecting to the server
    server = current_app.config.get("MAIL_SERVER", "localhost")
    server_port = current_app.config.get("MAIL_PORT", 25)
    smtp_user = current_app.config.get("MAIL_USERNAME")
    smtp_pass = current_app.config.get("MAIL_PASSWORD")
    
    smtp = smtplib.SMTP()  # just doing SMTP(server, server_port) does not work with Mailtrap
    # but doing .connect explicitly afterwards works both with Mailtrap and with Mandrill
    smtp.connect(server, server_port)

    if smtp_user is not None:
        smtp.login(smtp_user, smtp_pass)
        
    smtp.sendmail(fro, to, msg.as_string() )
    smtp.close()
Exemplo n.º 28
0
def send_mail(html_mail,text_mail):
    # Now compose message to send:
    me = '"Rene Gassmoeller" <*****@*****.**>'
    you = "*****@*****.**"
    #you = "*****@*****.**"
    
    # Create message container - the correct MIME type is multipart/alternative.
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "ASPECT Newsletter #" + str(number)
    msg['From'] = me
    msg['To'] = you
    msg['Date'] = formatdate()
    
    # Record the MIME types of both parts - text/plain and text/html.
    part1 = MIMEText(text_mail, 'plain')
    part2 = MIMEText(html_mail, 'html')
    
    # Attach parts into message container.
    # According to RFC 2046, the last part of a multipart message, in this case
    # the HTML message, is best and preferred.
    msg.attach(part1)
    msg.attach(part2)
    
    # Send the message via SMTP server.
    s = smtplib.SMTP_SSL('smtp.mailbox.org:465')
    s.login("*****@*****.**",pw)
    
    # sendmail function takes 3 arguments: sender's address, recipient's address
    # and message to send - here it is sent as one string.
    s.sendmail(me, you, msg.as_string())
    s.quit()
Exemplo n.º 29
0
def send_charter_email(context, pdf, to, sender, body, language):
    """ sending the charter by mail """
    mailhost = context.MailHost
    msg = MIMEMultipart()

    msg['Subject'] = translate(_(u"campaign_name", default=u"Healthy Workplaces"), target_language=language)
    msg['From'] = sender
    msg['To'] = to
    msg['Date'] = formatdate(localtime=True)
    msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    params = dict(charset='utf-8')
    part = MIMEBase('text', 'html', **params)
    part.set_payload(body)
    msg.attach(part)

    part = MIMEBase('application', 'octet-stream')
    part.set_payload(pdf)
    Encoders.encode_base64(part)
    part.add_header(
        'Content-Disposition',
        'attachment; filename="campaign-certificate.pdf"',
    )
    msg.attach(part)

    mailhost._send(sender, to, msg.as_string())
Exemplo n.º 30
0
def email_alert(siginfo, to_addrs):
    smtp_host    = get_config('email','smtp_host')
    smtp_port    = get_config('email','smtp_port', int)
    from_address = get_config('email','from_address')

    from_user, from_domain = parse_email_addr(from_address)
    if from_user is None:
        from_user = "******"
    if from_domain is None:
        from_domain = get_hostname()
    from_address = '%s@%s' % (from_user, from_domain)

    log_debug("alert smtp=%s:%d  -> %s" % (smtp_host, smtp_port, ','.join(to_addrs)))

    siginfo.update_derived_template_substitutions()
    summary = siginfo.substitute(siginfo.summary())
    subject = '[%s] %s' % (get_config('email','subject'), summary)
    text = siginfo.format_text() + siginfo.format_details() 

    email_msg            = MIMEMultipart('alternative')
    email_msg['Subject'] = subject
    email_msg['From']    = from_address
    email_msg['To']      = ', '.join(to_addrs)
    email_msg['Date']    = formatdate()

    email_msg.attach(MIMEText(text))

    import smtplib
    try:
        smtp = smtplib.SMTP(smtp_host, smtp_port)
        smtp.sendmail(from_address, to_addrs, email_msg.as_string())
        smtp.quit()
    except smtplib.SMTPException, e:
        syslog.syslog(syslog.LOG_ERR, "email failed: %s" % e)
Exemplo n.º 31
0
    def create_mail(self, text='', objs=[], only_links=''):
        """Create the mail and attach the the files.

        For object without a file it include a Link to the Object in to the
        message.
        """
        attachment_parts = []
        msg = MIMEMultipart()
        msg['Date'] = formatdate(localtime=True)

        # iterate over object list (which can include documents and mails),
        # create attachement parts for them and prepare docs_links
        docs_links = '%s:\r\n' % (translate(
                _('label_documents', default=u'Attachments'),
                context=self.request))

        for obj in objs:

            if IMail.providedBy(obj):
                obj_file = obj.message
            else:
                obj_file = obj.file

            if only_links or not obj_file:
                # rewrite the url with current adminunit's public url
                url = '%s/%s' % (
                    get_current_admin_unit().public_url,
                    '/'.join(obj.getPhysicalPath()[2:]))

                docs_links = '%s\r\n - %s (%s)' % (
                    docs_links, obj.title, url)
                continue

            docs_links = '%s\r\n - %s (%s)' % (
                docs_links,
                obj.title,
                translate(
                    _('label_see_attachment', default=u'see attachment'),
                    context=self.request))

            mimetype = obj_file.contentType
            if not mimetype:
                mimetype = 'application/octet-stream'
            maintype, subtype = obj_file.contentType.split('/', 1)
            part = MIMEBase(maintype, subtype)
            part.set_payload(obj_file.data)
            if mimetype != 'message/rfc822':
                Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"'
                            % obj_file.filename)
            attachment_parts.append(part)

        # First, create the text part and attach it to the message ...
        text = '%s\r\n\r\n%s\r\n' % (
            text.encode(CHARSET, 'ignore'),
            docs_links.encode(CHARSET))

        if not isinstance(text, unicode):
            text = text.decode('utf8')
        msg.attach(MIMEText(text, 'plain', CHARSET))

        # ... then attach all the attachment parts
        for part in attachment_parts:
            msg.attach(part)

        return msg
Exemplo n.º 32
0
    def send(self, torcpts, ccrcpts, mime_headers={}):
        from email.MIMEText import MIMEText
        from email.Utils import formatdate
        stream = self.template.generate(**self.data)
        # don't translate the e-mail stream
        t = deactivate()
        try:
            body = stream.render('text', encoding='utf-8')
        finally:
            reactivate(t)
        public_cc = self.config.getbool('notification', 'use_public_cc')
        headers = {
            'X-Mailer': 'Trac %s, by Edgewall Software' % __version__,
            'X-Trac-Version': __version__,
            'X-Trac-Project': self.env.project_name,
            'X-URL': self.env.project_url,
            'Precedence': 'bulk',
            'Auto-Submitted': 'auto-generated',
            'Subject': self.subject,
            'From': (self.from_name, self.from_email) if self.from_name
                                                      else self.from_email,
            'Reply-To': self.replyto_email
        }

        def build_addresses(rcpts):
            """Format and remove invalid addresses"""
            return filter(lambda x: x,
                          [self.get_smtp_address(addr) for addr in rcpts])

        def remove_dup(rcpts, all):
            """Remove duplicates"""
            tmp = []
            for rcpt in rcpts:
                if not rcpt in all:
                    tmp.append(rcpt)
                    all.append(rcpt)
            return tmp, all

        notify_sys = NotificationSystem(self.env)
        toaddrs = build_addresses(torcpts)
        ccaddrs = build_addresses(ccrcpts)
        accaddrs = notify_sys.smtp_always_cc_list
        bccaddrs = notify_sys.smtp_always_bcc_list

        recipients = []
        toaddrs, recipients = remove_dup(toaddrs, recipients)
        ccaddrs, recipients = remove_dup(ccaddrs, recipients)
        accaddrs, recipients = remove_dup(accaddrs, recipients)
        bccaddrs, recipients = remove_dup(bccaddrs, recipients)

        # if there is not valid recipient, leave immediately
        if len(recipients) < 1:
            self.env.log.info("no recipient for a ticket notification")
            return

        pcc = accaddrs
        if public_cc:
            pcc += ccaddrs
            if toaddrs:
                headers['To'] = ', '.join(toaddrs)
        if pcc:
            headers['Cc'] = ', '.join(pcc)
        headers['Date'] = formatdate()
        msg = MIMEText(body, 'plain')
        # Message class computes the wrong type from MIMEText constructor,
        # which does not take a Charset object as initializer. Reset the
        # encoding type to force a new, valid evaluation
        del msg['Content-Transfer-Encoding']
        msg.set_charset(self._charset)
        self.add_headers(msg, headers)
        self.add_headers(msg, mime_headers)
        NotificationSystem(self.env).send_email(self.from_email, recipients,
                                                msg.as_string())
Exemplo n.º 33
0
    def send_email(self, to_addr, subject, reply_to=None, text=None,
                   html=None, encoding='utf-8', subject_with_host=True,
                   return_receipt=False, attachment=None):
        # 1. Check input data
        if type(subject) is unicode:
            subject = subject.encode(encoding)
        elif is_prototype(subject, MSG):
            subject = subject.gettext()
        else:
            raise TypeError, 'unexpected subject of type %s' % type(subject)

        if len(subject.splitlines()) > 1:
            raise ValueError, 'the subject cannot have more than one line'
        if text and not isinstance(text, unicode):
            raise TypeError, 'the text must be a Unicode string'
        if html and not isinstance(html, unicode):
            raise TypeError, 'the html must be a Unicode string'

        # 2. Local variables
        context = get_context()
        server = context.server
        mail = self.get_resource('/config/mail')

        # 3. Start the message
        message = MIMEMultipart('related')
        message['Date'] = formatdate(localtime=True)

        # 4. From
        from_addr = mail.get_value('emails_from_addr').strip()
        if from_addr:
            # FIXME Parse the address and use Header
            message['From'] = from_addr.encode(encoding)
        else:
            message['From'] = server.smtp_from

        # 5. To
        if isinstance(to_addr, tuple):
            real_name, address = to_addr
            to_addr = '%s <%s>' % (Header(real_name, encoding), address)
        message['To'] = to_addr

        # 6. Subject
        if subject_with_host is True:
            subject = '[%s] %s' % (context.uri.authority, subject)
        message['Subject'] = Header(subject, encoding)

        # 7. Reply-To
        if reply_to:
            message['Reply-To'] = reply_to
        elif mail.get_value('emails_reply_to'):
            user = context.user
            if user:
                user_title = Header(user.get_title(), encoding)
                user_email = user.get_value('email')
                message['Reply-To'] = '%s <%s>' % (user_title, user_email)

        # Return Receipt
        if return_receipt and reply_to:
            message['Disposition-Notification-To'] = reply_to # Standard
            message['Return-Receipt-To'] = reply_to           # Outlook 2000

        # 8. Body
        signature = mail.get_value('emails_signature')
        if signature:
            signature = signature.strip()
            if not signature.startswith('--'):
                signature = '-- \n%s' % signature
            text += '\n\n%s' % signature

        # Create MIMEText
        if html:
            html = html.encode(encoding)
            message_html = MIMEText(html, 'html', _charset=encoding)
        if text:
            text = text.encode(encoding)
            message_text = MIMEText(text, _charset=encoding)
        # Attach MIMETEXT to message
        if text and html:
            message_alternative = MIMEMultipart('alternative')
            message.attach(message_alternative)
            message_alternative.attach(message_text)
            message_alternative.attach(message_html)
        elif html:
            message.attach(message_html)
        elif text:
            message.attach(message_text)
        # Attach attachment
        if attachment:
            subtype = attachment.get_mimetype()
            data = attachment.to_str()
            if subtype[:6] == 'image/':
                subtype = subtype[6:]
                mime_cls = MIMEImage
            else:
                mime_cls = MIMEApplication
            message_attachment = mime_cls(data, subtype)
            message_attachment.add_header('Content-Disposition', 'attachment',
                                          filename=attachment.name)
            message.attach(message_attachment)

        # 6. Send email
        server.send_email(message)
Exemplo n.º 34
0
    def get_TEXT_mail(self,
                      name='',
                      build=None,
                      build_url=None,
                      waterfall_url=None,
                      failed_step='',
                      failed_tests=None,
                      status_text='',
                      test_reasoning='',
                      change=''):
        files_added = []
        files_modified = []
        files_renamed = []
        files_removed = []
        files_added_lbl = ''
        files_modified_lbl = ''
        files_renamed_lbl = ''
        files_removed_lbl = ''
        failed_tests_data = ''
        branch_link = ''

        rev_no = change.revision
        if change.hash:
            revision = change.hash
        branch = ""
        try:
            if change.branch:
                i = change.branch.index('launchpad')
                branch_link = 'https://bazaar.' + change.branch[
                    i:] + '/revision/' + str(rev_no) + '#'
                branch = change.branch
        except Exception:
            pass

        if failed_tests:
            failed_tests_data = "\nTest results:\n--------------\n"
            for ftn, ft_url, ft_text in failed_tests:
                failed_tests_data += '%s: %s\n%s\n\n' % \
                        (ftn, ft_url, ft_text)
        try:
            who_name = change.who[:change.who.index('<')]
        except:
            who_name = change.who

        kwargs = {
            'who_name': tools._to_unicode(who_name),
            'project_name': self.projectName,
            'name': name,
            'waterfall_url': urllib.quote(waterfall_url, '/:'),
            'build_url': build_url,
            'name_quote': urllib.quote(name),
            'failed_step': failed_step,
            'status_text': status_text,
            'who': tools._to_unicode(change.who),
            'when': formatdate(change.when, usegmt=True),
            'branch': branch,
            'revision': revision,
            'rev_no': rev_no,
            'files_added': files_added_lbl + '\n'.join(files_added),
            'files_modified': files_modified_lbl + '\n'.join(files_modified),
            'files_renamed': files_renamed_lbl + '\n'.join(files_renamed),
            'files_removed': files_removed_lbl + '\n'.join(files_removed),
            'failed_tests_data': failed_tests_data,
            'comments': change.comments,
            'reason': build.getReason()
        }
        kwargs['test_reasoning'] = test_reasoning % kwargs
        return tools._to_decode(text_mail % kwargs)
Exemplo n.º 35
0
 def format_date(self, secs):
     return '%s GMT' % formatdate(time() + secs)[:25]
Exemplo n.º 36
0
    def sendMail(self,
                 destination,
                 subject,
                 text,
                 sender=None,
                 reply_msg_ID=None,
                 accumulate=False):

        if not isinstance(destination, list):
            print "Cannot send email. destination should be a list of strings"
            return

        destination.sort()
        msg = MIMEMultipart()
        # it could happen that message are send after forking, threading and there's no current user anymore
        msg['From'] = sender if sender else '*****@*****.**'

        # add a mark on the subjcet automatically
        if locator().isDev():
            msg['Subject'] = '[McM-dev] ' + subject
            destination = ["*****@*****.**"
                           ]  # if -dev send only to service account and sender
            if sender:
                destination.append(sender)
        else:
            msg['Subject'] = '[McM] ' + subject

        msg['To'] = COMMASPACE.join(destination)
        msg['Date'] = formatdate(localtime=True)
        new_msg_ID = make_msgid()
        msg['Message-ID'] = new_msg_ID

        if reply_msg_ID is not None:
            msg['In-Reply-To'] = reply_msg_ID
            msg['References'] = reply_msg_ID

        # accumulate messages prior to sending emails
        com__accumulate = settings.get_value('com_accumulate')
        force_com_accumulate = settings.get_value('force_com_accumulate')
        if force_com_accumulate or (accumulate and com__accumulate):
            with locker.lock('accumulating_notifcations'):
                # get a subject where the request name is taken out
                subject_type = " ".join(
                    filter(lambda w: w.count('-') != 2,
                           msg['Subject'].split()))
                addressees = msg['To']
                sendee = msg['From']
                key = (subject_type, sendee, addressees)
                if key in self.cache:
                    self.cache[key]['Text'] += '\n\n'
                    self.cache[key]['Text'] += text
                    self.cache[key]['N'] += 1
                else:
                    self.cache[key] = {'Text': text, 'N': 1}
                # self.logger.info('Got a message in cache %s'% (self.cache.keys()))
                return new_msg_ID

        # add a signature automatically
        text += '\n\n'
        text += 'McM Announcing service'

        try:
            msg.attach(MIMEText(text))
            smtpObj = smtplib.SMTP()
            smtpObj.connect()
            smtpObj.sendmail(sender, destination, msg.as_string())
            smtpObj.quit()
            return new_msg_ID
        except Exception as e:
            print "Error: unable to send email", e.__class__
Exemplo n.º 37
0
    def send_article(self, obj, configs, send_later=False, isDraft=False):
        to_name = self.to_name_entry.get_text().decode("utf-8")
        from_name = self.from_entry.get_text().decode("utf-8")
        subject = self.subj_entry.get_text().decode("utf-8")
        date = formatdate(localtime=True)
        if not isDraft:
            errors, warnings = self.check_article(to_name, from_name, subject)
        else:
            errors, warnings = None, None
        if errors:
            message = "<span size='large' weight='heavy'>" + _(
                "Errors:") + "</span>\n\n" + errors
            if warnings:
                message = message + "\n\n<span size='large' weight='heavy'>" + _(
                    "Warnings:") + "</span>\n\n" + warnings
            dialog = Dialog_OK(message)
            do_send = False
        elif warnings:
            message = "<span size='large' weight='heavy'>" + _(
                "Warnings:") + "</span>\n\n" + warnings + _(
                    "\n\nDo you want to send the Article?")
            dialog = Dialog_YES_NO(message)
            do_send = dialog.resp
        else:
            do_send = True

        if do_send:
            references = self.references
            user_agent = self.VERSION
            output_charset = self.charset_combo.child.get_text()

            bounds = self.buffer.get_bounds()
            if bounds:
                start, stop = bounds
                text = self.buffer.get_text(start, stop, True).decode("utf-8")
                body = text.split("\n")
            else:
                body = []
            mail_to_send = Mail_To_Send(to_name, from_name, date, subject,
                                        references, user_agent, output_charset,
                                        self.ordered_list, body)
            mail = mail_to_send.get_article()
            article_backup = dict()  # this is needed for outbox/sent storing
            id_name = self.id_name
            for item in [
                    "to_name", "from_name", "subject", "references",
                    "user_agent", "output_charset", "body", "date", "id_name"
            ]:
                article_backup[item] = eval(item)

            def _store_article(dirName, article_backup):
                try:
                    out_files = os.listdir(dirName)
                except:
                    self.statusbar.push(
                        1,
                        _("Problems while opening : ") + dirName)
                else:
                    num = len(out_files)
                    numbers = map(int, out_files)
                    if not numbers: numbers = [-1]
                    number = max((max(numbers), num))
                    f = open(os.path.join(dirName, str(number + 1)), "wb")
                    cPickle.dump(article_backup, f, 1)
                    f.close()
                    if self.pathToArticle and not self.isSent:
                        try:
                            os.remove(
                                os.path.join(self.wdir, self.pathToArticle))
                        except:
                            pass
                    self.destroy(None)

            if send_later:
                if isDraft: outDir = "draft"
                else: outDir = "outbox"
                _store_article(os.path.join(self.wdir, outDir, "mail"),
                               article_backup)

            else:
                self.mailConnection = SMTPConnection(configs["smtp_server"],
                                                     int(configs["smtp_port"]),
                                                     configs["smtp_auth"],
                                                     configs["smtp_username"],
                                                     configs["smtp_password"])
                message, mailSent = self.mailConnection.sendMail(
                    from_name, to_name, mail)
                if not mailSent:
                    self.statusbar.push(1, message)
                    self.mailConnection.closeConnection()
                else:
                    self.mailConnection.closeConnection()
                    _store_article(os.path.join(self.wdir, "sent", "mail"),
                                   article_backup)
Exemplo n.º 38
0
def writeComment(request, config, data, comment):
    """
    Write a comment
    
    @param config: dict containing pyblosxom config info
    @type  config: dict
    
    @param data: dict containing entry info
    @type  data: dict
    
    @param comment: dict containing comment info
    @type  comment: dict

    @return: The success or failure of creating the comment.
    @rtype: string
    """
    entry = data['entry_list'][0]
    cdir = os.path.join(config['comment_dir'], entry['absolute_path'])
    cdir = os.path.normpath(cdir)
    if not os.path.isdir(cdir):
        os.makedirs(cdir)
    cfn = os.path.join(
        cdir, entry['fn'] + "-" + comment['pubDate'] + "." +
        config['comment_draft_ext'])

    argdict = {"request": request, "comment": comment}
    reject = tools.run_callback("comment_reject",
                                argdict,
                                donefunc=lambda x: x)
    if reject == 1:
        return "Comment rejected."

    # write comment
    cfile = None
    try:
        cfile = open(cfn, "w")
    except:
        tools.log("Couldn't open comment file %s for writing" % cfn)
        return "Error: Couldn't open comment file for writing."
    else:
        pass

    def makeXMLField(name, field):
        return "<" + name + ">" + cgi.escape(field[name]) + "</" + name + ">\n"

    try:
        try:
            #TODO: fix this to 'utf-8' and commit to sf
            comment[description].decode('utf-8')
            cfile.write('<?xml version=1.0 encoding=utf-8?>\n')
        except:
            encoding = config.get('blog_encoding', 'iso-8859-1')
            cfile.write('<?xml version="1.0" encoding="%s"?>\n' % encoding)
        cfile.write("<item>\n")
        cfile.write(makeXMLField('title', comment))
        cfile.write(makeXMLField('author', comment))
        cfile.write(makeXMLField('link', comment))
        cfile.write(makeXMLField('source', comment))
        cfile.write(makeXMLField('pubDate', comment))
        cfile.write(makeXMLField('description', comment))
        cfile.write("</item>\n")
        cfile.close()
    except:
        tools.log("Error writing comment data for ", cfn)
        cfile.close()

    # write latest pickle
    latest = None
    latestFilename = os.path.join(config['comment_dir'], 'LATEST.cmt')
    try:
        latest = open(latestFilename, "w")
    except:
        tools.log("Couldn't open latest comment pickle for writing")
        return "Error: Couldn't open latest comment pickle for writing."
    else:
        modTime = float(comment['pubDate'])

    try:
        cPickle.dump(modTime, latest)
        latest.close()
    except (IOError):
        # should log or e-mail
        if latest:
            latest.close()
        return "Error: Problem dumping the pickle."

    # if the right config keys are set, notify by e-mail
    if config.has_key('comment_smtp_server') and config.has_key(
            'comment_smtp_to'):

        # import the formatdate function which is in a different
        # place in Python 2.3 and up.
        try:
            from email.Utils import formatdate
        except ImportError:
            from rfc822 import formatdate

        import smtplib
        author = escape_SMTP_commands(clean_author(comment['author']))
        description = escape_SMTP_commands(comment['description'])
        if comment.has_key('email'):
            email = comment['email']
        else:
            email = config.get('comment_smtp_from', "*****@*****.**")
        try:
            server = smtplib.SMTP(config['comment_smtp_server'])
            curl = config['base_url'] + '/' + entry['file_path']

            headers = []
            headers.append(("From", email))
            headers.append(("To", config["comment_smtp_to"]))
            headers.append(("Date", formatdate(modTime)))
            headers.append(("Subject", "write back by %s" % author))

            html = """%s<br />\n%s<br />\n<a href="%s">%s</a>\n""" % (
                description, cfn, curl, curl)
            message = createhtmlmail(html, headers)
            server.sendmail(from_addr=email,
                            to_addrs=config['comment_smtp_to'],
                            msg=message)
            server.quit()
        except:
            tools.log("Error sending mail: %s" % message)
            return "Error: Problem sending notification email."

    msg = "Success: Comment has been registered."
    if config["comment_draft_ext"] != config["comment_ext"]:
        msg = msg + "  Comment will not appear until it has been manually approved by the owner of this web-site."
    return msg
Exemplo n.º 39
0
def email_article_summary(to_address, summary_filename, start_year,
                          start_month, end_year, end_month, num_articles):
    """Emails a summary file to the given address, with brief information about
    the number of articles published institute authors in a given time period.
    
    Inputs
    ----
    to_address : str
        E-mail address to send the article summary to.
        
    summary_filename : str
        Filename where the output summary file is saved to.
        
    start_year : int
        Year to start searching for article from, e.g. 2012
        
    start_month : int
        Month to start searching for articles from, between 1-12.
        
    end_year : int
        Inclusive year to stop searching for articles from.
        
    end_month : int
        Inclusive month to stop searching for articles from.
    
    num_articles : int
        Number of articles found in the given month.
        
    Notes
    ----
    start_year, start_month, end_year, end_month, and num_articles are required
    for the email body because this information cannot be deduced from the
    summary_filename PDF.
    
    Raises
    ----
    Exception
        If there was some problem sending the email.
    """

    host = HOST
    from_address = FROM_ADDRESS
    body = """
            Good morning,
    
            There were %i peer-reviewed papers produced by researchers at this institute between %i/%i and %i/%i. A summary file containing the front page from each article is attached with this email. Please print out these summary pages, highlight the author(s) on each article and pin them to the monthly papers noticeboard.
            
            Thanks a bunch,
            
            Skynet.
            
            """ % (
        num_articles,
        start_month,
        start_year,
        end_month,
        end_year,
    )

    recipients = [to_address, ADMIN_ADDRESS]

    logging.info("Preparing summary email report for %s" %
                 (', '.join(recipients), ))

    successful = True
    for recipient in recipients:

        message = MIMEMultipart()
        message["From"] = from_address
        message["To"] = recipient
        message[
            "Subject"] = "Refereed papers summary between %i/%i and %i/%i" % (
                start_month,
                start_year,
                end_month,
                end_year,
            )
        message["Date"] = formatdate(localtime=True)

        message.attach(MIMEText(textwrap.dedent(body).lstrip()))

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

        server = smtplib.SMTP(host)

        try:
            failed = server.sendmail(from_address, to_address,
                                     message.as_string())
            server.close()

        except Exception as e:
            logging.critical("Unable to send email to %s. Error: %s" % (
                recipient,
                str(e),
            ))
            successful = False

        else:
            logging.info("Email successfully sent to %s" % recipient)

    return successful
Exemplo n.º 40
0
def send_mail(subject=None,
              text=None,
              interval=timedelta(),
              channel=None,
              to=None,
              extra_headers=None,
              attachments=None,
              timeout=300,
              ):
    from freenasUI.account.models import bsdUsers
    from freenasUI.network.models import GlobalConfiguration
    from freenasUI.system.models import Email
    if not channel:
        channel = get_sw_name().lower()
    if interval > timedelta():
        channelfile = '/tmp/.msg.%s' % (channel)
        last_update = datetime.now() - interval
        try:
            last_update = datetime.fromtimestamp(os.stat(channelfile).st_mtime)
        except OSError:
            pass
        timediff = datetime.now() - last_update
        if (timediff >= interval) or (timediff < timedelta()):
            open(channelfile, 'w').close()
        else:
            return True, 'This message was already sent in the given interval'

    error = False
    errmsg = ''
    em = Email.objects.all().order_by('-id')[0]
    if not to:
        to = [bsdUsers.objects.get(bsdusr_username='******').bsdusr_email]
    if attachments:
        msg = MIMEMultipart()
        msg.preamble = text
        map(lambda attachment: msg.attach(attachment), attachments)
    else:
        msg = MIMEText(text, _charset='utf-8')
    if subject:
        msg['Subject'] = subject

    msg['From'] = em.em_fromemail
    msg['To'] = ', '.join(to)
    msg['Date'] = formatdate()

    try:
        gc = GlobalConfiguration.objects.order_by('-id')[0]
        local_hostname = "%s.%s" % (gc.get_hostname(), gc.gc_domain)
    except:
        local_hostname = "%s.local" % get_sw_name()

    msg['Message-ID'] = "<%s-%s.%s@%s>" % (get_sw_name().lower(), datetime.utcnow().strftime("%Y%m%d.%H%M%S.%f"), base64.urlsafe_b64encode(os.urandom(3)), local_hostname)

    if not extra_headers:
        extra_headers = {}
    for key, val in extra_headers.items():
        if key in msg:
            msg.replace_header(key, val)
        else:
            msg[key] = val
    msg = msg.as_string()

    try:
        if not em.em_outgoingserver or not em.em_port:
            # See NOTE below.
            raise ValueError('you must provide an outgoing mailserver and mail'
                             ' server port when sending mail')
        if em.em_security == 'ssl':
            server = smtplib.SMTP_SSL(
                em.em_outgoingserver,
                em.em_port,
                timeout=timeout,
                local_hostname=local_hostname)
        else:
            server = smtplib.SMTP(
                em.em_outgoingserver,
                em.em_port,
                timeout=timeout,
                local_hostname=local_hostname)
            if em.em_security == 'tls':
                server.starttls()
        if em.em_smtp:
            server.login(
                em.em_user.encode('utf-8'),
                em.em_pass.encode('utf-8'))
        # NOTE: Don't do this.
        #
        # If smtplib.SMTP* tells you to run connect() first, it's because the
        # mailserver it tried connecting to via the outgoing server argument
        # was unreachable and it tried to connect to 'localhost' and barfed.
        # This is because FreeNAS doesn't run a full MTA.
        # else:
        #    server.connect()
        server.sendmail(em.em_fromemail, to, msg)
        server.quit()
    except ValueError as ve:
        # Don't spam syslog with these messages. They should only end up in the
        # test-email pane.
        errmsg = str(ve)
        error = True
    except Exception as e:
        errmsg = str(e)
        log.warn('Failed to send email: %s', errmsg)
        error = True
    except smtplib.SMTPAuthenticationError as e:
        errmsg = "%d %s" % (e.smtp_code, e.smtp_error)
        error = True
    except:
        errmsg = "Unexpected error."
        error = True
    return error, errmsg
#!/usr/bin/python
# -*- encoding: utf-8 -*-

import git
import sys
from collections import defaultdict
from textwrap import wrap
from email.Utils import formatdate

repo = git.Repo('.')
changelog = defaultdict(list)

for id in repo.iter_commits('%s..HEAD' % sys.argv[1]):
    commit = repo.commit(id)
    changelog[commit.author.name].append(commit.summary)

print 'bash-completion (X.Y)'
print

for author in sorted(changelog.keys()):
    print "  [ %s ]" % author
    for log in changelog[author]:
        print '\n'.join(
            wrap(log, initial_indent='  * ', subsequent_indent='    '))
    print

print ' -- David Paleino <*****@*****.**> ', formatdate(localtime=True)
Exemplo n.º 42
0
    def createEmail(self,
                    msgdict,
                    builderName,
                    projectName,
                    results,
                    build,
                    patch=None,
                    logs=None):
        text = msgdict['body'].encode(ENCODING)
        type = msgdict['type']
        if 'subject' in msgdict:
            subject = msgdict['subject'].encode(ENCODING)
        else:
            subject = self.subject % {
                'result': Results[results],
                'projectName': projectName,
                'builder': builderName,
            }

        assert type in (
            'plain',
            'html'), "'%s' message type must be 'plain' or 'html'." % type

        if patch or logs:
            m = MIMEMultipart()
            m.attach(MIMEText(text, type, ENCODING))
        else:
            m = Message()
            m.set_payload(text, ENCODING)
            m.set_type("text/%s" % type)

        m['Date'] = formatdate(localtime=True)
        m['Subject'] = subject
        m['From'] = self.fromaddr
        # m['To'] is added later

        if patch:
            a = MIMEText(patch[1].encode(ENCODING), _charset=ENCODING)
            a.add_header('Content-Disposition',
                         "attachment",
                         filename="source patch")
            m.attach(a)
        if logs:
            for log in logs:
                name = "%s.%s" % (log.getStep().getName(), log.getName())
                if self._shouldAttachLog(
                        log.getName()) or self._shouldAttachLog(name):
                    a = MIMEText(log.getText().encode(ENCODING),
                                 _charset=ENCODING)
                    a.add_header('Content-Disposition',
                                 "attachment",
                                 filename=name)
                    m.attach(a)

        # Add any extra headers that were requested, doing WithProperties
        # interpolation if necessary
        if self.extraHeaders:
            properties = build.getProperties()
            for k, v in self.extraHeaders.items():
                k = properties.render(k)
                if k in m:
                    twlog.msg("Warning: Got header " + k +
                              " in self.extraHeaders "
                              "but it already exists in the Message - "
                              "not adding it.")
                    continue
                m[k] = properties.render(v)

        return m
Exemplo n.º 43
0
    def send(self, torcpts, ccrcpts, mime_headers={}):
        from email.MIMEText import MIMEText
        from email.Utils import formatdate, formataddr
        body = self.hdf.render(self.template_name)
        projname = self.config.get('project', 'name')
        public_cc = self.config.getbool('notification', 'use_public_cc')
        headers = {}
        headers['X-Mailer'] = 'Trac %s, by Edgewall Software' % __version__
        headers['X-Trac-Version'] =  __version__
        headers['X-Trac-Project'] =  projname
        headers['X-URL'] = self.config.get('project', 'url')
        headers['Subject'] = self.subject
        headers['From'] = (projname, self.from_email)
        headers['Sender'] = self.from_email
        headers['Reply-To'] = self.replyto_email

        def build_addresses(rcpts):
            """Format and remove invalid addresses"""
            return filter(lambda x: x, \
                          [self.get_smtp_address(addr) for addr in rcpts])

        def remove_dup(rcpts, all):
            """Remove duplicates"""
            tmp = []
            for rcpt in rcpts:
                if not rcpt in all:
                    tmp.append(rcpt)
                    all.append(rcpt)
            return (tmp, all)

        toaddrs = build_addresses(torcpts)
        ccaddrs = build_addresses(ccrcpts)
        accparam = self.config.get('notification', 'smtp_always_cc')
        accaddrs = accparam and \
                   build_addresses(accparam.replace(',', ' ').split()) or []
        bccparam = self.config.get('notification', 'smtp_always_bcc')
        bccaddrs = bccparam and \
                   build_addresses(bccparam.replace(',', ' ').split()) or []

        recipients = []
        (toaddrs, recipients) = remove_dup(toaddrs, recipients)
        (ccaddrs, recipients) = remove_dup(ccaddrs, recipients)
        (accaddrs, recipients) = remove_dup(accaddrs, recipients)
        (bccaddrs, recipients) = remove_dup(bccaddrs, recipients)
        
        # if there is not valid recipient, leave immediately
        if len(recipients) < 1:
            self.env.log.info('no recipient for a ticket notification')
            return

        pcc = accaddrs
        if public_cc:
            pcc += ccaddrs
            if toaddrs:
                headers['To'] = ', '.join(toaddrs)
        if pcc:
            headers['Cc'] = ', '.join(pcc)
        headers['Date'] = formatdate()
        # sanity check
        if not self._charset.body_encoding:
            try:
                dummy = body.encode('ascii')
            except UnicodeDecodeError:
                raise TracError, "Ticket contains non-Ascii chars. " \
                                 "Please change encoding setting"
        msg = MIMEText(body, 'plain')
        # Message class computes the wrong type from MIMEText constructor,
        # which does not take a Charset object as initializer. Reset the
        # encoding type to force a new, valid evaluation
        del msg['Content-Transfer-Encoding']
        msg.set_charset(self._charset)
        self.add_headers(msg, headers);
        self.add_headers(msg, mime_headers);
        self.env.log.debug("Sending SMTP notification to %s on port %d to %s"
                           % (self.smtp_server, self.smtp_port, recipients))
        msgtext = msg.as_string()
        # Ensure the message complies with RFC2822: use CRLF line endings
        recrlf = re.compile("\r?\n")
        msgtext = "\r\n".join(recrlf.split(msgtext))
        self.server.sendmail(msg['From'], recipients, msgtext)
Exemplo n.º 44
0
def mandar_mail(pm_servidor_correo,
                pm_login_usuario,
                pm_login_password,
                pm_emisor_nombre,
                pm_emisor_correo,
                pm_receptor_nombre,
                pm_receptor_correo,
                pm_asunto,
                pm_archivo_texto,
                pm_archivo_html,
                pm_adjuntos=[],
                pm_acuse_recibo=False,
                pm_imagenes_embebidas=[]):
    """
    Rutina para enviar correo electrónico, permitiendo enviar el
    mensaje alternativa/conjuntamente en modo texto y html, así como
    con archivos adjuntos, imágenes embebidas y pudiendo solicitar
    confirmación de lectura.
    """
    assert type(pm_adjuntos) == list
    assert type(pm_imagenes_embebidas) == list

    #Inicializamos el mensaje a enviar y vamos añadiendo partes
    msgRaiz = MIMEMultipart('related')
    msgRaiz['From'] = pm_emisor_nombre + ' <' + pm_emisor_correo + '>'
    msgRaiz['To'] = pm_receptor_correo
    msgRaiz['Subject'] = pm_asunto
    msgRaiz['Date'] = formatdate(localtime=True)
    msgRaiz.preamble = ''  #De momento, no lo uso
    msgRaiz.epilogue = ''  #De momento, no lo uso

    if pm_acuse_recibo:
        msgRaiz['Disposition-Notification-To'] = pm_emisor_correo

    #Se encapsulan las versiones de texto plano y html del cuerpo
    #del mensaje en una parte 'alternative' para que el cliente de
    #correo decida qué parte mostrar
    msgAlternativo = MIMEMultipart('alternative')
    msgRaiz.attach(msgAlternativo)

    #Abrimos mensaje de texto alternativo y lo añadimos
    #   fp = open(pm_archivo_texto, 'rb')
    msgTexto = MIMEText(pm_archivo_texto, 'plain')
    #   msgTexto = MIMEText(fp.read(), 'plain')
    msgAlternativo.attach(msgTexto)
    #   fp.close()

    #Abrimos mensaje html alternativo y lo añadimos
    #   fp = open(pm_archivo_html, 'rb')
    msgHtml = MIMEText(pm_archivo_html, 'html')
    #   msgHtml = MIMEText(fp.read(), 'html')
    msgAlternativo.attach(msgHtml)
    #   fp.close()

    #Añadimos las imágenes embebidas, si las hay
    for imagen in pm_imagenes_embebidas:
        #Cargar imagen
        archivo_imagen = open(imagen, 'rb')
        msgImage = MIMEImage(archivo_imagen.read())
        archivo_imagen.close()

        #Hemos de adjuntar la imagen en el content-id.
        #En el archivo html se debe hacer referencia al content-id
        #como fuente en el source de la imagen, por ejemplo:
        #<img src="cid:/nombre/de_la_ruta_entera/imagen.jpg">
        msgImage.add_header('Content-ID', '<' + imagen + '>')
        msgRaiz.attach(msgImage)

    #Añadimos los ficheros adjuntos a mandar , si los hay
    for file in pm_adjuntos:
        adjunto = MIMEBase('application', "octet-stream")
        adjunto.set_payload(open(file, "rb").read())
        Encoders.encode_base64(adjunto)
        adjunto.add_header(
            'Content-Disposition',
            'attachment; filename = "%s"' % os.path.basename(file))
        msgRaiz.attach(adjunto)

    #Conectamos con el servidor de correo y mandamos el mensaje
    servidor = smtplib.SMTP(pm_servidor_correo)
    #servidor.set_debuglevel(1)
    servidor.starttls()
    servidor.ehlo()
    servidor.login(pm_login_usuario, pm_login_password)
    try:
        servidor.sendmail(pm_emisor_correo, pm_receptor_correo,
                          msgRaiz.as_string())
        servidor.quit()
        resultado = True
    except:
        resultado = False

    return (resultado)
Exemplo n.º 45
0
def cookie_expiration_date(days):
    expires = time.time() + (days * 24 * 60 * 60)
    return formatdate(expires, usegmt=True)
Exemplo n.º 46
0
    def doSendlog(self, additonalinfo=None):
        ref = str(time())
        # Create the container (outer) email message.
        msg = MIMEMultipart()
        if config.logmanager.user.value != '' and config.logmanager.useremail.value != '':
            fromlogman = config.logmanager.user.value + '  <' + config.logmanager.useremail.value + '>'
            tocrashlogs = '*****@*****.**'
            msg['From'] = fromlogman
            msg['To'] = tocrashlogs
            msg['Cc'] = fromlogman
            msg['Date'] = formatdate(localtime=True)
            msg['Subject'] = 'Ref: ' + ref
            if additonalinfo != "":
                msg.attach(MIMEText(additonalinfo, 'plain'))
            else:
                msg.attach(
                    MIMEText(config.logmanager.additionalinfo.value, 'plain'))
            if self.sendallfiles:
                self.selectedFiles = self["list"].getSelectedList()
                for send in self.previouslySent:
                    if send in self.selectedFiles:
                        self.selectedFiles.remove(send)
                self.sel = ",".join(self.selectedFiles).replace(",", " ")
                self["list"].instance.moveSelectionTo(0)
                for f in self.selectedFiles:
                    self.previouslySent.append(f)
                    fp = open(f, 'rb')
                    data = MIMEText(fp.read())
                    fp.close()
                    msg.attach(data)
                    self.saveSelection()
                    sentfiles = self.sel
            else:
                self.sel = self["list"].getCurrent()[0]
                self.sel = str(self.sel[0])
                sentfiles = self.sel
                fp = open((self.defaultDir + self.sel), 'rb')
                data = MIMEText(fp.read())
                fp.close()
                msg.attach(data)
                self.sentsingle = self.defaultDir + self.sel
                self.changeSelectionState()
                self.saveSelection()

            # Send the email via our own SMTP server.
            wos_user = '******'
            wos_pwd = base64.b64decode('TF95X0dCRlRFNHRDenVKN1dNdlEkZj14')

            try:
                print "connecting to server: mail.openld.es"
                #socket.setdefaulttimeout(30)
                s = smtplib.SMTP("mail.openld.es", 25)
                s.login(wos_user, wos_pwd)
                if config.logmanager.usersendcopy.value:
                    s.sendmail(fromlogman, [tocrashlogs, fromlogman],
                               msg.as_string())
                    s.quit()
                    self.session.open(
                        MessageBox, sentfiles + ' ' +
                        _('has been sent to the SVN team team.\nplease quote')
                        + ' ' + str(ref) + ' ' +
                        _('when asking question about this log\n\nA copy has been sent to yourself.'
                          ), MessageBox.TYPE_INFO)
                else:
                    s.sendmail(fromlogman, tocrashlogs, msg.as_string())
                    s.quit()
                    self.session.open(
                        MessageBox, sentfiles + ' ' +
                        _('has been sent to the SVN team team.\nplease quote')
                        + ' ' + str(ref) + ' ' +
                        _('when asking question about this log'),
                        MessageBox.TYPE_INFO)
            except Exception, e:
                self.session.open(MessageBox,
                                  _("Error:\n%s" % e),
                                  MessageBox.TYPE_INFO,
                                  timeout=10)
Exemplo n.º 47
0
    def doSendlog(self, additonalinfo=None):
        ref = str(time())
        msg = MIMEMultipart()
        if config.logmanager.user.value != '' and config.logmanager.useremail.value != '':
            fromlogman = config.logmanager.user.value + '  <' + config.logmanager.useremail.value + '>'
            tocrashlogs = '*****@*****.**'
            msg['From'] = fromlogman
            msg['To'] = tocrashlogs
            msg['Cc'] = fromlogman
            msg['Date'] = formatdate(localtime=True)
            msg['Subject'] = 'Ref: ' + ref
            if additonalinfo != '':
                msg.attach(MIMEText(additonalinfo, 'plain'))
            else:
                msg.attach(
                    MIMEText(config.logmanager.additionalinfo.value, 'plain'))
            if self.sendallfiles:
                self.selectedFiles = self['list'].getSelectedList()
                for send in self.previouslySent:
                    if send in self.selectedFiles:
                        self.selectedFiles.remove(send)

                self.sel = ','.join(self.selectedFiles).replace(',', ' ')
                self['list'].instance.moveSelectionTo(0)
                for f in self.selectedFiles:
                    self.previouslySent.append(f)
                    fp = open(f, 'rb')
                    data = MIMEText(fp.read())
                    fp.close()
                    msg.attach(data)
                    self.saveSelection()
                    sentfiles = self.sel

            else:
                self.sel = self['list'].getCurrent()[0]
                self.sel = str(self.sel[0])
                sentfiles = self.sel
                fp = open(self.defaultDir + self.sel, 'rb')
                data = MIMEText(fp.read())
                fp.close()
                msg.attach(data)
                self.sentsingle = self.defaultDir + self.sel
                self.changeSelectionState()
                self.saveSelection()
            wos_user = '******'
            wos_pwd = base64.b64decode('NDJJWnojMEpldUxX')
            try:
                print 'connecting to server: mail.dummy.org'
                s = smtplib.SMTP('mail.dummy.org', 26)
                s.login(wos_user, wos_pwd)
                if config.logmanager.usersendcopy.value:
                    s.sendmail(fromlogman, [tocrashlogs, fromlogman],
                               msg.as_string())
                    s.quit()
                    self.session.open(
                        MessageBox, sentfiles + ' ' +
                        _('has been sent to the SVN team team.\nplease quote')
                        + ' ' + str(ref) + ' ' +
                        _('when asking question about this log\n\nA copy has been sent to yourself.'
                          ), MessageBox.TYPE_INFO)
                else:
                    s.sendmail(fromlogman, tocrashlogs, msg.as_string())
                    s.quit()
                    self.session.open(
                        MessageBox, sentfiles + ' ' +
                        _('has been sent to the SVN team team.\nplease quote')
                        + ' ' + str(ref) + ' ' +
                        _('when asking question about this log'),
                        MessageBox.TYPE_INFO)
            except Exception as e:
                self.session.open(MessageBox,
                                  _('Error:\n%s' % e),
                                  MessageBox.TYPE_INFO,
                                  timeout=10)

        else:
            self.session.open(
                MessageBox,
                _('You have not setup your user info in the setup screen\nPress MENU, and enter your info, then try again'
                  ),
                MessageBox.TYPE_INFO,
                timeout=10)
Exemplo n.º 48
0
def send_email(config, entry, comment, comment_dir, comment_filename):
    """Send an email to the blog owner on a new comment

    @param config: configuration as parsed by Pyblosxom
    @type config: dictionary

    @param entry: a file entry
    @type config: dictionary

    @param comment: comment as generated by read_comments
    @type comment: dictionary

    @param comment_dir: the comment directory
    @type comment_dir: string

    @param comment_filename: file name of current comment
    @type comment_filename: string
    """
    import smtplib
    # import the formatdate function which is in a different
    # place in Python 2.3 and up.
    try:
        from email.Utils import formatdate
    except ImportError:
        from rfc822 import formatdate
    from socket import gethostbyaddr

    author = escape_smtp_commands(clean_author(comment['author']))
    description = escape_smtp_commands(comment['description'])
    ipaddress = escape_smtp_commands(comment.get('ipaddress', '?'))

    if 'comment_smtp_from' in config:
        email = config['comment_smtp_from']
    else:
        email = escape_smtp_commands(clean_author(comment['email']))

    try:
        curl = "%s/%s" % (config['base_url'],
                          tools.urlencode_text(entry['file_path']))
        comment_dir = os.path.join(config['comment_dir'],
                                   entry['absolute_path'])

        # create the message
        message = []
        message.append("Name: %s" % author)
        if 'email' in comment:
            message.append("Email: %s" % comment['email'])
        if 'link' in comment:
            message.append("URL: %s" % comment['link'])
        try:
            host_name = gethostbyaddr(ipaddress)[0]
            message.append("Hostname: %s (%s)" % (host_name, ipaddress))
        # FIXME - bare except here--bad!
        except:
            message.append("IP: %s" % ipaddress)
        message.append("Entry URL: %s" % curl)
        message.append("Comment location: %s" % comment_filename)
        message.append("\n\n%s" % description)

        if 'comment_mta_cmd' in config:
            # set the message headers
            message.insert(0, "")
            message.insert(0, "Subject: comment on %s" % curl)
            message.insert(0,
                           "Date: %s" % formatdate(float(comment['pubDate'])))
            message.insert(0, "To: %s" % config["comment_smtp_to"])
            message.insert(0, "From: %s" % email)

            body = '\n'.join(message).encode('utf-8')

            argv = [
                config['comment_mta_cmd'], '-s',
                '"comment on %s"' % curl, config['comment_smtp_to']
            ]

            process = subprocess.Popen(argv,
                                       stdin=subprocess.PIPE,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE)
            process.stdin.write(body)
            process.stdin.close()
            process.wait()
            stdout = process.stdout.read()
            stderr = process.stderr.read()
            tools.get_logger().debug('Ran MTA command: ' + ' '.join(argv))
            tools.get_logger().debug('Received stdout: ' + stdout)
            tools.get_logger().debug('Received stderr: ' + stderr)
            # the except clause below will catch this
            assert stderr == '', stderr

        else:
            assert 'comment_smtp_server' in config
            server = smtplib.SMTP(config['comment_smtp_server'])
            mimemsg = MIMEText("\n".join(message).encode("utf-8"), 'plain',
                               'utf-8')

            # set the message headers
            mimemsg["From"] = email
            mimemsg["To"] = config["comment_smtp_to"]
            mimemsg["Date"] = formatdate(float(comment["pubDate"]))
            mimemsg["Subject"] = ("comment on %s" % curl)

            # send the message via smtp
            server.sendmail(from_addr=email,
                            to_addrs=config['comment_smtp_to'],
                            msg=mimemsg.as_string())
            server.quit()

    except Exception, e:
        tools.get_logger().error("error sending email: %s" %
                                 traceback.format_exception(*sys.exc_info()))
Exemplo n.º 49
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=None,
                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 an EmailMessage object"""
    ln = default_ln(ln)
    if html_images is None:
        html_images = {}

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

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

    if type(bccaddr) is list:
        bccaddr = ','.join(bccaddr)

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

    toaddr = remove_temporary_emails(toaddr)

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

    if replytoaddr:
        headers['Reply-To'] = replytoaddr
    if usebcc:
        headers['Bcc'] = bccaddr
        kwargs['bcc'] = toaddr.split(',') + bccaddr.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['CFG_VERSION'],
                                                  cfg['CFG_SITE_URL'])

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

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

        #if not html_images:
        #    # No image? Attach the HTML to the root
        #    msg_root.attach(msg_text)
        #else:
        if html_images:
            # Image(s)? Attach the HTML and image(s) as children of a
            # "related" block
            msg_related = MIMEMultipart('related')
            #msg_related.attach(msg_text)
            for image_id, image_path in iteritems(html_images):
                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.legacy.bibdocfile.api 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:
                from invenio.ext.logging import register_exception
                register_exception(alert_admin=True,
                                   prefix="Can't attach %s" % attachment)

    return msg_root
Exemplo n.º 50
0
def send_popsheet_email(revision, order, email_list, sender):
    '''
    threaded_connection = Database.connect_to_database()
    cursor = threaded_connection.cursor()

    #cursor = Database.connection.cursor()
    revision = cursor.execute('SELECT * FROM revisions WHERE id = \'{}\' LAMIT 1'.format(revision_id)).fetchone()
    order = cursor.execute('SELECT * FROM {} WHERE item = \'{}\' LAMIT 1'.format(Ecrs.table_used, revision[1])).fetchone()
    email_list = cursor.execute('SELECT email FROM employees WHERE gets_revision_notice = \'yes\''.format(revision[1])).fetchall()
    sender = cursor.execute('SELECT email FROM employees WHERE name = \'{}\' LAMIT 1'.format(General.app.current_user)).fetchone()[0]
    '''

    server = smtplib.SMTP('mailrelay.lennoxintl.com')
    email_string = ''
    for email in email_list:
        email_string += '; {}'.format(email[0])
    email_string = email_string[2:]

    msg = MIMEMultipart()
    msg["From"] = sender
    msg["To"] = email_string
    msg["Subject"] = 'Pop Sheet Notice: {} ({}-{})'.format(
        order[0], order[1], order[2])
    # msg["Subject"] = 'Revision Notice: {} ({}-{}) {}'.format(order[0], order[1], order[2], revision[2].replace('>', ' > '))
    msg['Date'] = formatdate(localtime=True)

    shortcuts = ''
    try:
        order_directory = OrderFileOpeners.get_order_directory(order[1])
    except Exception as e:
        print e
        order_directory = None

    if order_directory:
        shortcuts = '<a href=\"file:///{}\">Open Order Folder</a>'.format(
            order_directory)
    # add a 'open revised document' also
    ###<a href=\"file:///R:\\Design_Eng\\Orders\\Orders_2012\\W-X-Y-Z\\Walmart\\212031\\212031-BOM_CA.xls">Open Revised Document</a>

    revision_id = revision[0]
    related_ecr = revision[9]
    # if related_ecr == None: related_ecr = ''
    document = revision[2].replace('>', ' > ')
    level = revision[3]
    reason = revision[5]
    description = revision[4]

    item_number = order[0]
    sales_order = '{}-{}'.format(order[1], order[2])
    customer = order[5]
    location = '{}, {}'.format(order[8], order[9])
    model = order[11]

    target_date = order[23]
    if target_date:
        target_date = target_date.strftime('%m/%d/%Y')
    else:
        target_date = ''

    produced_date = order[19]
    if produced_date:
        produced_date = produced_date.strftime('%m/%d/%Y')
    else:
        produced_date = ''

    # size="3"
    body_html = '''<style type=\"text/css\">td{{font-family:Arial; color:black; font-size:12pt;}}</style>
        <font face=\"arial\">
        {}
        <hr>
        <table border="0">
        <tr><td align=\"right\">Item&nbsp;Number:&nbsp;</td><td>{}</td></tr>
        <tr><td align=\"right\">Sales&nbsp;Order:&nbsp;</td><td>{}</td></tr>
        <tr><td align=\"right\">Customer:&nbsp;</td><td>{}</td></tr>
        <tr><td align=\"right\">Location:&nbsp;</td><td>{}</td></tr>
        <tr><td align=\"right\">Model:&nbsp;</td><td>{}</td></tr>
        <tr><td align=\"right\">Target&nbsp;Date:&nbsp;</td><td>{}</td></tr>
        <tr><td align=\"right\">Produced&nbsp;Date:&nbsp;</td><td>{}</td></tr>
        </table>
        <hr>
        <table border="0">
        <tr><td align=\"right\">Revision&nbsp;ID:&nbsp;</td><td>{}</td></tr>
        <tr><td align=\"right\">Related&nbsp;ECR:&nbsp;</td><td>{}</td></tr>
        <tr><td align=\"right\">Reason:&nbsp;</td><td>{}</td></tr>
        <tr><td align=\"right\">Document:&nbsp;</td><td>{}</td></tr>
        <tr><td align=\"right\">Revision&nbsp;Level:&nbsp;</td><td>{}</td></tr>
        <tr><td align=\"right\" valign=\"top\">Description:&nbsp;</td><td>{}</td></tr>
        </table>
        '''.format(shortcuts, item_number, sales_order, customer, location,
                   model, target_date, produced_date, revision_id, related_ecr,
                   reason, document, level, description)

    body = MIMEMultipart('alternative')
    body.attach(MIMEText(body_html, 'html'))
    msg.attach(body)

    # print email_string

    try:
        server.sendmail(sender, email_list, msg.as_string())
    except Exception, e:
        wx.MessageBox('Unable to send email. Error: {}'.format(e),
                      'An error occurred!', wx.OK | wx.ICON_ERROR)
Exemplo n.º 51
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
    def buildMessage(self, name, build, results):
        if self.mode == "all":
            intro = "The Buildbot has finished a build of %s.\n" % name
        elif self.mode == "failing":
            intro = "The Buildbot has detected a failed build of %s.\n" % name
        else:
            intro = "The Buildbot has detected a new failure of %s.\n" % name

        # buildurl
        buildurl = self.status.getURLForThing(build)
        # lgo: url's are already quoted now.
        #       if buildurl:
        #            buildurl = urllib.quote(buildurl, '/:')

        # buildboturl
        buildboturl = self.status.getBuildbotURL()
        #        if url:
        #            buildboturl = urllib.quote(url, '/:')

        # reason of build
        buildreason = build.getReason()

        # source stamp
        patch = None
        ss = build.getSourceStamp()
        if ss is None:
            source = "unavailable"
        else:
            if build.getChanges():
                revision = max([int(c.revision) for c in build.getChanges()])

            source = ""
            if ss.branch is None:
                ss.branch = "trunk"
            source += "[branch %s] " % ss.branch
            if revision:
                source += str(revision)
            else:
                source += "HEAD"
            if ss.patch is not None:
                source += " (plus patch)"

        # actual buildslave
        buildslave = build.getSlavename()

        # TODO: maybe display changes here? or in an attachment?

        # status
        t = build.getText()
        if t:
            t = ": " + " ".join(t)
        else:
            t = ""

        if results == SUCCESS:
            status = "Build succeeded!\n"
            res = "PASS"
        elif results == WARNINGS:
            status = "Build Had Warnings%s\n" % t
            res = "WARN"
        else:
            status = "BUILD FAILED%s\n" % t
            res = "FAIL"

        if build.getLogs():
            log = build.getLogs()[-1]
            laststep = log.getStep().getName()
            lastlog = log.getText()

            # only give me the last lines of the log files.
            lines = re.split('\n', lastlog)
            lastlog = ''
            for logline in lines[max(0, len(lines) - 100):]:
                lastlog = lastlog + logline

        # TODO: it would be nice to provide a URL for the specific build
        # here. That involves some coordination with html.Waterfall .
        # Ideally we could do:
        #  helper = self.parent.getServiceNamed("html")
        #  if helper:
        #      url = helper.getURLForBuild(build)

        text = self.body % {
            'result': res,
            'builder': name,
            'revision': revision,
            'branch': ss.branch,
            'blamelist': ",".join(build.getResponsibleUsers()),
            'buildurl': buildurl,
            'buildboturl': buildboturl,
            'reason': buildreason,
            'source': source,
            'intro': intro,
            'status': status,
            'slave': buildslave,
            'laststep': laststep,
            'lastlog': lastlog,
        }

        haveAttachments = False
        if ss.patch or self.addLogs:
            haveAttachments = True
            if not canDoAttachments:
                log.msg("warning: I want to send mail with attachments, "
                        "but this python is too old to have "
                        "email.MIMEMultipart . Please upgrade to python-2.3 "
                        "or newer to enable addLogs=True")

        if haveAttachments and canDoAttachments:
            m = MIMEMultipart()
            m.attach(MIMEText(text))
        else:
            m = Message()
            m.set_payload(text)

        m['Date'] = formatdate(localtime=True)
        m['Subject'] = self.subject % {
            'result': res,
            'builder': name,
            'revision': revision,
            'branch': ss.branch
        }
        m['From'] = self.fromaddr
        # m['To'] is added later
        m['Reply-To'] = self.replytoaddr

        if ss.patch:
            a = MIMEText(patch)
            a.add_header('Content-Disposition',
                         "attachment",
                         filename="source patch")
            m.attach(a)
        if self.addLogs:
            for log in build.getLogs():
                name = "%s.%s" % (log.getStep().getName(), log.getName())
                a = MIMEText(log.getText())
                a.add_header('Content-Disposition',
                             "attachment",
                             filename=name)
                m.attach(a)

        # now, who is this message going to?
        dl = []
        recipients = self.extraRecipients[:]
        if self.sendToInterestedUsers and self.lookup:
            for u in build.getInterestedUsers():
                d = defer.maybeDeferred(self.lookup.getAddress, u)
                d.addCallback(recipients.append)
                dl.append(d)
        d = defer.DeferredList(dl)
        d.addCallback(self._gotRecipients, recipients, m)
        return d
Exemplo n.º 53
0
def send_mail(to,
              subject,
              text,
              attachments=[],
              cc=[],
              bcc=[],
              smtphost="",
              fromaddr=""):

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

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

    myhost = socket.getfqdn()

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

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

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

    body = Template('This is a notification message from $application, running on \n' + \
            'host $host. Please review the following message:\n\n' + \
            '$notify_text\n\nIf output is being captured, you may find additional\n' + \
            'information in your logs.\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
Exemplo n.º 54
0
def add_calendar(adv='Advisor Rittie',
                 stud='Student Rittie',
                 adv_email='*****@*****.**',
                 stud_email='*****@*****.**',
                 dt_start=datetime(2015, 3, 10, 12, 30),
                 dt_end=datetime(2015, 3, 10, 13, 45),
                 uid='[email protected]::2015-03-10::12:30'):

    # construct calendar header info
    attendees = [adv_email]
    organizer = "ORGANIZER;CN=%s:mailto:%s" % (adv, adv_email)
    fro = "%s <%s>" % (adv, adv_email)
    description = "DESCRIPTION: Advisor Appointment with %s" % (stud) + CRLF
    attendee = ""
    for att in attendees:
        attendee += "ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ PARTICIPANT;PARTSTAT=ACCEPTED;RSVP=TRUE" + CRLF
        attendee += " ;CN=" + att + ";X-NUM-GUESTS=0:" + CRLF
        attendee += " mailto:" + att + CRLF

    # set calendar time signatures
    dtstamp = datetime.now().strftime("%Y%m%dT%H%M%S")
    dtstart = dt_start.strftime("%Y%m%dT%H%M%S")
    dtend = dt_end.strftime("%Y%m%dT%H%M%S")
    datesuffix = get_date_suffix(int(dt_start.strftime("%d")))
    datetxt = dt_start.strftime("%A, %B %d") + datesuffix + dt_start.strftime(
        ", %Y")
    starttxt = dt_start.strftime("%I:%M%p").replace('PM', 'pm').replace(
        'AM', 'am').lstrip('0')
    endtxt = dt_end.strftime("%I:%M%p").replace('PM',
                                                'pm').replace('AM',
                                                              'am').lstrip('0')

    # construct calendar item
    ical = "BEGIN:VCALENDAR" + CRLF
    ical += "PRODID:CS419ADVISORPROJECT" + CRLF
    ical += "VERSION:2.0" + CRLF
    ical += "CALSCALE:GREGORIAN" + CRLF
    ical += "METHOD:REQUEST" + CRLF
    ical += "BEGIN:VEVENT" + CRLF
    ical += "DTSTART:" + dtstart + CRLF
    ical += "DTEND:" + dtend + CRLF
    ical += "DTSTAMP:" + dtstamp + CRLF
    ical += organizer + CRLF
    ical += "UID:FIXMEUID" + uid + CRLF
    ical += attendee + "CREATED:" + dtstamp + CRLF
    ical += description + "LAST-MODIFIED:" + dtstamp + CRLF
    ical += "LOCATION: Student to contact Advisor" + CRLF
    ical += "SEQUENCE:0" + CRLF
    ical += "STATUS:CONFIRMED" + CRLF
    ical += "SUMMARY:Advisor Signup with %s confirmed for %s" % (adv,
                                                                 stud) + CRLF
    ical += "TRANSP:OPAQUE" + CRLF
    ical += "END:VEVENT" + CRLF
    ical += "END:VCALENDAR" + CRLF

    # construct email headers and body
    msg = MIMEMultipart('mixed')
    msg['Reply-To'] = fro
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = "Advisor Appointment with %s" % (stud)
    msg['From'] = fro
    msg['To'] = ",".join(attendees)
    eml_body = body = '''
	<br>Advising Signup with %s confirmed
	<br>Name: %s
	<br>Email: %s
	<br>Date: %s
	<br>Time: %s - %s


	<br><br><br>Please contact [email protected] if you experience problems
	''' % (adv, stud, stud_email, datetxt, starttxt, endtxt)

    # declare multipart structure and content info
    msgAlternative = MIMEMultipart('alternative')
    msg.attach(msgAlternative)

    #	calendar content info
    part_cal = MIMEText(ical, 'calendar;method=REQUEST')
    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"))

    #	email content info
    part_email = MIMEText(eml_body, 'html')
    eml_atch = MIMEBase('text/plain', '')
    Encoders.encode_base64(eml_atch)
    eml_atch.add_header('Content-Transfer-Encoding', "")

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

    # send the email calendar invite
    mailServer = smtplib.SMTP('engr.orst.edu')

    # 	Put the SMTP connection in TLS (Transport Layer Security) mode
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()

    mailServer.sendmail(fro, attendees, msg.as_string())
    mailServer.close()
Exemplo n.º 55
0
def meeting_invitation(toAddr, body, datetimeStrP, method, uid):
# def meeting_invitation():
    CRLF = "\r\n"
    # login = ""
    # password = ""
    # attendees = ['phommata <*****@*****.**>', '\n        Andrew Phommathep <*****@*****.**>', '\n        Andrew Phommathep <*****@*****.**>']
    attendees = toAddr
    organizer = "ORGANIZER;CN=organiser:mailto:do.not.reply"+CRLF+" @engr.orst.edu"
    fro = "<*****@*****.**>"

    # ddtstart = datetime.datetime.now()
    # ddtstart = "2015-02-18 15:00:00"
    # ddtstart = datetime.datetime.strptime(ddtstart, "%Y-%m-%d %H:%M:%S")
    ddtstart = datetimeStrP
    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")

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

    description = "DESCRIPTION: test invitation from pyICSParser"+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
    # ical+= "UID:FIXMEUID"+dtstamp+CRLF
    # ical+= "UID:Kevin D McGrath 2015-02-18 15:00:00"+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:test "+ddtstart.strftime("%Y%m%d @ %H:%M")+CRLF+\
           "TRANSP:OPAQUE"+CRLF+\
           "END:VEVENT"+CRLF+\
           "END:VCALENDAR"+CRLF

    # eml_body = "Advising Signup with McGrath, D Kevin confirmed\r\n" \
    #           "Name: REDACTED\r\n" \
    #           "Email: [email protected]\r\n" \
    #           "Date: Wednesday, November 21st, 2012\r\n" \
    #           "Time: 1:00pm - 1:15pm\r\n\r\n" \
    #           "Please contact [email protected] if you experience problems"
    eml_body = body
    msg = MIMEMultipart('mixed')
    msg['Reply-To']=fro
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = "Advising Meeting "+ status #+ 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='+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('smtp.gmail.com', 587)
    mailServer = smtplib.SMTP('mail.engr.oregonstate.edu', 587)
    # mailServer.ehlo()
    # mailServer.starttls()
    # mailServer.ehlo()
    # mailServer.login(login, password)
    mailServer.sendmail(fro, attendees, msg.as_string())
    mailServer.close()
Exemplo n.º 56
0
def hold(mlist, msg, msgdata, annotation):
    """Hold the message in both Mailman and Launchpad.

    `annotation` is an arbitrary string required by the API.
    """
    # Hold the message in Mailman and Launchpad so that it's easier to
    # resubmit it after approval via the LP u/i.  If the team administrator
    # ends up rejecting the message, it will also be easy to discard it on the
    # Mailman side.  But this way, we don't have to reconstitute the message
    # from the librarian if it gets approved.  However, unlike the standard
    # Moderate handler, we don't craft all the notification messages about
    # this hold.  We also need to keep track of the message-id (which better
    # be unique) because that's how we communicate about the message's status.
    request_id = mlist.HoldMessage(msg, annotation, msgdata)
    assert mlist.Locked(), (
        'Mailing list should be locked: %s' % mlist.internal_name())
    # This is a hack because by default Mailman cannot look up held messages
    # by message-id.  This works because Mailman's persistency layer simply
    # pickles the MailList object, mostly without regard to a known schema.
    #
    # Mapping: message-id -> request-id
    holds = getattr(mlist, 'held_message_ids', None)
    if holds is None:
        holds = mlist.held_message_ids = {}
    message_id = msg.get('message-id')
    if message_id is None:
        msg['Message-ID'] = message_id = make_msgid()
    if message_id in holds:
        # No legitimate sender should ever give us a message with a duplicate
        # message id, so treat this as spam.
        syslog('vette',
               'Discarding duplicate held message-id: %s', message_id)
        raise Errors.DiscardMessage
    # Discard messages that claim to be from the list itself because Mailman's
    # internal handlers did not approve the message before it arrived at this
    # step--these messages are forgeries.
    list_address = mlist.getListAddress()
    for sender in msg.get_senders():
        if list_address == sender:
            syslog('vette',
                   'Discarding forged message-id: %s', message_id)
            raise Errors.DiscardMessage
    # Discard messages without text content since there will be nothing to
    # moderate. Most of these messages are spam.
    if is_message_empty(msg):
        syslog('vette',
               'Discarding text-less message-id: %s', message_id)
        raise Errors.DiscardMessage
    holds[message_id] = request_id
    # In addition to Message-ID, the librarian requires a Date header.
    if 'date' not in msg:
        msg['Date'] = formatdate()
    # Store the message in the librarian.
    proxy = XMLRPCRunner.get_mailing_list_api_proxy()
    # This will fail if we can't talk to Launchpad.  That's okay though
    # because Mailman's IncomingRunner will re-queue the message and re-start
    # processing at this handler.
    proxy.holdMessage(mlist.internal_name(),
                      xmlrpclib.Binary(msg.as_string()))
    syslog('vette', 'Holding message for LP approval: %s', message_id)
    # Raise this exception, signaling to the incoming queue runner that it is
    # done processing this message, and should not send it through any further
    # handlers.
    raise Errors.HoldMessage
Exemplo n.º 57
0
    def executeBatch(self, notification, signal, targets):
        log.debug("Executing %s action for targets: %s", self.name, targets)
        self.setupAction(notification.dmd)
        tz_targets = self._targetsByTz(notification.dmd, targets)
        original_lst = signal.event.last_seen_time
        original_fst = signal.event.first_seen_time
        original_sct = signal.event.status_change_time
        for target_timezone, targets in tz_targets.iteritems():
            # Convert timestamp to user timezone
            signal.event.last_seen_time = self._adjustToTimezone(
                original_lst, target_timezone)
            signal.event.first_seen_time = self._adjustToTimezone(
                original_fst, target_timezone)
            signal.event.status_change_time = self._adjustToTimezone(
                original_sct, target_timezone)

            data = self._signalToContextDict(signal, notification)

            # Check for email recipients in the event
            details = data['evt'].details
            mail_targets = details.get('recipients', '')
            mail_targets = [
                x.strip() for x in mail_targets.split(',') if x.strip()
            ]
            if len(mail_targets) > 0:
                log.debug("Adding recipients defined in the event %s",
                          mail_targets)
                targets |= set(mail_targets)

            skipfails = notification.content.get('skipfails', False)

            if signal.clear:
                log.debug(
                    "Generating a notification at enabled 'Send Clear' option when event was closed"
                )
                subject = processTalSource(
                    notification.content['clear_subject_format'], skipfails,
                    **data)
                body = processTalSource(
                    notification.content['clear_body_format'], skipfails,
                    **data)
            else:
                subject = processTalSource(
                    notification.content['subject_format'], skipfails, **data)
                body = processTalSource(notification.content['body_format'],
                                        skipfails, **data)

            log.debug('Sending this subject: %s', subject)

            # Find all time strings in body and add timezone to it
            body = re.sub(r'(\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}\.\d{3})',
                          r'\1 ({})'.format(target_timezone), body)

            plain_body = self._encodeBody(self._stripTags(body))

            email_message = plain_body

            if notification.content['body_content_type'] == 'html':
                email_message = MIMEMultipart('related')
                email_message_alternative = MIMEMultipart('alternative')
                email_message_alternative.attach(plain_body)
                html_body = self._encodeBody(body)
                html_body.set_type('text/html')
                email_message_alternative.attach(html_body)

                email_message.attach(email_message_alternative)
                log.debug('Sending this body: %s', body)
            else:
                log.debug('Sending this body: %s', plain_body)

            host = notification.content['host']
            port = notification.content['port']
            user = notification.content['user']
            password = notification.content['password']
            useTls = notification.content['useTls']
            email_from = notification.content['email_from']

            email_message['Subject'] = subject
            email_message['From'] = email_from
            email_message['To'] = ','.join(targets)
            email_message['Date'] = formatdate(None, True)

            result, errorMsg = sendEmail(email_message, host, port, useTls,
                                         user, password)

            if result:
                log.debug("Notification '%s' sent emails to: %s",
                          notification.id, targets)
            else:
                raise ActionExecutionException(
                    "Notification '%s' FAILED to send emails to %s: %s" %
                    (notification.id, targets, errorMsg))
Exemplo n.º 58
0
print "FROM -> ",
mail_f = raw_input()
check(mail_f)
print "TO -> ",
mail_t = raw_input()
check(mail_t)

print
print "SUBJECT -> ",
sub = raw_input()

msg = MIMEMultipart()
msg['From'] = mail_f
to = []
msg['To'] = to.append(mail_t)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = sub

email_option_body(msg)
print "*" * 35

# Agrega aqui el ID y PASSWORD de SMPT2GO
# --> www.SMTP2GO.com
ID = "id"  #Tu user ID
PASS = "******"  #Tu Clave

# Enviar email
try:
    server = smtplib.SMTP("smtpcorp.com", 2525)
    server.ehlo()
    server.starttls()
Exemplo n.º 59
0
    def deliver(self, response):
        """Given an httpy.Response, write it out to the wire.
        """

        logger.debug("Attempting to send a response.")
        logger.debug("Response lineage as follows:" +
                     "\n%s" % traceback.format_exc())

        # Generate the body and output the Status-Line.
        # =============================================

        reason_phrase = '<no phrase>'
        if response.code in StatusCodes:
            reason_phrase, reason_message = StatusCodes.get(response.code)
            if (not response.body) and (response.code != 200):
                response.body = reason_message
        status_line = ' '.join((str(httpy.HTTP_VERSION_STRING),
                                str(response.code), reason_phrase))
        self.out.write(status_line + '\r\n')

        # Output the headers.
        # ===================
        # Make sure we have Content-Type, Content-Length, Date, and Server.

        lowered = [f.lower() for f in response.headers]
        if 'content-type' not in lowered:
            if 200 <= response.code <= 299:
                # Content-Type defaults to text/html for successful requests
                response.headers['Content-Type'] = 'text/html'
            else:
                # ... and to text/plain for errors.
                response.headers['Content-Type'] = 'text/plain'
        if 'content-length' not in lowered:
            if isiter(response.body):
                response.body = ''.join(list(response.body))
            response.headers['Content-Length'] = len(response.body)
        if 'date' not in lowered:
            response.headers['Date'] = formatdate(usegmt=True)
        if 'server' not in lowered:
            response.headers['Server'] = httpy.RESPONSE_HEADER

        for header in response.headers.iteritems():
            self.out.write("%s: %s\r\n" % header)

        self.out.write('\r\n')
        if hasattr(self.out, 'flush'):
            self.out.flush()

        # Output the body.
        # ================
        # We don't output the body for 304s or HEAD requests, but we always do
        # for Request parsing errors.

        want_body = ((response.code != 304) and (hasattr(self, 'request'))
                     and (self.request.method != 'HEAD'))

        if want_body:
            if isinstance(response.body, basestring):
                self.out.write(response.body)
            elif isiter(response.body):
                for n in response.body:
                    self.out.write(n)
            else:
                raise StandardError("Bad response body type: " +
                                    "'%s'" % type(response.body))

        line = ''
        if hasattr(self, 'request'):
            line = self.request.raw_line
        args = (line, response.code, reason_phrase)
        logger.debug("Responded to %s with %d %s" % args)
        if hasattr(self.out, 'flush'):
            self.out.flush()
Exemplo n.º 60
0
    def sendMailMessage(self, xMailMessage):
        COMMASPACE = ', '

        if dbg:
            print >> sys.stderr, "PyMailSMPTService sendMailMessage"
        recipients = xMailMessage.getRecipients()
        sendermail = xMailMessage.SenderAddress
        sendername = xMailMessage.SenderName
        subject = xMailMessage.Subject
        ccrecipients = xMailMessage.getCcRecipients()
        bccrecipients = xMailMessage.getBccRecipients()
        if dbg:
            print >> sys.stderr, "PyMailSMPTService subject", subject
            print >> sys.stderr, "PyMailSMPTService from", sendername.encode(
                'utf-8')
            print >> sys.stderr, "PyMailSMTPService from", sendermail
            print >> sys.stderr, "PyMailSMPTService send to", recipients

        attachments = xMailMessage.getAttachments()

        textmsg = Message()

        content = xMailMessage.Body
        flavors = content.getTransferDataFlavors()
        if dbg:
            print >> sys.stderr, "PyMailSMPTService flavors len", len(flavors)

        #Use first flavor that's sane for an email body
        for flavor in flavors:
            if flavor.MimeType.find('text/html') != -1 or flavor.MimeType.find(
                    'text/plain') != -1:
                if dbg:
                    print >> sys.stderr, "PyMailSMPTService mimetype is", flavor.MimeType
                textbody = content.getTransferData(flavor)
                try:
                    textbody = textbody.value
                except:
                    pass
                textbody = textbody.encode('utf-8')

                if len(textbody):
                    mimeEncoding = re.sub("charset=.*", "charset=UTF-8",
                                          flavor.MimeType)
                    if mimeEncoding.find('charset=UTF-8') == -1:
                        mimeEncoding = mimeEncoding + "; charset=UTF-8"
                    textmsg['Content-Type'] = mimeEncoding
                    textmsg['MIME-Version'] = '1.0'
                    textmsg.set_payload(textbody)

                break

        if (len(attachments)):
            msg = MIMEMultipart()
            msg.epilogue = ''
            msg.attach(textmsg)
        else:
            msg = textmsg

        hdr = Header(sendername, 'utf-8')
        hdr.append('<' + sendermail + '>', 'us-ascii')
        msg['Subject'] = subject
        msg['From'] = hdr
        msg['To'] = COMMASPACE.join(recipients)
        if len(ccrecipients):
            msg['Cc'] = COMMASPACE.join(ccrecipients)
        if xMailMessage.ReplyToAddress != '':
            msg['Reply-To'] = xMailMessage.ReplyToAddress

        mailerstring = "OpenOffice.org 2.0 via Caolan's mailmerge component"
        try:
            ctx = uno.getComponentContext()
            aConfigProvider = ctx.ServiceManager.createInstance(
                "com.sun.star.configuration.ConfigurationProvider")
            prop = uno.createUnoStruct('com.sun.star.beans.PropertyValue')
            prop.Name = "nodepath"
            prop.Value = "/org.openoffice.Setup/Product"
            aSettings = aConfigProvider.createInstanceWithArguments(
                "com.sun.star.configuration.ConfigurationAccess", (prop, ))
            mailerstring = aSettings.getByName("ooName") + " " + \
             aSettings.getByName("ooSetupVersion") + " via Caolan's mailmerge component"
        except:
            pass

        msg['X-Mailer'] = mailerstring
        msg['Date'] = formatdate(localtime=True)

        for attachment in attachments:
            content = attachment.Data
            flavors = content.getTransferDataFlavors()
            flavor = flavors[0]
            ctype = flavor.MimeType
            maintype, subtype = ctype.split('/', 1)
            msgattachment = MIMEBase(maintype, subtype)
            data = content.getTransferData(flavor)
            msgattachment.set_payload(data)
            Encoders.encode_base64(msgattachment)
            fname = attachment.ReadableName
            try:
                fname.encode('ascii')
            except:
                fname = ('utf-8', '', fname.encode('utf-8'))
            msgattachment.add_header('Content-Disposition', 'attachment', \
             filename=fname)
            msg.attach(msgattachment)

        uniquer = {}
        for key in recipients:
            uniquer[key] = True
        if len(ccrecipients):
            for key in ccrecipients:
                uniquer[key] = True
        if len(bccrecipients):
            for key in bccrecipients:
                uniquer[key] = True
        truerecipients = uniquer.keys()

        if dbg:
            print >> sys.stderr, "PyMailSMPTService recipients are", truerecipients

        self.server.sendmail(sendermail, truerecipients, msg.as_string())