def send_email(address,message):
    """Send an email to the address saying that prepration for the dir is done"""
    import smtplib
    from email.MIMEText import MIMEText
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMENonMultipart import MIMENonMultipart
    from email.MIMEBase import MIMEBase
    from email import Encoders
    import mimetypes
    #
    # Prepare the message
    #
    text=message
    text_mes=MIMEText(text)
    message=MIMEMultipart()
    message.preamble='pKD message'
    message.epilogue = ''
    message['Subject']='Message from pKD server'
    message['From']='pKD Server <*****@*****.**>' 
    message['Reply-To']='*****@*****.**'
    message['To']=address
    message.attach(text_mes)
    #
    # Send the email
    #
    #sys.stdout=X
    try:
        server=smtplib.SMTP('193.1.169.34') #mail.ucd.ie
        server.set_debuglevel(1)
        server.login('jensniel','alpha2')
        server.sendmail('*****@*****.**',address,message.as_string())
        server.quit()
    except:
        pass
    return
Example #2
0
    def compose(self, From, To, body, attaches, **headers):
        from email.MIMEMultipart import MIMEMultipart
        from email.MIMEText import MIMEText
        from email.MIMEBase import MIMEBase
        from email.Encoders import encode_base64

        message = MIMEMultipart()
        message['To'] = formataddr(To, self.charset)
        message['From'] = formataddr(From, self.charset)
        self._setHeaders(message, **headers)
        message.preamble = "Multipart message"
        message.epilogue = ""

        body = isinstance(body, unicode) and body.encode(self.charset) or body
        text = MIMEText(body, _charset=self.charset)
        message.attach(text)

        for ctype, filename, fileobj in attaches:
            maintype, subtype = ctype.split('/', 1)
            attach = MIMEBase(maintype, subtype)
            attach.set_payload(fileobj.read())
            encode_base64(attach)
            attach.add_header("Content-Disposition", "attachment", filename=filename)
            message.attach(attach)

        return message
Example #3
0
def send_email_to_list(debug,line,fromaddr,template,smtp_server,msgsubject,username,password):     
    replyto = fromaddr
    htmlmsgtext = template
    try:
        msgtext = htmlmsgtext.replace('<b>','').replace('</b>','').replace('<br>',"\r").replace('</br>',"\r").replace('<br/>',"\r").replace('</a>','')
        msgtext = re.sub('<.*?>','',msgtext)
        msg = MIMEMultipart()
        msg.preamble = 'This is a multi-part message in MIME format.\n'
        msg.epilogue = ''

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

        msg.add_header('From', fromaddr)
        msg.add_header('To', line)
        msg.add_header('Subject', msgsubject)
        msg.add_header('Reply-To', replyto)
        server = smtplib.SMTP(smtp_server)
        if debug == True:
            server.set_debuglevel(True)
        
        server.starttls()
        server.login(username,password)
        server.sendmail(msg['From'], [msg['To']], msg.as_string())
        print ">sent to: ",line
        server.quit()
        print ">closed session"
        print ">sleeping, dont want to flood smtp server"
        time.sleep(1)
        
    except Exception,e:
        print str(e)
        print ">error sending email ",line
Example #4
0
def send_email_csv_attach(toaddrs, mail, csv_fn, fromaddr=EMAIL_SENDER_ADDR):
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = toaddrs
    msg['Subject'] = 'please check attached csv file for cr status'
    msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'
    # To guarantee the message ends with a newline
    msg.epilogue = ''

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

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

    server = smtplib.SMTP('remotesmtp.mot.com')
    server.set_debuglevel(1)
    server.sendmail(fromaddr, toaddrs, msg.as_string())
    server.quit()
Example #5
0
def emailFile(to,
              subject,
              message,
              filePath,
              mimeType=None,
              fromEmail=FROMEMAIL,
              server=SERVER):
    """
    sends an email attachment to the given address or list of addesses.
    
    if the mimeType is not specified, it uses mimetypes.guess_type to determine it.
    """
    toList, to = processTo(to)

    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['To'] = to
    msg['From'] = fromEmail
    msg['Date'] = formatdate()
    msg.preamble = 'You are not using a MIME-aware reader\n'
    msg.epilogue = ''

    #add the main message
    msg.attach(MIMEText(message))

    if type(filePath) is list:
        for f in filePath:
            addFile(f, msg, mimeType)
    else:
        addFile(filePath, msg, mimeType)

    rawEmail(toList, msg.as_string(), server=server, fromEmail=fromEmail)
Example #6
0
def emailAggregatorPage(from_addr, to_addr, subj, smtp_host, out_fn):
    """
    Read in the HTML page produced by an aggregator run, construct a
    MIME-Multipart email message with the HTML attached, and send it off
    with the given from, to, and subject headers using the specified
    SMTP mail server.
    """
    # Begin building the email message.
    msg = MIMEMultipart()
    msg['To'] = to_addr
    msg['From'] = from_addr
    msg['Subject'] = subj
    msg.preamble = "You need a MIME-aware mail reader.\n"
    msg.epilogue = ""

    # Generate a plain text alternative part.
    plain_text = """
    This email contains entries from your subscribed feeds in HTML.
    """
    part = MIMEText(plain_text, "plain", UNICODE_ENC)
    msg.attach(part)

    # Generate the aggregate HTML page, read in the HTML data, attach it
    # as another part of the email message.
    html_text = open(out_fn).read()
    part = MIMEText(html_text, "html", UNICODE_ENC)
    msg.attach(part)

    # Finally, send the whole thing off as an email message.
    print "Sending email '%s' to '%s'" % (subj, to_addr)
    s = smtplib.SMTP(smtp_host)
    s.sendmail(from_addr, to_addr, msg.as_string())
    s.close()
Example #7
0
def construct_email_message(sender, to_list, cc_list, subject, mtext,
                            attachment_list):
    """
    #
    """
    outer = MIMEMultipart()
    outer['From'] = sender
    outer['To'] = ', '.join(to_list)
    outer['Cc'] = ', '.join(cc_list)
    outer['Subject'] = subject
    outer.preample = 'You will not see this in a MIME-aware mail reader.\n'
    outer.epilogue = ''

    # plain text body
    msg = MIMEText(mtext + '\n\n')
    msg.add_header('Content-Disposition', 'inline')
    outer.attach(msg)

    # file attachments
    # outer.add_header('Content-Transfer-Encoding', 'base64')
    for att in attachment_list:
        if not os.path.isfile(att):
            continue
        ctype, encoding = mimetypes.guess_type(att)
        maintype, subtype = ctype.split('/', 1)
        fp = open(att, 'rb')
        msg = MIMEBase(maintype, subtype)
        # msg = MIMEBase('application', 'octet-stream')
        msg.set_payload(fp.read())
        Encoders.encode_base64(msg)
        basename = att.split('/')[-1]
        msg.add_header('Content-Disposition', 'attachment', filename=basename)
        outer.attach(msg)

    return outer
    def prepare_email_message(self):
        plain = self.plain
        if not plain:
            return None

        # We definitely want unicode at this point.
        plain = su(plain)

        # We must choose the body charset manually.  Note that the
        # goal and effect of this loop is to determine the
        # body_charset.
        for body_charset in "US-ASCII", get_charset(), "UTF-8":
            try:
                plain.encode(body_charset)
            except UnicodeEncodeError:
                pass
            else:
                break
            # Encoding should work now; let's replace errors just in case.
        plain = plain.encode(body_charset, "replace")

        text_part = MIMEText(plain, "plain", body_charset)

        email_msg = MIMEMultipart("alternative")
        email_msg.epilogue = ""
        email_msg.attach(text_part)
        return email_msg
def emailAggregatorPage(from_addr, to_addr, subj, smtp_host, out_fn):
    """
    Read in the HTML page produced by an aggregator run, construct a
    MIME-Multipart email message with the HTML attached, and send it off
    with the given from, to, and subject headers using the specified
    SMTP mail server.
    """
    # Begin building the email message.
    msg = MIMEMultipart()
    msg['To']      = to_addr
    msg['From']    = from_addr
    msg['Subject'] = subj
    msg.preamble   = "You need a MIME-aware mail reader.\n"
    msg.epilogue   = ""

    # Generate a plain text alternative part.
    plain_text = """
    This email contains entries from your subscribed feeds in HTML.
    """
    part = MIMEText(plain_text, "plain", UNICODE_ENC)
    msg.attach(part)

    # Generate the aggregate HTML page, read in the HTML data, attach it
    # as another part of the email message.
    html_text = open(out_fn).read()
    part = MIMEText(html_text, "html", UNICODE_ENC)
    msg.attach(part)

    # Finally, send the whole thing off as an email message.
    print "Sending email '%s' to '%s'" % (subj, to_addr)
    s = smtplib.SMTP(smtp_host)
    s.sendmail(from_addr, to_addr, msg.as_string())
    s.close()
Example #10
0
    def smtp_process(self, alstr_to, astr_from, astr_subject, astr_body,
                     alstr_attach):
        #
        # PRECONDITIONS
        # o Should only be called by one of the send() methods
        # o Assumes that any attachments are valid files
        #
        # POSTCONDITIONS
        # o Interacts with the SMTPlib module
        #

        self.internals_check()

        print astr_from

        msg = MIMEMultipart()
        msg['Subject'] = astr_subject
        msg['From'] = astr_from
        msg.preamble = "This is a mult-part message in MIME format."
        msg.attach(MIMEText(astr_body))
        msg.epilogue = ''

        for file in alstr_attach:
            fp = open(file, 'rb')
            img = MIMEImage(fp.read())
            img.add_header('Content-ID', file)
            fp.close()
            msg.attach(img)

        smtp = smtplib.SMTP()
        smtp.connect(self.mstr_SMTPserver)
        for str_to in alstr_to:
            msg['To'] = str_to
            smtp.sendmail(astr_from, str_to, msg.as_string())
        smtp.close()
def prepare_email_message(mensagem, html=False):

    email = su(mensagem)

    # We must choose the body charset manually.  Note that the
    # goal and effect of this loop is to determine the
    # body_charset.
    for body_charset in 'US-ASCII', get_charset(), 'UTF-8':
        try:
            email.encode(body_charset)
        except UnicodeEncodeError:
            pass
        else:
            break
            # Encoding should work now; let's replace errors just in case.
    if html:
        email = email.encode(body_charset, 'xmlcharrefreplace')
        text_part = MIMEText(email, 'html', body_charset)
    else:
        email = email.encode(body_charset, 'replace')
        text_part = MIMEText(email, 'plain', body_charset)

    # Okay, we send both plain text and html
    email_msg = MIMEMultipart('alternative')
    email_msg.epilogue = ''
    email_msg.attach(text_part)
    return email_msg
def send_from_gmail(email, body, subject):
    ''' Send email from gmail.'''
    server = SMTP('smtp.gmail.com', 587)
## server.set_debuglevel(1)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(EMAIL_LOGIN, EMAIL_PASSWORD)
    # Create the enclosing (outer) message
    outer = MIMEMultipart()
    outer['Subject'] = subject
    outer['To'] = email
    outer['From'] = EMAIL_LOGIN
    outer.preamble = '\n'
    # To guarantee the message ends with a newline
    outer.epilogue =''
    # Note: we should handle calculating the charset
    msg = MIMEText(body)
    # Message body
    outer.attach(msg)
    text = outer.as_string()
    server.sendmail(outer['From'], outer['To'], text)
    # SSL error because of bad comunication closing
    try:
        server.quit()
    except:
        pass
Example #13
0
def send_email(address, message):
    """Send an email to the address saying that prepration for the dir is done"""
    import smtplib
    from email.MIMEText import MIMEText
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMENonMultipart import MIMENonMultipart
    from email.MIMEBase import MIMEBase
    from email import Encoders
    import mimetypes
    #
    # Prepare the message
    #
    text = message
    text_mes = MIMEText(text)
    message = MIMEMultipart()
    message.preamble = 'pKD message'
    message.epilogue = ''
    message['Subject'] = 'Message from pKD server'
    message['From'] = 'pKD Server <*****@*****.**>'
    message['Reply-To'] = '*****@*****.**'
    message['To'] = address
    message.attach(text_mes)
    #
    # Send the email
    #
    #sys.stdout=X
    try:
        server = smtplib.SMTP('193.1.169.34')  #mail.ucd.ie
        server.set_debuglevel(1)
        server.login('jensniel', 'alpha2')
        server.sendmail('*****@*****.**', address, message.as_string())
        server.quit()
    except:
        pass
    return
Example #14
0
def sendMultipartMail(context,
                      from_,
                      to,
                      cc=[],
                      bcc=[],
                      subject="",
                      text="",
                      charset="utf-8"):
    """
    """
    mail = MIMEMultipart("alternative")

    mail['From'] = from_
    mail['To'] = to
    mail['Bcc'] = "".join(cc)
    mail['Bcc'] = "".join(bcc)
    mail['Subject'] = subject
    mail.epilogue = ''

    # create & attach text part
    text = text.encode("utf-8")
    text_part = MIMEText(text, "plain", charset)
    mail.attach(text_part)

    # create & attach html part with images
    html_part = MIMEMultipart("related")
    html_code = MIMEText(text, "html", charset)
    html_part.attach(html_code)
    mail.attach(html_part)

    context.MailHost.send(mail.as_string())
Example #15
0
def emailFile(to, subject, message, filePath, mimeType=None, fromEmail=FROMEMAIL, server=SERVER):
    """
    sends an email attachment to the given address or list of addesses.
    
    if the mimeType is not specified, it uses mimetypes.guess_type to determine it.
    """
    toList, to = processTo(to)

    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['To'] = to
    msg['From'] = fromEmail
    msg['Date'] = formatdate()
    msg.preamble = 'You are not using a MIME-aware reader\n'
    msg.epilogue = ''

    #add the main message
    msg.attach(MIMEText(message))
    
    if type(filePath) is list:
        for f in filePath:
            addFile(f, msg, mimeType)
    else:
        addFile(filePath, msg, mimeType)

    rawEmail(toList, msg.as_string(), server=server, fromEmail=fromEmail)
    def send_mail(self, mail_data):
        if self.email_send:
            print 'Sending traceback via mail ...'
        else:
            print mail_data
            return
        
        subject = self.mail_subject
        sender = self.mail_from
        recipients = self.mail_to
        encoding = 'iso-8859-1'
        
        if not mail_data:
            return
        
        msg = MIMEMultipart("alternative")
        
        msg['Subject'] = Header(subject, encoding)
        msg['To'] = str(recipients)[1:-1].replace('\'','')
        msg['MIME-Version'] = "1.0"
        msg.epilogue = ''

        textPart = MIMEText(mail_data,encoding)
        msg.attach(textPart)

        server = smtplib.SMTP(self.smtp_server)
        try:
            server.sendmail(sender, recipients, msg.as_string())
        except smtplib.SMTPRecipientsRefused,msg:
            print 'mail was refused by smtp server'
Example #17
0
 def send(self, rcpt, mime_headers={}):
     from email.MIMEMultipart import MIMEMultipart
     from email.MIMEText import MIMEText
     from email.Header import Header
     from email.Utils import formatdate
     body = self.hdf.render(self.template_name)
     msg = MIMEMultipart()
     msg.attach(MIMEText(body, 'plain', 'utf-8'))
     msg.epilogue = ''
     msg['X-Mailer'] = 'Trac %s, by Edgewall Software' % __version__
     msg['X-Trac-Version'] = __version__
     projname = self.config.get('project', 'name')
     msg['X-Trac-Project'] = projname
     msg['X-URL'] = self.config.get('project', 'url')
     msg['Subject'] = Header(self.subject, 'utf-8')
     msg['From'] = '%s <%s>' % (projname, self.from_email)
     msg['Sender'] = self.from_email
     msg['Reply-To'] = self.replyto_email
     msg['To'] = rcpt
     msg['Date'] = formatdate()
     for hdr in mime_headers.keys():
         msg[hdr] = mime_headers[hdr]
     self.env.log.debug("Sending SMTP notification to %s on port %d" %
                        (self.smtp_server, self.smtp_port))
     self.server.sendmail(self.from_email, [rcpt], msg.as_string())
Example #18
0
def send_email(debug,toaddr2,msgsubject,fromaddr,template,smtp_server,username,password):
    replyto = fromaddr
    htmlmsgtext = template
    msgtext = htmlmsgtext.replace('<b>','').replace('</b>','').replace('<br>',"\r").replace('</br>',"\r").replace('<br/>',"\r").replace('</a>','')
    msgtext = re.sub('<.*?>','',msgtext)
    msg = MIMEMultipart()
    msg.preamble = 'This is a multi-part message in MIME format.\n'
    msg.epilogue = ''
    body = MIMEMultipart('alternative')
    body.attach(MIMEText(msgtext))
    body.attach(MIMEText(htmlmsgtext, 'html'))
    msg.attach(body)
    msg.add_header('From', fromaddr)
    msg.add_header('To', toaddr2)
    msg.add_header('Subject', msgsubject)
    msg.add_header('Reply-To', replyto)
    server = smtplib.SMTP(smtp_server)
    if debug == True:
            server.set_debuglevel(True)
    
    server.starttls()
    server.login(username,password)
    server.sendmail(msg['From'], [msg['To']], msg.as_string())
    print ">sent email"
    server.quit()
    print ">closed session"
Example #19
0
    def __createMultipartMail(self):
        """
        Private method to create a multipart mail message.
        
        @return string containing the mail message
        """
        try:
            import sipconfig

            sip_version_str = sipconfig.Configuration().sip_version_str
        except ImportError:
            sip_version_str = "sip version not available"

        mpPreamble = (
            "This is a MIME-encoded message with attachments. "
            "If you see this message, your mail client is not "
            "capable of displaying the attachments."
        )

        msgtext = "%s\r\n----\r\n%s----\r\n%s----\r\n%s" % (
            unicode(self.message.toPlainText()),
            Utilities.generateVersionInfo("\r\n"),
            Utilities.generatePluginsVersionInfo("\r\n"),
            Utilities.generateDistroInfo("\r\n"),
        )

        # first part of multipart mail explains format
        msg = MIMEMultipart()
        msg["From"] = unicode(Preferences.getUser("Email"))
        msg["To"] = self.__toAddress
        msg["Subject"] = "[eric4] %s" % unicode(self.subject.text())
        msg.preamble = mpPreamble
        msg.epilogue = ""

        # second part is intended to be read
        att = MIMEText(msgtext, _charset=unicode(Preferences.getSystem("StringEncoding")))
        msg.attach(att)

        # next parts contain the attachments
        for index in range(self.attachments.topLevelItemCount()):
            itm = self.attachments.topLevelItem(index)
            maintype, subtype = str(itm.text(1)).split("/", 1)
            fname = unicode(itm.text(0))
            name = os.path.basename(fname)

            if maintype == "text":
                att = MIMEText(open(fname, "rb").read(), _subtype=subtype)
            elif maintype == "image":
                att = MIMEImage(open(fname, "rb").read(), _subtype=subtype)
            elif maintype == "audio":
                att = MIMEAudio(open(fname, "rb").read(), _subtype=subtype)
            else:
                att = MIMEBase(maintype, subtype)
                att.set_payload(open(fname, "rb").read())
                Encoders.encode_base64(att)
            att.add_header("Content-Disposition", "attachment", filename=name)
            msg.attach(att)

        return msg.as_string()
Example #20
0
    def createEnvelop(self, source, destination, subject):
        envelop = MIMEMultipart()
        envelop['From'] = source
        envelop['To'] = destination
        envelop['Subject'] = subject
        envelop.epilogue = ''  # make sure it ends with a newline

        return envelop
Example #21
0
    def createEnvelop(self, source, destination, subject):
        envelop = MIMEMultipart()
        envelop['From'] = source
        envelop['To'] = destination
        envelop['Subject'] = subject
        envelop.epilogue = '' # make sure it ends with a newline

        return envelop
Example #22
0
    def sendEmail(self, addresses, subject, body):
        """
        send email from address book.
        """
        if not addresses:
            return

        portal_url = getToolByName(self, 'portal_url')
        portal = portal_url.getPortalObject()
        plone_utils = getToolByName(self, 'plone_utils')
        mailHost = plone_utils.getMailHost()

        # preparing the from address.
        charset = portal.getProperty('email_charset', None)
        if charset is None or charset == '':
            charset = plone_utils.getSiteEncoding()
        fromAddress = portal.getProperty('email_from_address', None)
        if fromAddress is None:
            self.log.error(
                'Cannot send notification email: email sender address not set')
            return
        fromName = portal.getProperty('email_from_name', None)
        if fromName is not None:
            fromAddress = "%s <%s>" % (fromName, fromAddress)
        if isinstance(fromAddress, unicode):
            fromAddress = fromAddress.encode(charset, 'replace')
        # for testing only!
        #fromAddress = 'web master <*****@*****.**>'

        email = MIMEMultipart('alternative')
        email.epilogue = ''

        # preparing the email message
        if isinstance(body, unicode):
            body = body.encode(charset, 'replace')
        textPart = MIMEText(body, 'plain', charset)
        email.attach(textPart)
        # the html format.
        htmlPart = MIMEText(body, 'html', charset)
        email.attach(htmlPart)

        message = str(email)

        if isinstance(subject, unicode):
            subject = subject.encode(charset, 'replace')

        for address in addresses:
            if isinstance(address, unicode):
                address = address.encode(charset, 'replace')
            try:
                mailHost.send(message=message,
                              mto=address,
                              mfrom='David <*****@*****.**>',
                              subject=subject)
            except ConflictError:
                raise
            except:
                self.log.error('Sending email error for %s!' % (address))
Example #23
0
    def httprequest(self, postdata):
        if not self.anubisURL.startswith("http://"):
            raise "Invalid URL, only http:// URLs are allowed: url='%s'" % (
                self.anubisURL)
        if not postdata:
            raise "Invalid/No POST data supplied: postdata='%s'" % (postdata)

        headers = {}
        headers["Content-Type"] = "multipart/form-data"
        message = MIMEMultipart(_subtype="form-data")
        ### notification element
        part = MIMEText(None)
        part.set_payload(postdata["notification"], "us-ascii")
        part.add_header("Content-Disposition",
                        "form-data",
                        name="notification")
        message.attach(part)
        ### email element
        part = MIMEText(None)
        part.set_payload(postdata["email"], "us-ascii")
        part.add_header("Content-Disposition", "form-data", name="email")
        message.attach(part)
        ### type element
        part = MIMEText(None)
        part.set_payload(postdata["analysisType"], "us-ascii")
        part.add_header("Content-Disposition",
                        "form-data",
                        name="analysisType")
        message.attach(part)
        ### file data element
        part = MIMEBase('application', "octet-stream")
        part.set_payload(postdata['executable']['content'])
        ### Add content-disposition header.
        dispHeaders = postdata["executable"].get("headers", {})
        part.add_header("Content-Disposition",
                        "form-data",
                        name="executable",
                        filename=postdata["executable"]["filename"])
        for dhName, dhValue in dispHeaders:
            part.add_header(dhName, dhValue)
        message.attach(part)
        message.epilogue = ""
        headerBlock, body = message.as_string().split("\n\n", 1)
        for hName, hValue in message.items():
            headers[hName] = hValue
        ### Make the HTTP request and get the response.
        ### Precondition: 'url', 'method', 'headers', 'body' are all setup properly.
        scheme, netloc, path, parameters, query, fragment = urlparse.urlparse(
            self.anubisURL)
        if parameters or query or fragment:
            raise "Unexpected URL: parameters=%r, query=%r, fragment=%r" % (
                parameters, query, fragment)
        try:
            conn = httplib.HTTPConnection(netloc)
            conn.request("POST", path, body, headers)
            response = conn.getresponse()
        except socket.error, e:
            response = ConnRes(404, e)
Example #24
0
def prepare_mail_message(msg, attachment, filename):
    """ Creates the message
    """
    html = msg

    # First, we transform the message in a text format.
    portal_transforms = getToolByName(getSite(),
                                      'portal_transforms')
    plain = portal_transforms.convert('html_to_text',
                                      html).getData()

    # We definitely want unicode at this point.
    plain = su(plain)
    html = su(html)

    # We must choose the body charset manually.  Note that the
    # goal and effect of this loop is to determine the
    # body_charset.
    for body_charset in 'US-ASCII', get_charset(), 'UTF-8':
        try:
            plain.encode(body_charset)
            html.encode(body_charset)
        except UnicodeEncodeError:
            pass
        else:
            break

    # Encoding should work now; let's replace errors just in case.
    plain = plain.encode(body_charset, 'replace')
    html = html.encode(body_charset, 'xmlcharrefreplace')

    text_part = MIMEText(plain, 'plain', body_charset)
    html_part = MIMEText(html, 'html', body_charset)

    # As we have plain text, html and attachment, we need to do
    # two multiparts:
    # - the first one contains the message
    # the second one includes the previous one and the attachment.
    email_content = MIMEMultipart('alternative')
    email_content.epilogue = ''
    email_content.attach(text_part)
    email_content.attach(html_part)

    # Now the attachment.
    attach = MIMEBase('application', 'pdf')
    attach.set_payload(attachment.read())
    Encoders.encode_base64(attach)
    attach.add_header('Content-Disposition',
                      'attachment; filename="%s"' % filename)

    # We attach everything to the mail.
    email_msg = MIMEMultipart()
    email_msg.attach(email_content)
    email_msg.attach(attach)
    return email_msg
Example #25
0
def main(argv):
    is_looping = False
    root_path = "./"
    move_path = None
    fail_path = DEFAULT_FAIL_PATH
    try:
        opts, args = getopt.getopt(argv, "i:o:f:l")
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt == "-i":
            root_path += arg
        elif opt == "-o":
            move_path = "./" + arg
        elif opt == "-f":
            fail_path = "./" + arg
        elif opt == "-l":
            is_looping = True

    msg = "Importer naturally stopped."
    logger.info("Importer started with input=" + root_path + ", output=" +
                str(move_path) + ", fail=" + fail_path + ", loop=" +
                str(is_looping))
    try:
        while True:
            print "Importing..."
            parser_findzip(root_path, move_path, fail_path, is_looping)
            if (False == is_looping):
                break
            print "Waiting..."
            time.sleep(10)
    except:
        msg = traceback.format_exc()
        print msg

    if (False == is_looping):
        return

    logger.info("Mailing...")
    mail_obj = MIMEMultipart()
    mail_obj['Subject'] = EMAIL_SUBJECT
    mail_obj['From'] = EMAIL_FROM
    mail_obj['To'] = listToStr(EMAIL_RECEIVERS)
    mail_obj.preamble = "This is a multi-part message in MIME format."
    mail_obj.epilogue = ''
    msg_txt = MIMEText(msg)
    msg_txt.replace_header('Content-Type', 'text/html; charset="big5"')
    mail_obj.attach(msg_txt)
    msg_body = mail_obj.as_string()

    smtpObj = smtplib.SMTP('relay-b.pegatroncorp.com')
    smtpObj.sendmail(EMAIL_FROM, EMAIL_RECEIVERS, msg_body)
    smtpObj.quit()
Example #26
0
def sendAlarm( context, subj, txt ):
    import sco_utils
    msg = MIMEMultipart()
    subj = Header( subj,  sco_utils.SCO_ENCODING )
    msg['Subject'] = subj
    msg['From'] = context.get_preference('email_from_addr')
    msg['To'] = ALARM_DESTINATION
    msg.epilogue = ''
    txt = MIMEText( txt, 'plain', sco_utils.SCO_ENCODING )
    msg.attach(txt)
    context.sendEmail(msg)
Example #27
0
def sys_adm_notify(db, param):
  """This program sends notifications of messages to sys admins"""
  
  new_messages = dbobj.sys_admin_msg_list(db, status='N')
  sysadmins = dbobj.sys_admin_list(db)

  for sa in sysadmins:
    send_mail = 0
    body = tag('H1', param.title)
    body += "<H4>The following messages have been received and await your attention</H4>"
    body = tag('A', body, 'href=' + param.baseurl + param.pythondir + '/office.py?jw_action=sys_admf_msg')
    for msg in new_messages.messagelist:
      send_mail = 1
      line = tag('A', msg.body, 'href=' + param.baseurl + param.pythondir + '/office.py?jw_action=sys_admf_disp&msg_id=' + str(msg.msg_id))
      line += ' From: ' + msg.name + '<BR>'
      body += line

    if send_mail:
      # Create the mail message
      outer = MIMEMultipart()

      # Mail headers
      outer['Subject'] = 'You have new messages from ' + param.title
      outer['From'] = param.fromaddr
      outer['To'] = sa.email
      outer.preamble = 'Notification of messages'
      outer.epilogue = ''

      #Add the html header
      textfile = param.template_dir + '/' + param.email_header
      mf = open(textfile)
      msg_body = mf.read()
      mf.close()

      #Add the body of the email
      msg_body += body

      #Add the footer of the email
      textfile = param.template_dir + '/' + param.email_footer
      mf = open(textfile)
      msg_body += mf.read()
      mf.close()

      msgfile = MIMEText(msg_body, 'html')
      outer.attach(msgfile)

      mailserver = smtplib.SMTP(param.smtpserver)
      #mailserver.set_debuglevel(1)
      mailserver.sendmail(param.fromaddr, sa.email, outer.as_string())
      mailserver.quit()


  return
Example #28
0
def sendMail(subject,
             body,
             attachments = [],
             status = False,
             from_mail = '*****@*****.**',
             to_mail = [ '*****@*****.**' ],
             smtp_host = ''):
    if attachments:
        msg = MIMEMultipart()
    else:
        msg = Message()

    msg['Subject'] = subject
    msg['From']    = from_mail
    msg['To']      = ', '.join(to_mail)
    msg['X-ERP5-Tests'] = 'ERP5'

    if status:
        msg['X-ERP5-Tests-Status'] = 'OK'

    # Guarantees the message ends in a newline
    msg.preamble = subject
    msg.epilogue = ''

    if attachments:
        mime_text = MIMEText(body)
        mime_text.add_header('Content-Disposition', 'attachment',
                             filename='body')
        msg.attach(mime_text)
        html_re = re.compile('<html>', re.I)
        for item in attachments:
            mime_text = MIMEText(item)
            if html_re.match(item):
                mime_text.set_type('text/html')
                mime_text.add_header('Content-Disposition', 'attachment',
                                     filename='attachment.html')
            else:
                mime_text.add_header('Content-Disposition', 'attachment',
                                     filename='attachment.txt')
            msg.attach(mime_text)

    else:
        msg.set_payload(body)

    # Send the email via SMTP server.
    if smtp_host:
      s = smtplib.SMTP(smtp_host)
    else:
      s = smtplib.SMTP()
      s.connect()
    s.sendmail(from_mail, to_mail, msg.as_string())
    s.close()
Example #29
0
    def send(self,fromaddr,toaddr,msgsubject = '',msg='',attachments=[]):
        
        replyto = fromaddr
        self.htmlmsgtext=msg
        try:
            # Make text version from HTML - First convert tags that produce a line break to carriage returns
            msgtext = self.htmlmsgtext.replace('</br>',"\r").replace('<br />',"\r").replace('</p>',"\r")
            # Then strip all the other tags out
            msgtext = self.strip_tags(msgtext)

            # necessary mimey stuff
            msg = MIMEMultipart()
            msg.preamble = ''
            msg.epilogue = ''

            body = MIMEMultipart('alternative')
            body.attach(MIMEText(msgtext))
            body.attach(MIMEText(self.htmlmsgtext, 'html'))
            msg.attach(body)

            if 'attachments' in globals() and len('attachments') > 0: # are there attachments?
                for filename in attachments:
                    f = filename
                    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)

            msg.add_header('From', fromaddr)
            msg.add_header('To', toaddr)
            msg.add_header('Subject', msgsubject)
            msg.add_header('Reply-To', replyto)

            # The actual email sendy bits
            server = smtplib.SMTP(host)
            server.set_debuglevel(False) # set to True for verbose output
            try:
                    # gmail expect tls
                server.starttls()
                server.login(self.username,self.password)
                server.sendmail(msg['From'], [msg['To']], msg.as_string())
                print 'Email sent'
                server.quit() # bye bye
            except:
                # if tls is set for non-tls servers you would have raised an exception, so....
                server.login(username,password)
                server.sendmail(msg['From'], [msg['To']], msg.as_string())
                print 'Email sent'
                server.quit() # sbye bye        
        except:
            print ('Email NOT sent to %s successfully. %s ERR: %s %s %s ', str(toaddr), 'tete', str(sys.exc_info()[0]), str(sys.exc_info()[1]), str(sys.exc_info()[2]) )
Example #30
0
def mail_password(u, context=None, reset=False):
    "Send password by email"
    if not u['email']:
        return

    u['url'] = context.ScoURL()

    txt = """
Bonjour %(prenom)s %(nom)s,

""" % u
    if reset:
        txt += """
votre mot de passe ScoDoc a été ré-initialisé.

Le nouveau mot de passe est:  %(passwd)s
Votre nom d'utilisateur est %(user_name)s

Vous devrez changer ce mot de passe lors de votre première connexion 
sur %(url)s
""" % u
    else:
        txt += """
vous avez été déclaré comme utilisateur du logiciel de gestion de scolarité ScoDoc.

Votre nom d'utilisateur est %(user_name)s
Votre mot de passe est: %(passwd)s

Le logiciel est accessible sur: %(url)s

Vous êtes invité à changer ce mot de passe au plus vite (cliquez sur
votre nom en haut à gauche de la page d'accueil).
""" % u

    txt += """
        
ScoDoc est un logiciel libre développé à l'Université Paris 13 par Emmanuel Viennet.
Pour plus d'informations sur ce logiciel, voir %s

""" % SCO_WEBSITE
    msg = MIMEMultipart()
    if reset:
        msg['Subject'] = Header( 'Mot de passe ScoDoc',  SCO_ENCODING )
    else:
        msg['Subject'] = Header( 'Votre accès ScoDoc',  SCO_ENCODING )
    msg['From'] = context.get_preference('email_from_addr')
    msg['To'] = u['email']
    msg.epilogue = ''
    txt = MIMEText( txt, 'plain', SCO_ENCODING )
    msg.attach(txt)
    context.sendEmail(msg)
Example #31
0
    def send_email(self, context, request, receipt):
        title = context.Title()
        description = context.Description()
        body_html =  u'<html><div class="mailcontent"><h1 class="documentFirstHeading">' + title.decode('utf-8') + u'</h1><div class="documentDescription description">' + description.decode('utf-8') + u'</div>' + context.text.output + u'</div></html>'

        #for 'non HTML mail clients'
        transforms = api.portal.get_tool(name='portal_transforms')
        stream = transforms.convertTo('text/plain', body_html, mimetype='text/html')
        body_plain = stream.getData().strip()

        messages = IStatusMessage(self.request)

        # ready to create multipart mail
        try:
            mailhost = api.portal.get_tool(name='MailHost')
            # discovered that plone api might do this better
            # plone.api.portal.send_email , maybe
            outer = MIMEMultipart('alternative')
            outer['To'] = receipt
            outer['From'] = api.portal.get_registry_record('plone.email_from_address')
            outer['Subject'] = title
            outer.epilogue = ''

            # Attach text part
            text_part = MIMEText(body_plain, 'plain', _charset='UTF-8')

            # Attach html part with images
            html_part = MIMEMultipart('related')
            html_text = MIMEText(body_html, 'html', _charset='UTF-8')
            html_part.attach(html_text)

            # Add images to the message
            #for image in issue_data['images_to_attach']:
            #    html_part.attach(image)
            outer.attach(text_part)
            outer.attach(html_part)

            mailhost.send(outer.as_string())

            messages.add(_("sent_mail_message",  default=u"Sendt til $email",
                                                 mapping={'email': receipt },
                                                 ),
                                                 type="info")

        except:
            messages.add(_("cant_send_mail_message",
                                                 default=u"Kunne ikke sende til $email",
                                                 mapping={'email': receipt },
                                                 ),
                                                 type="warning")
Example #32
0
def notify_mail(msg):
	mail_obj = MIMEMultipart()
	mail_obj['Subject'] = EMAIL_SUBJECT
	mail_obj['From'] = private.mail_from_addr
	mail_obj['To'] = listToStr(private.get_mail_list())
	mail_obj.preamble = "This is a multi-part message in MIME format."
	mail_obj.epilogue = ''
	msg_txt = MIMEText(msg.replace("\n", "<br>"))
	msg_txt.replace_header('Content-Type', 'text/html; charset="big5"')
	mail_obj.attach(msg_txt)
	msg_body = mail_obj.as_string()
	smtpObj = smtplib.SMTP(private.mail_server_addr)
	smtpObj.sendmail(private.mail_from_addr, private.get_mail_list(), msg_body)
	smtpObj.quit()
Example #33
0
def notify_mail(msg):
    mail_obj = MIMEMultipart()
    mail_obj['Subject'] = EMAIL_SUBJECT
    mail_obj['From'] = private.mail_from_addr
    mail_obj['To'] = listToStr(private.get_mail_list())
    mail_obj.preamble = "This is a multi-part message in MIME format."
    mail_obj.epilogue = ''
    msg_txt = MIMEText(msg.replace("\n", "<br>"))
    msg_txt.replace_header('Content-Type', 'text/html; charset="big5"')
    mail_obj.attach(msg_txt)
    msg_body = mail_obj.as_string()
    smtpObj = smtplib.SMTP(private.mail_server_addr)
    smtpObj.sendmail(private.mail_from_addr, private.get_mail_list(), msg_body)
    smtpObj.quit()
Example #34
0
def emailHtml(to, subject, message):
    toList, to = processTo(to)
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['To'] = to
    msg['From'] = fromEmail
    msg['Date'] = formatdate()
    msg.preamble = 'You are not using a MIME-aware reader\n'
    msg.epilogue = ''

    #add the main message
    msg.attach(MIMEText(message))

    rawEmail(toList, msg.as_string())
Example #35
0
def emailHtml(to, subject, message):
    toList, to = processTo(to)
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['To'] = to
    msg['From'] = fromEmail
    msg['Date'] = formatdate()
    msg.preamble = 'You are not using a MIME-aware reader\n'
    msg.epilogue = ''

    #add the main message
    msg.attach(MIMEText(message))
    
    rawEmail(toList, msg.as_string())
Example #36
0
	def httprequest(self, postdata):
		if not self.anubisURL.startswith("http://"):
			raise "Invalid URL, only http:// URLs are allowed: url='%s'" % (self.anubisURL)
		if  not postdata:
			raise "Invalid/No POST data supplied: postdata='%s'" % (postdata)

		headers = {}
		headers["Content-Type"] = "multipart/form-data"
		message = MIMEMultipart(_subtype="form-data")
		### notification element
		part = MIMEText(None)
		part.set_payload(postdata["notification"], "us-ascii")
		part.add_header("Content-Disposition", "form-data", name="notification")
		message.attach(part)
		### email element
		part = MIMEText(None)
		part.set_payload(postdata["email"], "us-ascii")
		part.add_header("Content-Disposition", "form-data", name="email")
		message.attach(part)
		### type element
		part = MIMEText(None)
		part.set_payload(postdata["analysisType"], "us-ascii")
		part.add_header("Content-Disposition", "form-data", name="analysisType")
		message.attach(part)
		### file data element
		part = MIMEBase('application', "octet-stream")
		part.set_payload(postdata['executable']['content'])
		### Add content-disposition header.
		dispHeaders = postdata["executable"].get("headers", {})
		part.add_header("Content-Disposition", "form-data", name="executable", filename=postdata["executable"]["filename"])
		for dhName, dhValue in dispHeaders:
			part.add_header(dhName, dhValue)
		message.attach(part)
		message.epilogue = ""
		headerBlock, body = message.as_string().split("\n\n",1)
		for hName, hValue in message.items():
			headers[hName] = hValue
		### Make the HTTP request and get the response.
		### Precondition: 'url', 'method', 'headers', 'body' are all setup properly.
		scheme, netloc, path, parameters, query, fragment = urlparse.urlparse(self.anubisURL)
		if parameters or query or fragment:
			raise "Unexpected URL: parameters=%r, query=%r, fragment=%r" % (parameters, query, fragment)
		try:
			conn = httplib.HTTPConnection(netloc)
			conn.request("POST", path, body, headers)
			response = conn.getresponse()
		except socket.error, e:
			response = ConnRes(404, e)
def notify_mail(project, tsp):
	msg = "FACTORY ALERT!!! Project: %s, TSP: %s" % (project, tsp)
	print msg
	mail_obj = MIMEMultipart()
	mail_obj['Subject'] = EMAIL_SUBJECT
	mail_obj['From'] = EMAIL_FROM
	mail_obj['To'] = listToStr(EMAIL_RECEIVERS)
	mail_obj.preamble = "This is a multi-part message in MIME format."
	mail_obj.epilogue = ''
	msg_txt = MIMEText(msg)
	msg_txt.replace_header('Content-Type', 'text/html; charset="big5"')
	mail_obj.attach(msg_txt)
	msg_body = mail_obj.as_string()
	smtpObj = smtplib.SMTP('relay-b.pegatroncorp.com')
	smtpObj.sendmail(EMAIL_FROM, EMAIL_RECEIVERS, msg_body)
	smtpObj.quit()
Example #38
0
def notify_mail(project, tsp):
    msg = "FACTORY ALERT!!! Project: %s, TSP: %s" % (project, tsp)
    print msg
    mail_obj = MIMEMultipart()
    mail_obj['Subject'] = EMAIL_SUBJECT
    mail_obj['From'] = EMAIL_FROM
    mail_obj['To'] = listToStr(EMAIL_RECEIVERS)
    mail_obj.preamble = "This is a multi-part message in MIME format."
    mail_obj.epilogue = ''
    msg_txt = MIMEText(msg)
    msg_txt.replace_header('Content-Type', 'text/html; charset="big5"')
    mail_obj.attach(msg_txt)
    msg_body = mail_obj.as_string()
    smtpObj = smtplib.SMTP('relay-b.pegatroncorp.com')
    smtpObj.sendmail(EMAIL_FROM, EMAIL_RECEIVERS, msg_body)
    smtpObj.quit()
Example #39
0
def send_mail(to, subject, text, attach):
    ###
    if settings.DEBUG:
        logger.debug(u"\n{}\n{}\n{}\n".format(to, subject, text))
        return
    ###
    try:
        msg = MIMEMultipart('related')
        organization = settings.MAIL_SENDER_ORGANIZATION
        mailer = settings.MAIL_SENDER_MAILER
        msg['Message-ID'] = msgid()
        msg['Organization'] = make_header([(organization, 'UTF-8')])
        msg['X-Mailer'] = make_header([(mailer, 'UTF-8')])
        msg['From'] = make_header([(mailer, 'UTF-8'), ('<' + settings.MAIL_SENDER_SENDER + '>', 'us-ascii')])
        msg['To'] = make_header([(to, 'us-ascii')])
        msg['Subject'] = make_header([(subject, 'UTF-8')])
        msg.preamble = "This is a multi-part message in MIME format."
        msg.epilogue = "End of message"
        # alternative part
        msgAlternative = MIMEMultipart('alternative')
        msg.attach(msgAlternative)
        msgText = MIMEText(text, '', 'utf-8')
        msgAlternative.attach(msgText)
        # html part
        to_attach = MIMEText(text.encode('utf-8'), 'html', 'utf-8')
        msgAlternative.attach(to_attach)

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

        mailServer = smtplib.SMTP(settings.MAIL_SENDER_SERVER, settings.MAIL_SENDER_PORT)
        mailServer.ehlo()
        mailServer.starttls()
        mailServer.ehlo()
        mailServer.login(settings.MAIL_SENDER_USER, settings.MAIL_SENDER_PASSWORD)
        mailServer.sendmail(settings.MAIL_SENDER_SENDER, to, msg.as_string())
        # Should be mailServer.quit(), but that crashes...
        mailServer.close()
    except Exception as e:
        logger.error(u'\n\nMessage to "{}" with subject "{}" was not sended\nException message: "{}"\n'.format(to, subject, e.message))
        return
Example #40
0
def smtp_notify (event_type, description, content=None):
    """E-Mail Notification"""

    # Create the container (outer) email message.
    msg = MIMEMultipart('related')
    msg['From'] = config.get('dbAlerter','smtp_from')
    msg['To'] = config.get('dbAlerter','smtp_to')
    msg.preamble = 'Notification for event - ' + event_type

    # Guarantees the message ends in a newline
    msg.epilogue = ''

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

    msg_text = MIMEText('This message was sent from the dbAlerter host (' + socket.gethostname() + ") to notify you that the following event has occured:\n\n" + event_type + ' - ' + description + "\n\nIf you are not the intended recipient of this notification please contact " + parseaddr(config.get('dbAlerter','smtp_from'))[1] + '.')
    msg_alt.attach(msg_text)

    if (content is None):
        msg['Subject'] = event_type + ' on ' + socket.gethostname()
        # We reference the image in the IMG SRC attribute by the ID we give it below
        msg_text = MIMEText('<a href="http://www.wave2.org/w2wiki/dbalerter"><img src="cid:dbalerterlogo"></a><p>This message was sent from the <a href="http://www.wave2.org/w2wiki/dbalerter">dbAlerter</a> host (<b>' + socket.gethostname() + '</b>) to notify you that the following event has occured:</p><b><i>' + event_type + '</i></b> - ' + description + '<p>If you are not the intended recipient of this notification please contact <b><a href="mailto:' + parseaddr(config.get('dbAlerter','smtp_from'))[1] + '">' + parseaddr(config.get('dbAlerter','smtp_from'))[1] + '</a></b>.', 'html')

    else:
        msg['Subject'] = event_type + ' - ' + description
        msg_text = MIMEText('<a href="http://www.wave2.org/w2wiki/dbalerter"><img src="cid:dbalerterlogo"></a><p>This message was sent from the <a href="http://www.wave2.org/w2wiki/dbalerter">dbAlerter</a> host (<b>' + socket.gethostname() + '</b>) with the following information:</p><pre>' + content + '</pre><p>If you are not the intended recipient of this notification please contact <b><a href="mailto:' + parseaddr(config.get('dbAlerter','smtp_from'))[1] + '">' + parseaddr(config.get('dbAlerter','smtp_from'))[1] + '</a></b>.', 'html')

    msg_alt.attach(msg_text)

    # This example assumes the image is in the current directory
    fp = resource_stream(__name__, 'images/dbAlerter.jpg')
    msg_image = MIMEImage(fp.read())
    fp.close()

    # Define the image's ID as referenced above
    msg_image.add_header('Content-ID', '<dbalerterlogo>')
    msg.attach(msg_image)
    # Send the email via our own SMTP server.
    s = smtplib.SMTP()
    s.connect(config.get('dbAlerter', 'smtp_server'))
    s.sendmail(config.get('dbAlerter', 'smtp_from'), config.get('dbAlerter', 'smtp_to'), msg.as_string())
    s.close()
    log_notify(event_type, description, 'Email')
    def generate(self, fp):
        msg = MIMEMultipart(_subtype='related')
        msg['Subject'] = 'archived'
        msg.epilogue = ''   # Guarantees the message ends in a newline

        for res in self.resource_list:
            if '/' in res.ctype_actual:
                maintype, subtype = res.ctype_actual.split('/',1)
            else:
                maintype, subtype = res.ctype_actual, ''
            part = MIMENonMultipart(maintype, subtype)
            part.set_payload(res.data)
            part['content-location'] = res.uri
            Encoders.encode_base64(part)
            msg.attach(part)

        # generate the MIME message
        Generator(fp, False).flatten(msg)
def send_mail(email, body): 
    # Create the enclosing (outer) message
    outer = MIMEMultipart()
    outer['Subject']= 'Application error log'
    outer['To']= email
    #outer['CC']= email2
    outer['From']= '*****@*****.**'
    outer.preamble = '\n' 
    # To guarantee the message ends with a newline
    outer.epilogue =''  
    # Note: we should handle calculating the charset
    msg= MIMEText(body) 
    # Message body
    outer.attach(msg) 
    text = outer.as_string() 
    MAIL = "/usr/sbin/sendmail"
    p = os.popen("%s -t" % MAIL, 'w')
    p.write(text)
    p.close() 
Example #43
0
def send_email(filename):
    msgsubject = 'Workout from Rowsberry Pi'
    htmlmsgtext = """This is a workout recorded with Rowsberry Pi</br>
                     Yup. Yup. Yup.</br>"""
    msgtext = htmlmsgtext.replace('<b>', '').replace('</b>', '').replace(
        '<br>', "\r").replace('</br>', "\r").replace('<br/>',
                                                     "\r").replace('</a>', '')
    msgtext = re.sub('<.*?>', '', msgtext)

    msg = MIMEMultipart()
    msg.preamble = 'This is a multi-part message in MIME format.\n'
    msg.epilogue = ''

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

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

    msg.add_header('From', email_fromaddress)
    msg.add_header('To', email_recipients)
    msg.add_header('Subject', msgsubject)

    # The actual email sendy bits
    server = smtplib.SMTP('%s:%s' % (email_host, email_port))
    server.set_debuglevel(True)
    if email_use_tls:
        server.starttls()
        server.login(email_host_user, email_host_password)

    if not isinstance(email_recipients, list):
        email_recipients = [email_recipients]
    server.sendmail(msg['From'], email_recipients, msg.as_string())

    server.quit()  #bye bye
Example #44
0
    def prepare_email_message(self):
        plain = self.plain
        html = self.html
        if not plain and not html:
            return None

        # We definitely want unicode at this point.
        plain = utils.su(plain)
        html = utils.su(html)

        # We must choose the body charset manually.  Note that the
        # goal and effect of this loop is to determine the
        # body_charset.
        for body_charset in 'US-ASCII', utils.get_charset(), 'UTF-8':
            try:
                plain.encode(body_charset)
                html.encode(body_charset)
            except UnicodeEncodeError:
                pass
            else:
                break
        # Encoding should work now; let's replace errors just in case.
        plain = plain.encode(body_charset, 'replace')
        html = html.encode(body_charset, 'xmlcharrefreplace')

        text_part = MIMEText(plain, 'plain', body_charset)
        html_part = MIMEText(html, 'html', body_charset)

        # No sense in sending plain text and html when we only have
        # one of those:
        if not plain:
            return html_part
        if not html:
            return text_part

        # Okay, we send both plain text and html
        email_msg = MIMEMultipart('alternative')
        email_msg.epilogue = ''
        email_msg.attach(text_part)
        email_msg.attach(html_part)
        return email_msg
Example #45
0
    def prepare_email_message(self):
        plain = self.plain
        html = self.html
        if not plain and not html:
            return None

        # We definitely want unicode at this point.
        plain = utils.su(plain)
        html = utils.su(html)

        # We must choose the body charset manually.  Note that the
        # goal and effect of this loop is to determine the
        # body_charset.
        for body_charset in 'US-ASCII', utils.get_charset(), 'UTF-8':
            try:
                plain.encode(body_charset)
                html.encode(body_charset)
            except UnicodeEncodeError:
                pass
            else:
                break
        # Encoding should work now; let's replace errors just in case.
        plain = plain.encode(body_charset, 'replace')
        html = html.encode(body_charset, 'xmlcharrefreplace')

        text_part = MIMEText(plain, 'plain', body_charset)
        html_part = MIMEText(html, 'html', body_charset)

        # No sense in sending plain text and html when we only have
        # one of those:
        if not plain:
            return html_part
        if not html:
            return text_part

        # Okay, we send both plain text and html
        email_msg = MIMEMultipart('alternative')
        email_msg.epilogue = ''
        email_msg.attach(text_part)
        email_msg.attach(html_part)
        return email_msg
Example #46
0
def mail_bulletin(context, formsemestre_id, I, pdfdata, filename):
    """Send bulletin by email to etud
    If bul_mail_list_abs pref is true, put list of absences in mail body (text).
    """
    etud = I['etud']
    webmaster = context.get_preference('bul_mail_contact_addr', formsemestre_id)
    dept = unescape_html(context.get_preference('DeptName',formsemestre_id))
    copy_addr = context.get_preference('email_copy_bulletins',formsemestre_id)            
    intro_mail = context.get_preference('bul_intro_mail', formsemestre_id)
    
    if intro_mail:
        hea = intro_mail % { 'nomprenom' : etud['nomprenom'], 'dept':dept, 'webmaster':webmaster }
    else:
        hea = ''

    if context.get_preference('bul_mail_list_abs'):
        hea += '\n\n' + sco_abs_views.ListeAbsEtud(context,
                                                   etud['etudid'], with_evals=False, format='text')
    
    msg = MIMEMultipart()
    subj = Header( 'Relevé de notes de %s' % etud['nomprenom'],  SCO_ENCODING )
    recipients = [ etud['email'] ] 
    msg['Subject'] = subj
    msg['From'] = context.get_preference('email_from_addr',formsemestre_id)
    msg['To'] = ' ,'.join(recipients)
    if copy_addr:
        msg['Bcc'] = copy_addr.strip()
    # Guarantees the message ends in a newline
    msg.epilogue = ''
    # Text
    txt = MIMEText( hea, 'plain', SCO_ENCODING )
    # log('hea:\n' + hea)
    msg.attach(txt)
    # Attach pdf
    att = MIMEBase('application', 'pdf')
    att.add_header('Content-Disposition', 'attachment', filename=filename)
    att.set_payload( pdfdata )
    Encoders.encode_base64(att)
    msg.attach(att)
    log('mail bulletin a %s' % msg['To'] )
    context.sendEmail(msg)
Example #47
0
def makemail(cfg, files, bodyfields):
    ret = MIMEMultipart()
    bodystr = ''.join(map(lambda (k,v) : '%s : %s\n' % (k,v), bodyfields.iteritems()))
    ret.attach(MIMEText(bodystr))
    seen = { }

    for filename in files:
        if seen.has_key(filename):
            continue
        seen[filename] = True
        f = open(filename, 'r')
        msg = MIMEText(f.read(), 'plain', 'iso8859-1')
        f.close()
        msg.add_header('Content-Disposition', 'attachment', filename=os.path.split(filename)[1])
        ret.attach(msg)
        ret['Subject'] = 'Automatically generated Marvin submission'
        ret['From'] = cfg.get('user', 'email')
        ret['To'] = cfg.get('kattis', 'email')
        # Guarantees ending newline
        ret.epilogue=''
        return ret
Example #48
0
def makemail(cfg, files, bodyfields):
	ret = MIMEMultipart()
	bodystr = ''.join(map(lambda (k,v) : '%s : %s\n' % (k,v), bodyfields.iteritems()))
	ret.attach(MIMEText(bodystr))
	seen = { }

	for filename in files:
		if seen.has_key(filename):
			continue
		seen[filename] = True
		f = open(filename, 'r')
		msg = MIMEText(f.read(), 'plain', 'iso8859-1')
		f.close()
		msg.add_header('Content-Disposition', 'attachment', filename=os.path.split(filename)[1])
		ret.attach(msg)
	ret['Subject'] = 'Automatically generated Marvin submission'
	ret['From'] = cfg.get('user', 'email')
	ret['To'] = cfg.get('kattis', 'email')
	# Guarantees ending newline
	ret.epilogue=''
	return ret
def emailEntries(from_addr, to_addr, subj, smtp_host, entries):
    """
    Given a from address, to address, a subject template, SMTP host,
    and a list of entries, construct an email message via template for
    each entry and send it off using the given header values.
    """
    for entry in entries:
        
        # Build a subject line for the current feed entry.
        curr_subj = subj % entry
        
        # Begin building the email message.
        msg = MIMEMultipart()
        msg['To']      = to_addr
        msg['From']    = from_addr
        msg['Subject'] = curr_subj
        msg.preamble   = "You would not see this in a MIME-aware mail reader.\n"
        msg.epilogue   = ""

        # Generate a plain text alternative part.
        plain_text = """
        This email contains entries from your subscribed feeds in HTML.
        """
        part = MIMEText(plain_text, "plain", UNICODE_ENC)
        msg.attach(part)

        # Generate the aggregate HTML page, read in the HTML data, attach it
        # as another part of the email message.
        out = []
        out.append(FEED_HDR_TMPL % entry)
        out.append(ENTRY_TMPL % entry)
        html_text = PAGE_TMPL % "".join(out)
        part = MIMEText(html_text, "html", UNICODE_ENC)
        msg.attach(part)

        # Finally, send the whole thing off as an email message.
        print "Sending email '%s' to '%s'" % (curr_subj, to_addr)
        s = smtplib.SMTP(smtp_host)
        s.sendmail(from_addr, to_addr, msg.as_string())
        s.close()
def emailEntries(from_addr, to_addr, subj, smtp_host, entries):
    """
    Given a from address, to address, a subject template, SMTP host,
    and a list of entries, construct an email message via template for
    each entry and send it off using the given header values.
    """
    for entry in entries:

        # Build a subject line for the current feed entry.
        curr_subj = subj % entry

        # Begin building the email message.
        msg = MIMEMultipart()
        msg['To'] = to_addr
        msg['From'] = from_addr
        msg['Subject'] = curr_subj
        msg.preamble = "You would not see this in a MIME-aware mail reader.\n"
        msg.epilogue = ""

        # Generate a plain text alternative part.
        plain_text = """
        This email contains entries from your subscribed feeds in HTML.
        """
        part = MIMEText(plain_text, "plain", UNICODE_ENC)
        msg.attach(part)

        # Generate the aggregate HTML page, read in the HTML data, attach it
        # as another part of the email message.
        out = []
        out.append(FEED_HDR_TMPL % entry)
        out.append(ENTRY_TMPL % entry)
        html_text = PAGE_TMPL % "".join(out)
        part = MIMEText(html_text, "html", UNICODE_ENC)
        msg.attach(part)

        # Finally, send the whole thing off as an email message.
        print "Sending email '%s' to '%s'" % (curr_subj, to_addr)
        s = smtplib.SMTP(smtp_host)
        s.sendmail(from_addr, to_addr, msg.as_string())
        s.close()
Example #51
0
def send_email(addresses, host, port, from_address, subject, html_email,
               plain_email, avatars, tweet_images):
    password = raw_input('Password: '******'related')
    msgRoot['Subject'] = subject
    msgRoot['From'] = from_address
    msgRoot['To'] = ', '.join(addresses)
    msgRoot.epilogue = ''

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

    msgText = MIMEText(plain_email.encode('utf-8'))
    msgAlternative.attach(msgText)

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

    for avatar in avatars:
        with open("{0}_av".format(avatar), 'rb') as fp:
            msgImage = MIMEImage(fp.read())
            msgImage.add_header('Content-ID', '<{0}_av>'.format(avatar))
            msgRoot.attach(msgImage)
    for tweet_image in tweet_images:
        with open(tweet_image, 'rb') as fp:
            msgImage = MIMEImage(fp.read())
            msgImage.add_header('Content-ID', '<{0}>'.format(tweet_image))
            msgRoot.attach(msgImage)
    with open("plone-logo.png", 'rb') as fp:
        msgImage = MIMEImage(fp.read())
        msgImage.add_header('Content-ID', '<plone-logo.png>')
        msgRoot.attach(msgImage)    

    session = smtplib.SMTP(host, port)
    session.starttls()
    session.login(from_address, password)
    session.sendmail(from_address, addresses, msgRoot.as_string())
    session.quit()
Example #52
0
    def add_attachment(self, path):
        #Create a multipart message and each attachment gets a part
        if not self.email.is_multipart():
            newemail = MIMEMultipart()
            newemail['Subject'] = self.email['Subject']
            newemail['To'] = self.email['To']
            newemail['From'] = self.email['From']
            newemail.preamble = 'There are attachments\n'
            newemail.epilogue = ''
            self.email = newemail

        f = File.File(path)
        filename = f.get_filename()
        mt = f.get_mimetype()
        maintype, subtype = mt.split('/', 1)
        if maintype == 'text':
            fp = open(path)
            #We should handle calculating the charset
            msg = MIMEText(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'image':
            fp = open(path, 'rb')
            msg = MIMEImage(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'audio':
            fp = open(path, 'rb')
            msg = MIMEAudio(fp.read(), _subtype=subtype)
            fp.close()
        else:
            fp = open(path, 'rb')
            msg = MIMEBase('application', 'octet-stream')
            msg.set_payload(fp.read())
            fp.close()
            # Encode the payload using Base64
            Encoders.encode_base64(msg)
        # Set the filename parameter
        msg.add_header('Content-Disposition', 'attachment', filename=filename)
        self.email.attach(msg)
        self.attachments.append(path)
Example #53
0
    def send_mail(self, fromaddr, toaddrs, subject, contents, attachments=[]):
        import smtplib
        import mimetypes

        from email import Encoders
        from email.Message import Message
        from email.MIMEBase import MIMEBase
        from email.MIMEMultipart import MIMEMultipart
        from email.MIMEText import MIMEText

        # FIXME: assume that return value is set on all errors..

        # FIXME: raise exceptions on send errors

        msg = MIMEMultipart()
        msg['Subject'] = subject
        msg['From'] = fromaddr
        msg['To'] = ', '.join(toaddrs)

        msg.preamble = contents
        msg.epilogue = ''

        att = MIMEText(contents, 'plain')
        msg.attach(att)

        for subtype, filename in attachments:
            f = open(filename, 'rb')
            att = MIMEBase('application', subtype)
            att.set_payload(f.read())
            Encoders.encode_base64(att)
            att.add_header('Content-Disposition',
                           'attachment',
                           filename=os.path.basename(filename))
            f.close()
            msg.attach(att)

        s = smtplib.SMTP(SMTP_SERVER)
        s.sendmail(fromaddr, toaddrs, msg.as_string())
Example #54
0
def send_report(txtreport, htmlreport):
    if options.emails is None:
        return
    print "sending email to", options.emails
    try:
        sender = '*****@*****.**'
        recipients = options.emails
        subject = ' system-test results'
        message = MIMEMultipart('alternative')
        message['To'] = ', '.join(recipients)
        message['From'] = sender
        message['Subject'] = subject
        #        message.preamble = subject
        message.epilogue = ''
        p1 = MIMEText(txtreport, 'plain')
        p2 = MIMEText(htmlreport, 'html')
        message.attach(p1)
        message.attach(p2)
        session = smtplib.SMTP('localhost')
        session.sendmail(sender, recipients, message.as_string())
        session.quit()
    except smtplib.SMTPException, e:
        print "Couldn't send report.  %s" % e
Example #55
0
def odf2mht(self, odtfile):
    tmpfile = saveodtfile(odtfile)
    self.REQUEST.RESPONSE.setHeader('Content-Type', 'message/rfc822')
    msg = MIMEMultipart('related', type="text/html")
    msg.preamble = 'This is a multi-part message in MIME format.'
    msg.epilogue = ''
    result = odf2xhtml(tmpfile).encode('us-ascii', 'xmlcharrefreplace')
    htmlpart = MIMEText(result, 'html', 'us-ascii')
    htmlpart['Content-Location'] = 'index.html'
    msg.attach(htmlpart)
    z = zipfile.ZipFile(tmpfile)
    for file in z.namelist():
        if file[0:9] == 'Pictures/':
            suffix = file[file.rfind(".") + 1:]
            main, sub = suffices.get(suffix, ('application', 'octet-stream'))
            img = MIMENonMultipart(main, sub)
            img.set_payload(z.read(file))
            img['Content-Location'] = "" + file
            Encoders.encode_base64(img)
            msg.attach(img)
    z.close()
    unlink(tmpfile)
    return msg.as_string()
Example #56
0
def main():

    if not len(sys.argv) == 2:
        print >> sys.stderr, "Usage: ./audreytoo.py /path/to/images/"
        sys.exit(1)

    image_directory = sys.argv[1]

    if not os.path.isdir(image_directory):
        print >> sys.stderr, "%s is not readable.  Aborting." % (
            image_directory)
        sys.exit(1)

    today = date.today()

    # Build Message
    outer = MIMEMultipart()
    outer['Subject'] = 'Picture of the week: %s Edition' % today.strftime(
        "%B %d")
    outer['To'] = ", ".join(TO)
    outer['From'] = FROM
    outer.preamble = 'Picture of the week: %s Edition\n' % today.strftime(
        "%B %d")
    # To guarantee the message ends with a newline.  I stole this from somewhere on the net.
    outer.epilogue = ''

    highpriority = []
    lowpriority = []

    for filename in os.listdir(image_directory):
        if not os.path.isfile(os.path.join(
                image_directory, filename)) or os.path.splitext(
                    filename)[1].lower() not in VALID_FILES:
            continue

        # If the file starts with next-, we'll send that right away.  note that
        # next-01 is a higher priority than next-02, etc.
        if filename.startswith('next-'):
            highpriority.append(filename)
        else:
            lowpriority.append(filename)

    if not len(highpriority) and not len(lowpriority):
        mail_admin("You're all out of pictures. :(")
        sys.exit(1)

    if len(highpriority):
        highpriority.sort()
        filename = highpriority.pop(0)
    else:
        filename = random.choice(lowpriority)

    try:
        path = os.path.join(image_directory, filename)
        fp = open(path, 'rb')
        msg = MIMEImage(fp.read())
        fp.close()

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

        # Now send the message
        s = smtplib.SMTP(SMTP_SERVER)
        s.login(SMTP_USER, SMTP_PASS)
        s.sendmail(FROM, TO, outer.as_string())
        s.close()

        os.remove(path)

        total_remaining = len(highpriority) + len(lowpriority) - 1
        if total_remaining < 10:
            # Total number of pictures is less than 10, give ADMIN a heads up
            mail_admin("Only %s pictures left in the pool" % (total_remaining),
                       "Need more pictures!")
    except:
        mail_admin("Something is broken!",
                   "Output:\n\n%s" % (sys.exc_info()[0]))
Example #57
0
def httprequest(url, postdata={}, headers=None, ssl=False):
    """A urllib.urlopen() replacement for http://... that gets the
    content-type right for multipart POST requests.

    "url" is the http URL to open.
    "postdata" is a dictionary describing data to post. If the dict is
        empty (the default) a GET request is made, otherwise a POST
        request is made. Each postdata item maps a string name to
        either:
        - a string value; or
        - a file part specification of the form:
            {"filename": <filename>,    # file to load content from
             "content": <content>,      # (optional) file content
             "headers": <headers>}      # (optional) headers
          <filename> is used to load the content (can be overridden by
          <content>) and as the filename to report in the request.
          <headers> is a dictionary of headers to use for the part.
          Note: currently the file part content but be US-ASCII text.
    "headers" is an optional dictionary of headers to send with the
        request. Note that the "Content-Type" and "Content-Length"
        headers are automatically determined.

    The current urllib.urlopen() *always* uses:
        Content-Type: application/x-www-form-urlencoded
    for POST requests. This is incorrect if the postdata includes a file
    to upload. If a file is to be posted the post data is:
        Content-Type: multipart/form-data
    
    This returns the response content if the request was successfull
    (HTTP code 200). Otherwise an IOError is raised.

    For example, this invocation:
        url = 'http://www.perl.org/survey.cgi'
        postdata = {
            "name": "Gisle Aas",
            "email": "gisle at aas.no",
            "gender": "M",
            "born": "1964",
            "init": {"filename": "~/.profile"},
        }
   
    Inspiration: Perl's HTTP::Request module.
    http://aspn.activestate.com/ASPN/Reference/Products/ActivePerl/site/lib/HTTP/Request/Common.html
    """
    if not url.startswith("http://"):
        raise "Invalid URL, only http:// URLs are allow: url='%s'" % url

    if not headers:
        headers = {}

    if not postdata:
        method = "GET"
        body = None
    else:
        method = "POST"

        # Determine if require a multipart content-type: 'contentType'.
        for part in postdata.values():
            if isinstance(part, dict):
                contentType = "multipart/form-data"
                break
        else:
            contentType = "application/x-www-form-urlencoded"
        headers["Content-Type"] = contentType

        # Encode the post data: 'body'.
        if contentType == "application/x-www-form-urlencoded":
            body = urllib.urlencode(postdata)
        elif contentType == "multipart/form-data":
            message = MIMEMultipart(_subtype="form-data")
            for name, value in postdata.items():
                if isinstance(value, dict):
                    # Get content.
                    if "content" in value:
                        content = value["content"]
                    else:
                        fp = open(value["filename"], "rb")
                        content = fp.read()

                    part = MIMEBase('application', "octet-stream")
                    part.set_payload(content)
                    #                    Encoders.encode_base64(part)

                    # Add content-disposition header.
                    dispHeaders = value.get("headers", {})
                    if "Content-Disposition" not in dispHeaders:
                        #XXX Should be a case-INsensitive check.
                        part.add_header("Content-Disposition",
                                        "form-data",
                                        name=name,
                                        filename=value["filename"])
                    for dhName, dhValue in dispHeaders:
                        part.add_header(dhName, dhValue)
                else:
                    # Do not use ctor to set payload to avoid adding a
                    # trailing newline.
                    part = MIMEText(None)
                    part.set_payload(value, "us-ascii")
                    part.add_header("Content-Disposition",
                                    "form-data",
                                    name=name)
                message.attach(part)
            message.epilogue = ""  # Make sure body ends with a newline.
            # Split off the headers block from the .as_string() to get
            # just the message content. Also add the multipart Message's
            # headers (mainly to get the Content-Type header _with_ the
            # boundary attribute).
            headerBlock, body = message.as_string().split("\n\n", 1)
            for hName, hValue in message.items():
                headers[hName] = hValue
            #print "XXX ~~~~~~~~~~~~ multi-part body ~~~~~~~~~~~~~~~~~~~"
            #import sys
            #sys.stdout.write(body)
            #print "XXX ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
        else:
            raise "Invalid content-type: '%s'" % contentType

    # Make the HTTP request and get the response.
    # Precondition: 'url', 'method', 'headers', 'body' are all setup properly.
    scheme, netloc, path, parameters, query, fragment = urlparse.urlparse(url)
    if parameters or query or fragment:
        raise "Unexpected URL form: parameters, query or fragment parts "\
              "are not allowed: parameters=%r, query=%r, fragment=%r"\
              % (parameters, query, fragment)

    if ssl:
        conn = httplib.HTTPSConnection(netloc)
    else:
        conn = httplib.HTTPConnection(netloc)
    conn.request(method, path, body, headers)
    response = conn.getresponse()
    return response
def create_email_message(fromaddr,
                         toaddrs,
                         ccaddrs,
                         subject,
                         priority,
                         include_project=False,
                         stack_trace="",
                         comments=""):
    # format a message suitable to be sent to the Roundup bug tracker

    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEText import MIMEText
    from email.MIMEBase import MIMEBase

    message = MIMEMultipart()
    message['Subject'] = "%s [priority=%s]" % (subject, priority)
    message['To'] = ', '.join(toaddrs)
    message['Cc'] = ', '.join(ccaddrs)
    message['From'] = fromaddr
    message.preamble = 'You will not see this in a MIME-aware mail reader.\n'
    message.epilogue = ' '  # To guarantee the message ends with a newline

    # First section is simple ASCII data ...
    m = []
    m.append("Bug Report")
    m.append("==============================")
    m.append("")

    if len(comments) > 0:
        m.append("Comments:")
        m.append("========")
        m.append(comments)
        m.append("")

    if len(stack_trace) > 0:
        m.append("Stack Trace:")
        m.append("===========")
        m.append(stack_trace)
        m.append("")

    msg = MIMEText('\n'.join(m))
    message.attach(msg)

    # Include the log file ...
    if True:
        try:
            log = os.path.join(get_home_directory(), 'envisage.log')
            f = open(log, 'r')
            entries = f.readlines()
            f.close()

            ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/', 1)
            msg = MIMEBase(maintype, subtype)

            msg = MIMEText(''.join(entries))
            msg.add_header(
                'Content-Disposition', 'attachment', filename='logfile.txt')
            message.attach(msg)
        except:
            logger.exception('Failed to include log file with message')

    # Include the environment variables ...
    if True:
        """
        Transmit the user's environment settings as well.  Main purpose is to
        work out the user name to help with following up on bug reports and
        in future we should probably send less data.
        """
        try:
            entries = []
            for key, value in os.environ.items():
                entries.append('%30s : %s\n' % (key, value))

            ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/', 1)
            msg = MIMEBase(maintype, subtype)

            msg = MIMEText(''.join(entries))
            msg.add_header(
                'Content-Disposition',
                'attachment',
                filename='environment.txt')
            message.attach(msg)

        except:
            logger.exception(
                'Failed to include environment variables with message')

# FIXME: no project plugins exist for Envisage 3, yet, and this isn't the right
# way to do it, either. See the docstring of attachments.py.
#    # Attach the project if requested ...
#    if include_project:
#        from attachments import Attachments
#        try:
#            attachments = Attachments(message)
#            attachments.package_any_relevant_files()
#        except:
#            logger.exception('Failed to include workspace files with message')

    return message
Example #59
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)