Ejemplo n.º 1
0
def createEmailTo(sender_name, sender_email, recipient_name, recipient_email,
                  subject, body, format="plain"):
    """Create an :obj:`email.MIMEText.MIMEtext` instance for an email. This
    method will take care of adding addings a date header and message ID
    to the email, as well as quoting of non-ASCII content.
    """
    if isinstance(body, unicode):
        mail=MIMEText(body.encode("utf-8"), format, "utf-8")
    else:
        mail=MIMEText(body, format)

    if sender_name:
        mail["From"]=emailutils.formataddr((sender_name, sender_email))
    else:
        mail["From"]=sender_email
    if recipient_name:
        mail["To"]=emailutils.formataddr((recipient_name, recipient_email))
    else:
        mail["To"]=recipient_email
    mail["Subject"]=Header(subject.encode("utf-8"), "utf-8")
    mail["Message-Id"]=emailutils.make_msgid()
    mail["Date"]=emailutils.formatdate(localtime=True)
    mail.set_param("charset", "utf-8")

    return mail
Ejemplo n.º 2
0
def createEmailTo(sender_name,
                  sender_email,
                  recipient_name,
                  recipient_email,
                  subject,
                  body,
                  format="plain"):
    """Create an :obj:`email.MIMEText.MIMEtext` instance for an email. This
    method will take care of adding addings a date header and message ID
    to the email, as well as quoting of non-ASCII content.
    """
    if isinstance(body, str):
        mail = MIMEText(body.encode("utf-8"), format, "utf-8")
    else:
        mail = MIMEText(body, format)

    if sender_name:
        mail["From"] = emailutils.formataddr((sender_name, sender_email))
    else:
        mail["From"] = sender_email
    if recipient_name:
        mail["To"] = emailutils.formataddr((recipient_name, recipient_email))
    else:
        mail["To"] = recipient_email
    mail["Subject"] = Header(subject.encode("utf-8"), "utf-8")
    mail["Message-Id"] = emailutils.make_msgid()
    mail["Date"] = emailutils.formatdate(localtime=True)
    mail.set_param("charset", "utf-8")

    return mail
 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
Ejemplo n.º 4
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)
Ejemplo n.º 5
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
Ejemplo n.º 6
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
Ejemplo n.º 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
Ejemplo n.º 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
Ejemplo n.º 9
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
Ejemplo n.º 10
0
 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
Ejemplo n.º 11
0
    def transport(self, data):
        if type(data) != type(''):
            # @todo Add warning that stream is being ignored
            # @todo Assuming that not string means stream.
            a = array.array('c')
            stream_data = data.read(1024)
            while stream_data:
                a.fromstring(stream_data)
                stream_data = data.read(1024)
            data = a.tostring()

        headers = {}
        splitdata = data.split('\r\n\r\n')
        if len(splitdata) > 1:
            headerdata = splitdata[0]
            data = string.join(splitdata[1:], '\r\n\r\n')
            for header in headerdata.split('\r\n'):
                splitheader = header.split(':')
                name = splitheader[0].strip()
                value = string.join(splitheader[1:], ':').strip()
                headers[name] = value

        if self.subtype:
            text_subtype = self.subtype
        else: text_subtype = 'plain'
        if text_subtype == 'plain':
            default_extension = 'txt'
        else:
            default_extension = text_subtype
        if text_subtype != 'xml' and data[:16].strip()[:5] == '<?xml':
            msglog.log('broadway', msglog.types.WARN,
                       'Transporter overriding configured subtype to "xml".')
            text_subtype='xml'
            default_extension = 'xml'
        msg = MIMEText(data, _subtype=text_subtype)
        subject = headers.get('Subject')
        if subject is None or subject == 'None' or subject == '':
            subject = self.subject
        #CSCtg54105
        else:
            if self.subject is not None and self.subject != 'None' and self.subject != '':
                subject = self.subject + ': ' + subject
        if subject:
            msg.add_header('Thread-Topic', subject)
            msg.add_header('Subject', subject)
        msg.add_header('From', self.sender)
        msg.add_header('To', COMMASPACE.join(self._recipients))
        date = headers.get('Date', formatdate(time.time(), True))
        msg.add_header('Date', date)

        message_id = make_msgid()
        if self.as_attachment:
            # @fixme: Make configurable
            default_filename = "%s.%s" % (
                message_id[1:-1].split("@")[0],
                default_extension
                )
            msg.add_header('Content-Disposition', 'attachment',
                           filename=default_filename)
            msg.set_param('name',  default_filename)
        # @fixme: Make configurable
        msg.add_header('Content-Class', 'urn:content-classes:message')
        # @fixme: Make configurable
        msg.add_header('X-Mailer', 'Mediator SMTP Transport')
        msg.add_header('Message-ID', message_id)
        # @fixme: Make configurable
        msg.add_header('Importance', 'normal')
        # @fixme: Make configurable
        msg.add_header('Priority', 'normal')
        msg.preamble = ''
        # To guarantee the message ends with a newline
        msg.epilogue = ''

        smtp = self.SMTP()
        if self.debug:
            smtp.set_debuglevel(self.debug)
        smtp.connect(self.host,self.port,self.timeout)
        if self.custom_domain:
            if not (200 <= smtp.ehlo(self.custom_domain)[0] <= 299):
                (code, resp) = smtp.helo(self.custom_domain)
                if not (200 <= code <= 299):
                    raise smtp.SMTPHeloError(code, resp)
        if self.authenticate:
            try:
                smtp.login(self.username,self.password)
            except smtplib.SMTPAuthenticationError:
                msglog.log('broadway',msglog.types.WARN,
                           'SMTP Authentication failed.' +
                           '  Invalid username/password.')
                raise
        failures = smtp.sendmail(self.sender,self._recipients,
                                 msg.as_string())
        for recipient in failures.keys():
            msglog.log('broadway',msglog.types.WARN,
                       'Error sending mail to %s -> %s' %
                       (recipient,failures[recipient]))
        smtp.close()
Ejemplo n.º 12
0
    def transport(self, data):
        if type(data) != type(''):
            # @todo Add warning that stream is being ignored
            # @todo Assuming that not string means stream.
            a = array.array('c')
            stream_data = data.read(1024)
            while stream_data:
                a.fromstring(stream_data)
                stream_data = data.read(1024)
            data = a.tostring()

        headers = {}
        splitdata = data.split('\r\n\r\n')
        if len(splitdata) > 1:
            headerdata = splitdata[0]
            data = string.join(splitdata[1:], '\r\n\r\n')
            for header in headerdata.split('\r\n'):
                splitheader = header.split(':')
                name = splitheader[0].strip()
                value = string.join(splitheader[1:], ':').strip()
                headers[name] = value

        if self.subtype:
            text_subtype = self.subtype
        else:
            text_subtype = 'plain'
        if text_subtype == 'plain':
            default_extension = 'txt'
        else:
            default_extension = text_subtype
        if text_subtype != 'xml' and data[:16].strip()[:5] == '<?xml':
            msglog.log('broadway', msglog.types.WARN,
                       'Transporter overriding configured subtype to "xml".')
            text_subtype = 'xml'
            default_extension = 'xml'
        msg = MIMEText(data, _subtype=text_subtype)
        subject = headers.get('Subject')
        if subject is None or subject == 'None' or subject == '':
            subject = self.subject
        #CSCtg54105
        else:
            if self.subject is not None and self.subject != 'None' and self.subject != '':
                subject = self.subject + ': ' + subject
        if subject:
            msg.add_header('Thread-Topic', subject)
            msg.add_header('Subject', subject)
        msg.add_header('From', self.sender)
        msg.add_header('To', COMMASPACE.join(self._recipients))
        date = headers.get('Date', formatdate(time.time(), True))
        msg.add_header('Date', date)

        message_id = make_msgid()
        if self.as_attachment:
            # @fixme: Make configurable
            default_filename = "%s.%s" % (message_id[1:-1].split("@")[0],
                                          default_extension)
            msg.add_header('Content-Disposition',
                           'attachment',
                           filename=default_filename)
            msg.set_param('name', default_filename)
        # @fixme: Make configurable
        msg.add_header('Content-Class', 'urn:content-classes:message')
        # @fixme: Make configurable
        msg.add_header('X-Mailer', 'Mediator SMTP Transport')
        msg.add_header('Message-ID', message_id)
        # @fixme: Make configurable
        msg.add_header('Importance', 'normal')
        # @fixme: Make configurable
        msg.add_header('Priority', 'normal')
        msg.preamble = ''
        # To guarantee the message ends with a newline
        msg.epilogue = ''

        smtp = self.SMTP()
        if self.debug:
            smtp.set_debuglevel(self.debug)
        smtp.connect(self.host, self.port, self.timeout)
        if self.custom_domain:
            if not (200 <= smtp.ehlo(self.custom_domain)[0] <= 299):
                (code, resp) = smtp.helo(self.custom_domain)
                if not (200 <= code <= 299):
                    raise smtp.SMTPHeloError(code, resp)
        if self.authenticate:
            try:
                smtp.login(self.username, self.password)
            except smtplib.SMTPAuthenticationError:
                msglog.log(
                    'broadway', msglog.types.WARN,
                    'SMTP Authentication failed.' +
                    '  Invalid username/password.')
                raise
        failures = smtp.sendmail(self.sender, self._recipients,
                                 msg.as_string())
        for recipient in failures.keys():
            msglog.log(
                'broadway', msglog.types.WARN,
                'Error sending mail to %s -> %s' %
                (recipient, failures[recipient]))
        smtp.close()
Ejemplo n.º 13
0
def handle_feedback():
	userdata = request.get_json(silent=True)
	
	# spamschutz vor Bots, die github durchlesen:
	domain = "."+".".join("de uni-frankfurt physik".split(" ")[::-1])
	from_addr = ("POKAL-Feedback", "*****@*****.**")
	to_addrs = [
		("eLearning", "elearning@th%s" % domain),
		("POTT", "pott@elearning%s" % domain),
	]
	subject = "POKAL Feedback"
	
	# Force python to encode utf-8 as quoted-printable and not base64
	# (both subject and body). unfortunately this modifies a global setting,
	# but email sending in POKAL is not such a popular task yet.
	Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')
	
	if userdata:
		# could correctly parse userdata
		output = {'status': 'JSON could be retrieved'}
		output['userdata'] = userdata
		status = 200 # OK
		
		msg = MIMEMultipart()
		msg['From'] = formataddr(from_addr)
		msg['To'] = ", ".join(map(formataddr,to_addrs))
		msg['Date'] = formatdate(localtime=True)
		msg['Subject'] = subject
		msg['Content-Type'] = 'text/html; charset=utf-8'
		
		body = u"""
Ein neuer POKAL-Feedback ist durch das Feedbacksystem (#984) eingereicht worden.

== Vom Besucher ausgefüllter Text ==
$note

== Screenshot ==
[[Image($screenshot_filename, width=100%)]]

== Daten ==

 URL des Worksheets::
    $url
 Name (Titel) des Worksheets::
    ''$worksheet_name''
 HRZ-Username des Benutzers::
    `$username`
 Nickname des Benutzers::
    `$nickname`
 Browser des Benutzers (User Agent)::
    `$HTTP_USER_AGENT`
 IP-Adresse des Besuchers::
    `HTTP_X_FORWARDED_FOR = $HTTP_X_FORWARDED_FOR`
 Verarbeitender POKAL-Server::
    `SERVER_NAME:... = $SERVER_NAME:$SERVER_PORT`
 Zwischenpunkt (Remote IP des bearbeitenden Pokal-Servers)::
    `REMOTE_ADDR = $REMOTE_ADDR`
 Endpunkt POKAL-Host::
    `HTTP_HOST = $HTTP_HOST`
 Uhrzeit::
    $date
 Anzahl Benutzer im Chat::
    $chat_nicknames_count
 Anzahl Chatzeilen::
    $chat_messages_count
 Länge Worksheet (Anzahl Worksheet-Zellen)::
    $cells_count

@type: Designen
@component: POKAL
@keywords: pokal, feedback
@sensitive: 1

"""
		# look at the image
		if "img" in userdata:
			screenshot_filename = "screenshot-%s.png" % str(uuid4())[:6]
			binaryimg = unpack_html2image_screenshot(userdata["img"])
			img_part = MIMEImage(binaryimg)
			img_part.set_param('name', screenshot_filename)
			img_part.add_header('Content-Disposition', 'attachment; filename="%s"' % screenshot_filename)
		else:	screenshot_filename = "<no screenshot present>"
		
		# enrich the data with classical CGI ENV vars
		serverdata = request.environ
		# further data
		furtherdata = {
			"screenshot_filename": screenshot_filename,
			"date": datetime.now().strftime("%c")
		}
		# userdata are overwritten by serverdata
		replace_data = dict(userdata.items() + serverdata.items() + furtherdata.items())
		
		body = Template(body).safe_substitute(replace_data)
		# make sure of a quoted printable body
		msg.attach( MIMEText(body.encode('utf-8'), 'plain', 'utf-8') )
		
		# format the image attachment
		msg.attach(img_part)
		
		# consider also the HTML attachments
		for key in ["cells", "chat_messages"]:
			if not key in userdata:
				continue
			text_part = MIMEText(userdata[key], "text/html", "utf-8")
			text_part.set_param('name', key+".html")
			text_part.add_header('Content-Disposition', 'attachment; filename="%s.html"' % key)
			msg.attach(text_part)		

		try:
			smtp = smtplib.SMTP('localhost')
			smtp.sendmail( emailaddr(from_addr), map(emailaddr, to_addrs), msg.as_string() )
			smtp.close()
			output['status'] = 'Feedback mail successfully sent.'
		except smtplib.SMTPException as e:
			output['status'] =  'Error sending mail: '+str(e)
			status = 502 # bad mail
	else:
		# could not parse userdata, or error, or not given
		output = {'status': 'Error: Please POST valid JSON feedback data.'}
		status = 400 # bad request

	# um auf POST-Argumente zuzugreifen:
	# request.form.get('key')
	
	res = make_response(encode_response(output))
	res.headers['Content-Type'] = 'application/json'
	return res, status