Beispiel #1
0
class Message(object):
    def __init__(self, from_addr, to_addrs, subject, message,
                 mime="text/plain", charset="utf-8"):
        self.subject = subject
        self.from_addr = from_addr

        if isinstance(to_addrs, types.StringType):
            self.to_addrs = [to_addrs]
        else:
            self.to_addrs = to_addrs

        self.msg = None
        self.__cache = None
        self.message = MIMEText(message, _charset=charset)
        self.message.set_type(mime)

    def attach(self, filename, mime=None, charset=None, content=None):
        base = os.path.basename(filename)
        if content is None:
            fd = open(filename)
            content = fd.read()
            fd.close()
        elif not isinstance(content, types.StringType):
            raise TypeError("Don't know how to attach content: %s" % \
                            repr(content))

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

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

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

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

        self.msg.attach(part)

    def __str__(self):
        return self.__cache or "cyclone email message: not rendered yet"

    def render(self):
        if self.msg is None:
            self.msg = self.message

        self.msg["Subject"] = self.subject
        self.msg["From"] = self.from_addr
        self.msg["To"] = COMMASPACE.join(self.to_addrs)
        self.msg["Date"] = formatdate(localtime=True)

        if self.__cache is None:
            self.__cache = self.msg.as_string()

        return StringIO(self.__cache)
 def create_email(self, subject, content):
     email = MIMEText(content)
     email.set_type('text/plain')
     email.set_param('charset', 'ASCII')
     email['subject'] = subject
     email['From'] = self.fromaddr
     email['To'] = self.toaddrs
     return email
Beispiel #3
0
    def executeBatch(self, notification, signal, targets):
        log.debug("Executing %s action for targets: %s", self.name, targets)
        self.setupAction(notification.dmd)

        data = _signalToContextDict(signal, self.options.get('zopeurl'), notification, self.guidManager)
        if signal.clear:
            log.debug('This is a clearing signal.')
            subject = processTalSource(notification.content['clear_subject_format'], **data)
            body = processTalSource(notification.content['clear_body_format'], **data)
        else:
            subject = processTalSource(notification.content['subject_format'], **data)
            body = processTalSource(notification.content['body_format'], **data)

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

        plain_body = MIMEText(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 = MIMEText(body.replace('\n', '<br />\n'))
            html_body.set_type('text/html')
            email_message_alternative.attach(html_body)

            email_message.attach(email_message_alternative)

        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)
            )
Beispiel #4
0
class Message(object):
    def __init__(self, from_addr, to_addrs, subject, message, mime="text/plain", charset="utf-8"):
        self.subject = subject
        self.from_addr = from_addr
        self.to_addrs = isinstance(to_addrs, types.StringType) and [to_addrs] or to_addrs
  
        self.msg = None
        self.__cache = None
        self.message = MIMEText(message)
        self.message.set_charset(charset)
        self.message.set_type(mime)
  
    def attach(self, filename, mime=None, charset=None, content=None):
        base = os.path.basename(filename)
        if content is None:
            fd = open(filename)
            content = fd.read()
            fd.close()
  
        if not isinstance(content, types.StringType):
            raise TypeError("don't know how to handle content: %s" % type(content))
  
        part = MIMEBase("application", "octet-stream")
        part.set_payload(content)
        Encoders.encode_base64(part)
        part.add_header("Content-Disposition", "attachment; filename=\"%s\"" % base)
  
        if mime is not None:
            part.set_type(mime)
  
        if charset is not None:
            part.set_charset(charset)
  
        if self.msg is None:
            self.msg = MIMEMultipart()
            self.msg.attach(self.message)
  
        self.msg.attach(part)
  
    def __str__(self):
        return self.__cache or "nuswit mail message: not rendered yet"
  
    def render(self):
        if self.msg is None:
            self.msg = self.message
  
        self.msg["Subject"] = self.subject
        self.msg["From"] = self.from_addr
        self.msg["To"] = COMMASPACE.join(self.to_addrs)
        self.msg["Date"] = formatdate(localtime=True)
  
        if self.__cache is None:
            self.__cache = self.msg.as_string()
  
        return StringIO(self.__cache)
Beispiel #5
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()
Beispiel #6
0
def mail(send_from, send_to, subject, text, content_type, files=[],
         server='localhost', port=25, username=None, password=None):
    def _auth(server, port, username, password):
        logging.debug("Attempting to send email via %s:%i using the \
            following credentials (%s:%s)." % (server, port, username,
                                               password))
        smtp = smtplib.SMTP(server, port)
        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()
        smtp.login(username, password)
        smtp.sendmail(username, send_to, msg.as_string())
        smtp.close()

    def _unauth(server, port):
        logging.debug("Attempting to send email via %s:%i" % (server, port))
        smtp = smtplib.SMTP(server, port)
        smtp.sendmail(send_from, send_to, msg.as_string())
        smtp.close()

    assert type(send_to) == list

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

    text = MIMEText(text)
    text.set_type(content_type)
    text.set_param('charset', 'UTF-8')

    msg.attach(text)

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

    if not username and not password:
        _unauth(server, port)
    else:
        _auth(server, port, username, password)
Beispiel #7
0
 def assemble_email(self, exc_data):
     short_html_version, short_extra = self.format_html(
         exc_data, show_hidden_frames=False, show_extra_data=True)
     long_html_version, long_extra = self.format_html(
         exc_data, show_hidden_frames=True, show_extra_data=True)
     text_version = self.format_text(exc_data,
                                     show_hidden_frames=True,
                                     show_extra_data=True)[0]
     msg = MIMEMultipart()
     msg.set_type('multipart/alternative')
     msg.preamble = msg.epilogue = ''
     text_msg = MIMEText(as_str(text_version))
     text_msg.set_type('text/plain')
     text_msg.set_param('charset', 'UTF-8')
     msg.attach(text_msg)
     html_msg = MIMEText(
         as_str(short_html_version) + as_str(''.join(short_extra)))
     html_msg.set_type('text/html')
     html_msg.set_param('charset', 'UTF-8')
     html_long = MIMEText(
         as_str(long_html_version) + as_str(''.join(long_extra)))
     html_long.set_type('text/html')
     html_long.set_param('charset', 'UTF-8')
     msg.attach(html_msg)
     msg.attach(html_long)
     subject = as_str('%s: %s' %
                      (exc_data.exception_type,
                       formatter.truncate(str(exc_data.exception_value))))
     msg['Subject'] = as_str(self.subject_prefix) + subject
     msg['From'] = as_str(self.from_address)
     msg['To'] = as_str(', '.join(self.to_addresses))
     msg['Date'] = formatdate()
     return msg
Beispiel #8
0
 def assemble_email(self, exc_data):
     short_html_version, short_extra = self.format_html(exc_data, show_hidden_frames=False, show_extra_data=True)
     long_html_version, long_extra = self.format_html(exc_data, show_hidden_frames=True, show_extra_data=True)
     text_version = self.format_text(exc_data, show_hidden_frames=True, show_extra_data=True)[0]
     msg = MIMEMultipart()
     msg.set_type("multipart/alternative")
     msg.preamble = msg.epilogue = ""
     text_msg = MIMEText(as_str(text_version))
     text_msg.set_type("text/plain")
     text_msg.set_param("charset", "UTF-8")
     msg.attach(text_msg)
     html_msg = MIMEText(as_str(short_html_version) + as_str("".join(short_extra)))
     html_msg.set_type("text/html")
     html_msg.set_param("charset", "UTF-8")
     html_long = MIMEText(as_str(long_html_version) + as_str("".join(long_extra)))
     html_long.set_type("text/html")
     html_long.set_param("charset", "UTF-8")
     msg.attach(html_msg)
     msg.attach(html_long)
     subject = as_str("%s: %s" % (exc_data.exception_type, formatter.truncate(str(exc_data.exception_value))))
     msg["Subject"] = as_str(self.subject_prefix) + subject
     msg["From"] = as_str(self.from_address)
     msg["To"] = as_str(", ".join(self.to_addresses))
     msg["Date"] = formatdate()
     return msg
 def assemble_email(self, exc_data):
     short_html_version, short_extra = self.format_html(
         exc_data, show_hidden_frames=False, show_extra_data=True)
     long_html_version, long_extra = self.format_html(
         exc_data, show_hidden_frames=True, show_extra_data=True)
     text_version = self.format_text(
         exc_data, show_hidden_frames=True, show_extra_data=True)[0]
     msg = MIMEMultipart()
     msg.set_type('multipart/alternative')
     msg.preamble = msg.epilogue = ''
     text_msg = MIMEText(as_str(text_version))
     text_msg.set_type('text/plain')
     text_msg.set_param('charset', 'UTF-8')
     msg.attach(text_msg)
     html_msg = MIMEText(as_str(short_html_version) + as_str(''.join(short_extra)))
     html_msg.set_type('text/html')
     html_msg.set_param('charset', 'UTF-8')
     html_long = MIMEText(as_str(long_html_version) + as_str(''.join(long_extra)))
     html_long.set_type('text/html')
     html_long.set_param('charset', 'UTF-8')
     msg.attach(html_msg)
     msg.attach(html_long)
     subject = as_str('%s: %s' % (exc_data.exception_type,
                                  formatter.truncate(str(exc_data.exception_value))))
     msg['Subject'] = as_str(self.subject_prefix) + subject
     msg['From'] = as_str(self.from_address)
     msg['To'] = as_str(', '.join(self.to_addresses))
     msg['Date'] = formatdate()
     return msg
Beispiel #10
0
 def assemble_email(self, exc_data):
     short_html_version = self.format_html(
         exc_data, show_hidden_frames=False)
     long_html_version = self.format_html(
         exc_data, show_hidden_frames=True)
     text_version = self.format_text(
         exc_data, show_hidden_frames=False)
     msg = MIMEMultipart()
     msg.set_type('multipart/alternative')
     msg.preamble = msg.epilogue = ''
     text_msg = MIMEText(text_version)
     text_msg.set_type('text/plain')
     text_msg.set_param('charset', 'ASCII')
     msg.attach(text_msg)
     html_msg = MIMEText(short_html_version)
     html_msg.set_type('text/html')
     # @@: Correct character set?
     html_msg.set_param('charset', 'UTF-8')
     html_long = MIMEText(long_html_version)
     html_long.set_type('text/html')
     html_long.set_param('charset', 'UTF-8')
     msg.attach(html_msg)
     msg.attach(html_long)
     subject = '%s: %s' % (exc_data.exception_type,
                        formatter.truncate(str(exc_data.exception_value)))
     msg['Subject'] = self.subject_prefix + subject
     msg['From'] = self.from_address
     msg['To'] = ', '.join(self.to_addresses)
     return msg
 def assemble_email(self, exc_data):
     short_html_version = self.format_html(exc_data, show_hidden_frames=False)[0]
     long_html_version = self.format_html(exc_data, show_hidden_frames=True)[0]
     text_version = self.format_text(exc_data, show_hidden_frames=False)[0]
     msg = MIMEMultipart()
     msg.set_type("multipart/alternative")
     msg.preamble = msg.epilogue = ""
     text_msg = MIMEText(text_version)
     text_msg.set_type("text/plain")
     text_msg.set_param("charset", "ASCII")
     msg.attach(text_msg)
     html_msg = MIMEText(short_html_version)
     html_msg.set_type("text/html")
     # @@: Correct character set?
     html_msg.set_param("charset", "UTF-8")
     html_long = MIMEText(long_html_version)
     html_long.set_type("text/html")
     html_long.set_param("charset", "UTF-8")
     msg.attach(html_msg)
     msg.attach(html_long)
     subject = "%s: %s" % (exc_data.exception_type, formatter.truncate(str(exc_data.exception_value)))
     msg["Subject"] = self.subject_prefix + subject
     msg["From"] = self.from_address
     msg["To"] = ", ".join(self.to_addresses)
     return msg
Beispiel #12
0
 def assemble_email(self, exc_data):
     short_html_version = self.format_html(
         exc_data, show_hidden_frames=False)
     long_html_version = self.format_html(
         exc_data, show_hidden_frames=True)
     text_version = self.format_text(
         exc_data, show_hidden_frames=False)
     msg = MIMEMultipart()
     msg.set_type('multipart/alternative')
     msg.preamble = msg.epilogue = ''
     text_msg = MIMEText(text_version)
     text_msg.set_type('text/plain')
     text_msg.set_param('charset', 'ASCII')
     msg.attach(text_msg)
     html_msg = MIMEText(short_html_version)
     html_msg.set_type('text/html')
     # @@: Correct character set?
     html_msg.set_param('charset', 'UTF-8')
     html_long = MIMEText(long_html_version)
     html_long.set_type('text/html')
     html_long.set_param('charset', 'UTF-8')
     msg.attach(html_msg)
     msg.attach(html_long)
     subject = '%s: %s' % (exc_data.exception_type,
                           formatter.truncate(str(exc_data.exception_value)))
     msg['Subject'] = self.subject_prefix + subject
     msg['From'] = self.from_address
     msg['To'] = ', '.join(self.to_addresses)
     return msg
Beispiel #13
0
    def executeBatch(self, notification, signal, targets):
        log.debug("Executing %s action for targets: %s", self.name, targets)
        self.setupAction(notification.dmd)

        data = _signalToContextDict(signal, self.options.get('zopeurl'),
                                    notification, self.guidManager)
        if signal.clear:
            log.debug('This is a clearing signal.')
            subject = processTalSource(
                notification.content['clear_subject_format'], **data)
            body = processTalSource(notification.content['clear_body_format'],
                                    **data)
        else:
            subject = processTalSource(notification.content['subject_format'],
                                       **data)
            body = processTalSource(notification.content['body_format'],
                                    **data)

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

        #plain_body = MIMEText(self._stripTags(body))
        plain_body = MIMEText(self._stripTags(body),
                              _subtype='plain',
                              _charset='utf-8')
        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 = MIMEText(body.replace('\n', '<br />\n'),
                                 _subtype='html',
                                 _charset='utf-8')
            #html_body = MIMEText(body.replace('\n', '<br />\n'))
            html_body.set_type('text/html')
            email_message_alternative.attach(html_body)

            email_message.attach(email_message_alternative)

            # Attach image

            (zpdir,
             tail) = os.path.split(__file__)  # Get path to this directory
            imFile = zpdir + '/imageFile0.jpg'
            imageFile = open(imFile, 'rb')
            msgImage = MIMEImage(imageFile.read())
            imageFile.close()
            msgImage.add_header('Content-ID', '<image0>')
            email_message.attach(msgImage)

            # Add the trailer images - see and of body_format and clear_body_format
            if signal.clear:
                imFile = zpdir + '/imageFile2.jpg'
                imageFile = open(imFile, 'rb')
                msgImage = MIMEImage(imageFile.read())
                imageFile.close()
                msgImage.add_header('Content-ID', '<image2>')
                email_message.attach(msgImage)
            else:
                imFile = zpdir + '/imageFile1.jpg'
                imageFile = open(imFile, 'rb')
                msgImage = MIMEImage(imageFile.read())
                imageFile.close()
                msgImage.add_header('Content-ID', '<image1>')
                email_message.attach(msgImage)

        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))
Beispiel #14
0
class Message(object):
    """Create new e-mail messages.

    Example::

        msg = mail.Message(
                from_addr="root@localhost",
                to_addrs=["user1", "user2", "user3"],
                subject="Test, 123",
                mime="text/html")
    """
    def __init__(self,
                 from_addr,
                 to_addrs,
                 subject,
                 message,
                 mime="text/plain",
                 charset="utf-8"):
        self.subject = subject
        self.from_addr = from_addr

        if isinstance(to_addrs, types.StringType):
            self.to_addrs = [to_addrs]
        else:
            self.to_addrs = to_addrs

        self.msg = None
        self.__cache = None
        self.message = MIMEText(message, _charset=charset)
        self.message.set_type(mime)

    def attach(self, filename, mime=None, charset=None, content=None):
        """Attach files to this message.

        Example::

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

        It also supports fake attachments::

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

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

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

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

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

        self.msg.attach(part)

    def __str__(self):
        return self.__cache or "cyclone email message: not rendered yet"

    def render(self):
        if self.msg is None:
            self.msg = self.message

        self.msg["Subject"] = self.subject
        self.msg["From"] = self.from_addr
        self.msg["To"] = COMMASPACE.join(self.to_addrs)
        self.msg["Date"] = formatdate(localtime=True)

        if self.__cache is None:
            self.__cache = self.msg.as_string()

        return StringIO(self.__cache)

    def add_header(self, key, value, **params):
        """Adds custom headers to this message.

        Example::

            msg.add_header("X-MailTag", "foobar")
        """
        if self.msg is None:
            self.msg = self.message

        self.msg.add_header(key, value, **params)
Beispiel #15
0
    def send(self, torcpts, ccrcpts):
        from email.MIMEText import MIMEText
        from email.Utils import formatdate, formataddr
        body = self.hdf.render(self.template_name)
        projname = self.config.get('project', 'name')
        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)

        recipients = []
        (toaddrs, recipients) = remove_dup(toaddrs, recipients)
        (ccaddrs, recipients) = remove_dup(ccaddrs, recipients)
        
        if len(recipients) < 1:
            self.env.log.info('no recipient for a ticket notification')
            return

        headers['To'] = ', '.join(toaddrs)
        headers['Cc'] = ', '.join(ccaddrs)
        headers['Date'] = formatdate()
        if not self._charset.body_encoding:
            try:
                dummy = body.encode('ascii')
            except UnicodeDecodeError:
                raise TracError, "CodeReview contains non-Ascii chars. " \
                                 "Please change encoding setting"
        msg = MIMEText(body)
        msg.set_type("text/html")

        del msg['Content-Transfer-Encoding']
        msg.set_charset(self._charset)
        self.add_headers(msg, 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)
Beispiel #16
0
    def send(self, torcpts, ccrcpts):
        from email.MIMEText import MIMEText
        from email.Utils import formatdate, formataddr
        body = self.hdf.render(self.template_name)
        projname = self.config.get('project', 'name')
        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)

        recipients = []
        (toaddrs, recipients) = remove_dup(toaddrs, recipients)
        (ccaddrs, recipients) = remove_dup(ccaddrs, recipients)
        
        if len(recipients) < 1:
            self.env.log.info('no recipient for a ticket notification')
            return

        headers['To'] = ', '.join(toaddrs)
        headers['Cc'] = ', '.join(ccaddrs)
        headers['Date'] = formatdate()
        if not self._charset.body_encoding:
            try:
                dummy = body.encode('ascii')
            except UnicodeDecodeError:
                raise TracError, "CodeReview contains non-Ascii chars. " \
                                 "Please change encoding setting"
        msg = MIMEText(body)
        msg.set_type("text/html")

        del msg['Content-Transfer-Encoding']
        msg.set_charset(self._charset)
        self.add_headers(msg, 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)
Beispiel #17
0
class Message(object):
    """Create new e-mail messages.

    Example::

        msg = mail.Message(
                from_addr="root@localhost",
                to_addrs=["user1", "user2", "user3"],
                subject="Test, 123",
                message="Hello thar!",
                mime="text/html")
    """

    def __init__(self, from_addr, to_addrs, subject, message,
                 mime="text/plain", charset="utf-8"):
        self.subject = subject
        self.from_addr = from_addr

        if isinstance(to_addrs, types.StringType):
            self.to_addrs = [to_addrs]
        else:
            self.to_addrs = to_addrs

        self.msg = None
        self.__cache = None
        self.message = MIMEText(message, _charset=charset)
        self.message.set_type(mime)

    def attach(self, filename, mime=None, charset=None, content=None):
        """Attach files to this message.

        Example::

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

        It also supports fake attachments::

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

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

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

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

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

        self.msg.attach(part)

    def __str__(self):
        return self.__cache or "cyclone email message: not rendered yet"

    def render(self):
        if self.msg is None:
            self.msg = self.message

        self.msg["Subject"] = self.subject
        self.msg["From"] = self.from_addr
        self.msg["To"] = COMMASPACE.join(self.to_addrs)
        self.msg["Date"] = formatdate(localtime=True)

        if self.__cache is None:
            self.__cache = self.msg.as_string()

        return StringIO(self.__cache)

    def add_header(self, key, value, **params):
        """Adds custom headers to this message.

        Example::

            msg.add_header("X-MailTag", "foobar")
        """
        if self.msg is None:
            self.msg = self.message

        self.msg.add_header(key, value, **params)
    def executeBatch(self, notification, signal, targets):
        log.debug("Executing %s action for targets: %s", self.name, targets)
        self.setupAction(notification.dmd)

        data = _signalToContextDict(signal, self.options.get('zopeurl'), notification, self.guidManager)
        if signal.clear:
            log.debug('This is a clearing signal.')
            subject = processTalSource(notification.content['clear_subject_format'], **data)
            body = processTalSource(notification.content['clear_body_format'], **data)
        else:
            subject = processTalSource(notification.content['subject_format'], **data)
            body = processTalSource(notification.content['body_format'], **data)

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

        #plain_body = MIMEText(self._stripTags(body))
        plain_body = MIMEText(self._stripTags(body), _subtype='plain', _charset='utf-8')
        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 = MIMEText(body.replace('\n', '<br />\n'), _subtype='html', _charset='utf-8')
            #html_body = MIMEText(body.replace('\n', '<br />\n'))
            html_body.set_type('text/html')
            email_message_alternative.attach(html_body)

            email_message.attach(email_message_alternative)

            # Attach image

            (zpdir, tail) = os.path.split(__file__)   # Get path to this directory
            imFile = zpdir + '/imageFile0.jpg'
            imageFile = open(imFile, 'rb')
            msgImage = MIMEImage(imageFile.read())
            imageFile.close()
            msgImage.add_header('Content-ID', '<image0>')
            email_message.attach(msgImage)

            # Add the trailer images - see and of body_format and clear_body_format
            if signal.clear:
                imFile = zpdir + '/imageFile2.jpg'
                imageFile = open(imFile, 'rb')
                msgImage = MIMEImage(imageFile.read())
                imageFile.close()
                msgImage.add_header('Content-ID', '<image2>')
                email_message.attach(msgImage)
            else:
                imFile = zpdir + '/imageFile1.jpg'
                imageFile = open(imFile, 'rb')
                msgImage = MIMEImage(imageFile.read())
                imageFile.close()
                msgImage.add_header('Content-ID', '<image1>')
                email_message.attach(msgImage)



        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)
            )