Пример #1
0
def main(args):
  msg1 = Message()
  msg1.set_charset('iso-2022-jp')
  msg1['From'] = Header(u'Yusuke Shinyama <*****@*****.**>', 'iso-2022-jp')
  msg1['To'] = Header(u'きょうから明日です <today@tomorrow>', 'iso-2022-jp')
  msg1['Subject'] = Header(u'ムーミン谷のみなさんへ', 'iso-2022-jp')
  msg1['Date'] = 'Thu, 31 Aug 2004 03:06:09 +0900'
  msg1.set_payload(u'その逆だ!'.encode('iso-2022-jp'), 'iso-2022-jp')
  fp = file(args.pop(0), 'wb')
  fp.write(msg1.as_string(0))
  fp.close()

  msg2 = MIMEMultipart()
  msg2.set_charset('utf-8')
  msg2['From'] = Header(u'えうすけ <*****@*****.**>', 'iso-2022-jp')
  msg2['To'] = Header(u'だれでも <any@one>', 'utf-8')
  msg2['Subject'] = Header(u'何を見てるんだい?', 'iso-2022-jp')
  msg2['Date'] = 'Thu, 29 Feb 2004 19:23:34 +0500'
  text1 = MIMEText(u'ああそうか、\nこれは夢なんだ。'.encode('utf-8'), 'plain', 'utf-8')
  text2 = MIMEText(u'<html><body>\n<strong>HEY!</strong>\n<p>do you wanna feel unconfortably energetic?\n</body></html>', 'html')
  h = Header(u'ふうばあ ばず', 'iso-2022-jp')
  text2.add_header('Content-Disposition', 'attachment', filename=h.encode())
  msg2.set_payload([text1, text2])
  fp = file(args.pop(0), 'wb')
  fp.write(msg2.as_string(0))
  fp.close()

  msg3 = MIMEMultipart()
  msg3['From'] = '=?iso-2022-jp?b?Gy?= \xff\xaa\x88'
  msg3['Subject'] = 'huh?'
  msg3['Date'] = 'Tue, 25 Nov 2008 01:00:09 +0900'
  parts = MIMEMultipart()
  parts.set_payload([MIMEText('part1'), MIMEText('part2')])
  msg4 = Message()
  msg4.set_charset('iso-2022-jp')
  msg4['From'] = Header(u'john doe <*****@*****.**>', 'iso-2022-jp')
  msg4['To'] = Header(u'どこだって? <where@where>', 'iso-2022-jp')
  msg4['Subject'] = Header(u'その先の日本へ', 'iso-2022-jp')
  msg4['Date'] = 'Sun, 31 Aug 2008 12:20:33 +0900'
  msg4.set_payload(u'ししかばう゛ー'.encode('iso-2022-jp'), 'iso-2022-jp')
  msg3.set_payload([parts, MIMEMessage(msg4)])
  fp = file(args.pop(0), 'wb')
  fp.write(msg3.as_string(0))
  fp.close()

  return
Пример #2
0
 def forum_post_as_email(self, forum, post):
     '''Convert a post to email'''
     topic = post.topic
     sre, subject = re.match(r'(Re: )?(.*)',
                             post.subject).groups()
     if subject == '':
         if post.pid != topic.firstpost:
             sre = 'Re: '
         subject = topic.title or 'topic %s' % topic.tid
     subject = (sre or '') + forum.subjectPrefix + subject
     if post.datetime is not None:
         pass
     zauthor,n = re.subn(r'[^-A-Za-z0-9]+','_', post.author)
     fromm = _subst(self.fromPattern, u=zauthor)
     msgid = _subst(self.messageIdPattern, p=post.pid)
     hbody = '<html><body>%s</body></html>' % post.body.encode('utf-8')
     try:
         from email.Message import Message 
         from email.Header import Header
         from email.Utils import formatdate
         # Force quoted-printable for utf-8 instead of base64 (for Thunderbird "View source")
         import email.Charset as cs
         cs.add_charset('utf-8', cs.SHORTEST, cs.QP, 'utf-8')
     except ImportError:
         from email.message import Message
         from email.header import Header
         from email.utils import formatdate
     msg = Message()
     msg.add_header('From', fromm)
     msg.add_header('To', forum.recipient)
     hsubj = Header(subject)
     msg.add_header('Subject', str(hsubj))
     msg.add_header('Message-ID', '<%s>' % msgid)
     if topic.firstpost:
         firstid = _subst(self.messageIdPattern, p=topic.firstpost)
         msg.add_header('In-Reply-To', '<%s>' % firstid)
         msg.add_header('References', '<%s>' % firstid)
     if post.datetime is not None:
         date = formatdate(post.datetime)
         msg.add_header('Date', date)
     msg.set_payload(hbody)
     msg.set_type('text/html')
     msg.set_charset('utf-8')
     return msg.as_string()
Пример #3
0
	s += '<table>'

	# Get rid of HTML and display it
	for field in fields:
		s += '<tr><td>%s</td><td><strong>%s</strong></td></tr>' % (
			field,
			string.replace( cgi.escape( form[field] ), "\n", "<br />\n" )
			)

	s += '</table>'

	msgBody = '%s ( %s ) sent you a message through the Python Community Server:\n\n' % (fromName, fromUrl) + form['msgBody']

	# Now build an RFC-2822 message out of it
	msg = Message()
	msg.set_charset(mailEncoding)
	msg.set_payload(msgBody.decode(documentEncoding).encode(mailEncoding))
	msg['X-User-Agent'] = 'Python Community Server'
	msg['From'] = '%s (%s)' % (
		fromEmail,
		quoteHeader(fromName, documentEncoding, mailEncoding)
	)
	msg['To'] = u.email
	msg['Subject'] = quoteHeader(subject, documentEncoding, mailEncoding)

	try:
		sender = smtplib.SMTP( "localhost", 25 )
		sender.sendmail(
			set.ServerMailTo(),
			u.email,
			msg.as_string(),
Пример #4
0
def sendmail(request, to, subject, text, mail_from=None):
    """ Create and send a text/plain message

    Return a tuple of success or error indicator and message.

    @param request: the request object
    @param to: recipients (list)
    @param subject: subject of email (unicode)
    @param text: email body text (unicode)
    @param mail_from: override default mail_from
    @type mail_from: unicode
    @rtype: tuple
    @return: (is_ok, Description of error or OK message)
    """
    import smtplib, socket
    from email.Message import Message
    from email.Charset import Charset, QP
    from email.Utils import formatdate, make_msgid

    _ = request.getText
    cfg = request.cfg
    mail_from = mail_from or cfg.mail_from
    subject = subject.encode(config.charset)

    # Create a text/plain body using CRLF (see RFC2822)
    text = text.replace(u'\n', u'\r\n')
    text = text.encode(config.charset)

    # Create a message using config.charset and quoted printable
    # encoding, which should be supported better by mail clients.
    # TODO: check if its really works better for major mail clients
    msg = Message()
    charset = Charset(config.charset)
    charset.header_encoding = QP
    charset.body_encoding = QP
    msg.set_charset(charset)

    # work around a bug in python 2.4.3 and above:
    msg.set_payload('=')
    if msg.as_string().endswith('='):
        text = charset.body_encode(text)

    msg.set_payload(text)

    # Create message headers
    # Don't expose emails addreses of the other subscribers, instead we
    # use the same mail_from, e.g. u"Jürgen Wiki <*****@*****.**>"
    address = encodeAddress(mail_from, charset)
    msg['From'] = address
    msg['To'] = address
    msg['Date'] = formatdate()
    msg['Message-ID'] = make_msgid()
    msg['Subject'] = Header(subject, charset)

    if cfg.mail_sendmail:
        # Set the BCC.  This will be stripped later by sendmail.
        msg['BCC'] = ','.join(to)
        # Set Return-Path so that it isn't set (generally incorrectly) for us.
        msg['Return-Path'] = address

    # Send the message
    if not cfg.mail_sendmail:
        try:
            logging.debug("trying to send mail (smtp) via smtp server '%s'" % cfg.mail_smarthost)
            host, port = (cfg.mail_smarthost + ':25').split(':')[:2]
            server = smtplib.SMTP(host, int(port))
            try:
                #server.set_debuglevel(1)
                if cfg.mail_login:
                    user, pwd = cfg.mail_login.split()
                    try: # try to do tls
                        server.ehlo()
                        if server.has_extn('starttls'):
                            server.starttls()
                            server.ehlo()
                            logging.debug("tls connection to smtp server established")
                    except:
                        logging.debug("could not establish a tls connection to smtp server, continuing without tls")
                    logging.debug("trying to log in to smtp server using account '%s'" % user)
                    server.login(user, pwd)
                server.sendmail(mail_from, to, msg.as_string())
            finally:
                try:
                    server.quit()
                except AttributeError:
                    # in case the connection failed, SMTP has no "sock" attribute
                    pass
        except smtplib.SMTPException, e:
            logging.exception("smtp mail failed with an exception.")
            return (0, str(e))
        except (os.error, socket.error), e:
            logging.exception("smtp mail failed with an exception.")
            return (0, _("Connection to mailserver '%(server)s' failed: %(reason)s") % {
                'server': cfg.mail_smarthost,
                'reason': str(e)
            })
Пример #5
0
    def comment(self, text='', username='', time='',
                note=None, use_heading=None,
                REQUEST=None, subject_heading='', message_id=None,
                in_reply_to=None, exclude_address=None, sendmail=1):
        """Add a comment to this page.

        We try to do this efficiently, avoiding re-rendering the full page
        if possible.  The comment will be mailed out to any subscribers.
        If auto-subscription is in effect, we subscribe the poster to this
        page.

        subject_heading is so named to avoid a clash with some existing
        zope subject attribute.  note and use_heading are not used and
        kept only for backwards compatibility.
        """
        if not self.checkSufficientId(REQUEST):
            return self.denied(
                _("Sorry, this wiki doesn't allow anonymous edits. Please configure a username in options first."))
        if self.isDavLocked(): return self.davLockDialog()
        # gather info
        oldtext         = self.read()
        text            = text and self.cleanupText(text)
        subject_heading = subject_heading and self.cleanupText(subject_heading)
        if not username:
            username = self.usernameFrom(REQUEST)
            if re.match(r'^(?:\d{1,3}\.){3}\d{1,3}$',username): username = ''
        username        = username and self.tounicode(username)
        firstcomment    = self.messageCount()==0
        # ensure the page comment and mail-out will have the same
        # message-id, and the same timestamp if possible (helps threading
        # & troubleshooting)
        if time: dtime = DateTime(time)
        else:
            dtime = self.ZopeTime()
            time = dtime.rfc822()
        if not message_id: message_id = self.messageIdFromTime(dtime)
        # format this comment as standard rfc2822
        m = Message()
        m.set_charset(self.encoding())
        m.set_payload(self.toencoded(text))
        m['From']       = self.toencoded(username)
        m['Date']       = time
        m['Subject']    = self.toencoded(subject_heading)
        m['Message-ID'] = message_id
        if in_reply_to: m['In-Reply-To'] = in_reply_to
        m.set_unixfrom(self.fromLineFrom(m['From'],m['Date'])[:-1])
        t = self.tounicode(str(m))
        # discard junk comments
        if not (m['Subject'] or m.get_payload()): return
        self.checkForSpam(t)

        # do it
        self.saveRevision()
        # append to the raw source
        t = '\n\n' + t
        self.raw += t
        # and to the _prerendered cache, carefully mimicking a full
        # prerender. This works with current page types at least.
        t = self.pageType().preRenderMessage(self,m)
        if firstcomment: t=self.pageType().discussionSeparator(self) + t
        t = self.pageType().preRender(self,t)
        self.setPreRendered(self.preRendered()+t)
        self.cookDtmlIfNeeded()
        # extras
        self.setLastEditor(REQUEST)
        self.setLastLog(subject_heading)
        if self.autoSubscriptionEnabled(): self.subscribeThisUser(REQUEST)
        self.index_object()
        if REQUEST: REQUEST.cookies['zwiki_username'] = m['From'] # use real from address
        if sendmail:
            self.sendMailToSubscribers(
                m.get_payload(), REQUEST, subject=m['Subject'],
                message_id=m['Message-ID'], in_reply_to=m['In-Reply-To'],
                exclude_address=exclude_address)
        if REQUEST: REQUEST.RESPONSE.redirect(REQUEST['URL1']+'#bottom')
Пример #6
0
def sendmail(request, to, subject, text, mail_from=None):
    """ Create and send a text/plain message

    Return a tuple of success or error indicator and message.

    @param request: the request object
    @param to: recipients (list)
    @param subject: subject of email (unicode)
    @param text: email body text (unicode)
    @param mail_from: override default mail_from
    @type mail_from: unicode
    @rtype: tuple
    @return: (is_ok, Description of error or OK message)
    """
    import smtplib, socket
    from email.Message import Message
    from email.Charset import Charset, QP
    from email.Utils import formatdate, make_msgid

    _ = request.getText
    cfg = request.cfg
    mail_from = mail_from or cfg.mail_from

    logging.debug("send mail, from: %r, subj: %r" % (mail_from, subject))
    logging.debug("send mail, to: %r" % (to, ))

    if not to:
        return (1, _("No recipients, nothing to do"))

    subject = subject.encode(config.charset)

    # Create a text/plain body using CRLF (see RFC2822)
    text = text.replace(u'\n', u'\r\n')
    text = text.encode(config.charset)

    # Create a message using config.charset and quoted printable
    # encoding, which should be supported better by mail clients.
    # TODO: check if its really works better for major mail clients
    msg = Message()
    charset = Charset(config.charset)
    charset.header_encoding = QP
    charset.body_encoding = QP
    msg.set_charset(charset)

    # work around a bug in python 2.4.3 and above:
    msg.set_payload('=')
    if msg.as_string().endswith('='):
        text = charset.body_encode(text)

    msg.set_payload(text)

    # Create message headers
    # Don't expose emails addreses of the other subscribers, instead we
    # use the same mail_from, e.g. u"Jürgen Wiki <*****@*****.**>"
    address = encodeAddress(mail_from, charset)
    msg['From'] = address
    msg['To'] = address
    msg['Date'] = formatdate()
    msg['Message-ID'] = make_msgid()
    msg['Subject'] = Header(subject, charset)
    # See RFC 3834 section 5:
    msg['Auto-Submitted'] = 'auto-generated'

    if cfg.mail_sendmail:
        # Set the BCC.  This will be stripped later by sendmail.
        msg['BCC'] = ','.join(to)
        # Set Return-Path so that it isn't set (generally incorrectly) for us.
        msg['Return-Path'] = address

    # Send the message
    if not cfg.mail_sendmail:
        try:
            logging.debug("trying to send mail (smtp) via smtp server '%s'" %
                          cfg.mail_smarthost)
            host, port = (cfg.mail_smarthost + ':25').split(':')[:2]
            server = smtplib.SMTP(host, int(port))
            try:
                #server.set_debuglevel(1)
                if cfg.mail_login:
                    user, pwd = cfg.mail_login.split()
                    try:  # try to do tls
                        server.ehlo()
                        if server.has_extn('starttls'):
                            server.starttls()
                            server.ehlo()
                            logging.debug(
                                "tls connection to smtp server established")
                    except:
                        logging.debug(
                            "could not establish a tls connection to smtp server, continuing without tls"
                        )
                    logging.debug(
                        "trying to log in to smtp server using account '%s'" %
                        user)
                    server.login(user, pwd)
                server.sendmail(mail_from, to, msg.as_string())
            finally:
                try:
                    server.quit()
                except AttributeError:
                    # in case the connection failed, SMTP has no "sock" attribute
                    pass
        except UnicodeError, e:
            logging.exception("unicode error [%r -> %r]" % (
                mail_from,
                to,
            ))
            return (0, str(e))
        except smtplib.SMTPException, e:
            logging.exception("smtp mail failed with an exception.")
            return (0, str(e))
Пример #7
0
def sendmail(subject, text, to=None, cc=None, bcc=None, mail_from=None):
    """ Create and send a text/plain message

    Return a tuple of success or error indicator and message.

    :param subject: subject of email
    :type subject: unicode
    :param text: email body text
    :type text: unicode
    :param to: recipients
    :type to: list
    :param cc: recipients (CC)
    :type cc: list
    :param bcc: recipients (BCC)
    :type bcc: list
    :param mail_from: override default mail_from
    :type mail_from: unicode

    :rtype: tuple
    :returns: (is_ok, Description of error or OK message)
    """
    import smtplib, socket
    from email.Message import Message
    from email.Charset import Charset, QP
    from email.Utils import formatdate, make_msgid

    cfg = app.cfg
    mail_from = mail_from or cfg.mail_from

    logging.debug("send mail, from: {0!r}, subj: {1!r}".format(mail_from, subject))
    logging.debug("send mail, to: {0!r}".format(to))

    if not to and not cc and not bcc:
        return (1, _("No recipients, nothing to do"))

    subject = subject.encode(config.charset)

    # Create a text/plain body using CRLF (see RFC2822)
    text = text.replace(u'\n', u'\r\n')
    text = text.encode(config.charset)

    # Create a message using config.charset and quoted printable
    # encoding, which should be supported better by mail clients.
    # TODO: check if its really works better for major mail clients
    msg = Message()
    charset = Charset(config.charset)
    charset.header_encoding = QP
    charset.body_encoding = QP
    msg.set_charset(charset)

    # work around a bug in python 2.4.3 and above:
    msg.set_payload('=')
    if msg.as_string().endswith('='):
        text = charset.body_encode(text)

    msg.set_payload(text)

    address = encodeAddress(mail_from, charset)
    msg['From'] = address
    if to:
        msg['To'] = ','.join(to)
    if cc:
        msg['CC'] = ','.join(cc)
    msg['Date'] = formatdate()
    msg['Message-ID'] = make_msgid()
    msg['Subject'] = Header(subject, charset)
    # See RFC 3834 section 5:
    msg['Auto-Submitted'] = 'auto-generated'

    if cfg.mail_sendmail:
        if bcc:
            # Set the BCC.  This will be stripped later by sendmail.
            msg['BCC'] = ','.join(bcc)
        # Set Return-Path so that it isn't set (generally incorrectly) for us.
        msg['Return-Path'] = address

    # Send the message
    if not cfg.mail_sendmail:
        try:
            logging.debug("trying to send mail (smtp) via smtp server '{0}'".format(cfg.mail_smarthost))
            host, port = (cfg.mail_smarthost + ':25').split(':')[:2]
            server = smtplib.SMTP(host, int(port))
            try:
                #server.set_debuglevel(1)
                if cfg.mail_username is not None and cfg.mail_password is not None:
                    try: # try to do tls
                        server.ehlo()
                        if server.has_extn('starttls'):
                            server.starttls()
                            server.ehlo()
                            logging.debug("tls connection to smtp server established")
                    except:
                        logging.debug("could not establish a tls connection to smtp server, continuing without tls")
                    logging.debug("trying to log in to smtp server using account '{0}'".format(cfg.mail_username))
                    server.login(cfg.mail_username, cfg.mail_password)
                server.sendmail(mail_from, (to or []) + (cc or []) + (bcc or []), msg.as_string())
            finally:
                try:
                    server.quit()
                except AttributeError:
                    # in case the connection failed, SMTP has no "sock" attribute
                    pass
        except smtplib.SMTPException as e:
            logging.exception("smtp mail failed with an exception.")
            return (0, str(e))
        except (os.error, socket.error) as e:
            logging.exception("smtp mail failed with an exception.")
            return (0, _("Connection to mailserver '%(server)s' failed: %(reason)s",
                server=cfg.mail_smarthost,
                reason=str(e)
            ))
    else:
        try:
            logging.debug("trying to send mail (sendmail)")
            sendmailp = os.popen(cfg.mail_sendmail, "w")
            # msg contains everything we need, so this is a simple write
            sendmailp.write(msg.as_string())
            sendmail_status = sendmailp.close()
            if sendmail_status:
                logging.error("sendmail failed with status: {0!s}".format(sendmail_status))
                return (0, str(sendmail_status))
        except:
            logging.exception("sendmail failed with an exception.")
            return (0, _("Mail not sent"))

    logging.debug("Mail sent successfully")
    return (1, _("Mail sent successfully"))