def create_message(corpus, data, msg0=None): from email import Charset, Parser, MIMEMessage if not isinstance(data, unicode): raise TypeError('data must be a unicode.') p = Parser.FeedParser() p.feed(data) msg1 = p.close() csmap = Charset.Charset(config.MESSAGE_CHARSET) attach_msgs = [] # Re-encode the headers. headers = [] labels = [] for (k, v) in msg1.items(): v = rmsp(v) if not v: continue kl = k.lower() if kl == 'x-forward-msg': attach_msgs.extend(get_numbers(v)) continue if kl == 'label': labels = v.split(',') continue headers.append((k.encode('ascii', 'strict'), encode_header(v, csmap))) # Remove all the existing headers. for k in msg1.keys(): del msg1[k] # Reattach the headers. for (k, v) in headers: msg1[k] = v # Change the body. data = msg1.get_payload(decode=False) try: # First try to encode with us-ascii. data.encode('ascii', 'strict') # Succeed. msg1.set_charset('ascii') except UnicodeError: # Re-encode the body. if not csmap.output_charset: csmap = Charset.Charset('utf-8') msg1.set_charset(str(csmap.output_charset)) data = data.encode(str(csmap.output_codec), 'replace') msg1.set_payload(data) # Attach other messages (for forwarding). if attach_msgs: for loc in attach_msgs: p = Parser.FeedParser() p.feed(corpus.get_message(loc)) msg1 = mime_add(msg1, MIMEMessage.MIMEMessage(p.close())) # Integrate other mime objects. if msg0 and msg0.is_multipart(): for obj in msg0.get_payload()[1:]: msg1 = mime_add(msg1, obj) validate_message_structure(msg1) return (msg1, labels)
def set_charset(self, charset): if charset is None: self.del_param('charset') self._charset = None return None if isinstance(charset, str): charset = Charset.Charset(charset) if not isinstance(charset, Charset.Charset): raise TypeError(charset) self._charset = charset if not self.has_key('MIME-Version'): self.add_header('MIME-Version', '1.0') if not self.has_key('Content-Type'): self.add_header('Content-Type', 'text/plain', charset=charset.get_output_charset()) else: self.set_param('charset', charset.get_output_charset()) if not self.has_key('Content-Transfer-Encoding'): cte = charset.get_body_encoding() try: cte(self) except TypeError: self.add_header('Content-Transfer-Encoding', cte)
def set_charset(self, charset): """Set the charset of the payload to a given character set. charset can be a Charset instance, a string naming a character set, or None. If it is a string it will be converted to a Charset instance. If charset is None, the charset parameter will be removed from the Content-Type field. Anything else will generate a TypeError. The message will be assumed to be of type text/* encoded with charset.input_charset. It will be converted to charset.output_charset and encoded properly, if needed, when generating the plain text representation of the message. MIME headers (MIME-Version, Content-Type, Content-Transfer-Encoding) will be added as needed. """ if charset is None: self.del_param('charset') self._charset = None return if isinstance(charset, str): charset = Charset.Charset(charset) if not isinstance(charset, Charset.Charset): raise TypeError(charset) # BAW: should we accept strings that can serve as arguments to the # Charset constructor? self._charset = charset if not self.has_key('MIME-Version'): self.add_header('MIME-Version', '1.0') if not self.has_key('Content-Type'): self.add_header('Content-Type', 'text/plain', charset=charset.get_output_charset()) else: self.set_param('charset', charset.get_output_charset()) if str(charset) <> charset.get_output_charset(): self._payload = charset.body_encode(self._payload) if not self.has_key('Content-Transfer-Encoding'): cte = charset.get_body_encoding() try: cte(self) except TypeError: self._payload = charset.body_encode(self._payload) self.add_header('Content-Transfer-Encoding', cte)
def mime_new(fname, data, mimetype, charset): import mimetypes from email import Charset, Encoders from email import MIMEBase, MIMEText, MIMEImage, MIMEAudio # Try to guess the mimetype. if not mimetype: (mimetype, _) = mimetypes.guess_type(fname) if not mimetype: mimetype = 'text/plain' (maintype, subtype) = mimetype.split('/') # Create a MIME object. if maintype == 'text': # Text # Try to determine the character encoding. charset = charset or config.TERMINAL_CHARSET # Re-encode the data in a specified encoding. csmap = Charset.Charset(charset) try: if csmap.input_codec: data = unicode(data, str(csmap.input_codec), 'replace') if csmap.output_codec: data = data.encode(str(csmap.output_codec), 'replace') charset = str(csmap.output_charset) except UnicodeError: raise EncodingError('Cannot encode with %s' % charset) obj = MIMEText.MIMEText(data, subtype, charset) elif maintype == 'image': # Image obj = MIMEImage.MIMEImage(data, subtype) elif maintype == 'audio': # Audio obj = MIMEAudio.MIMEAudio(data, subtype) else: # Other obj = MIMEBase.MIMEBase(maintype, subtype) obj.set_payload(data) Encoders.encode_base64(obj) # Attach the MIME object to the original Message. obj.add_header('Content-Disposition', 'attachment', filename=fname) return obj
#coding:utf8 from email.Utils import COMMASPACE from email import Charset from email.MIMENonMultipart import MIMENonMultipart from email.MIMEMultipart import MIMEMultipart from email.Header import Header import smtplib UTF8 = Charset.Charset('utf-8') class UTF8MIMEText(MIMENonMultipart): def __init__(self, _text, _subtype='plain'): MIMENonMultipart.__init__(self, 'text', _subtype, charset='utf-8') self.set_payload(_text, UTF8) def gen_msg(email, name, to_list, subject, data): msg = MIMEMultipart() msg['Subject'] = Header(u'件粉红色的风景'.encode('utf8'), 'utf-8') msg['From'] = '%s\r' % email msg['To'] = '%s\n' % COMMASPACE.join(to_list) body = UTF8MIMEText(data) msg.attach(body) return msg if __name__ == "__main__": data = u'开房间第三方的手机分解速度放缓的风景反击得手发抖' subject = u'将发挥第三方的房贷收紧房贷负担' from optparse import OptionParser