当前位置: 首页>>代码示例>>Python>>正文


Python Charset.body_encoding方法代码示例

本文整理汇总了Python中email.charset.Charset.body_encoding方法的典型用法代码示例。如果您正苦于以下问题:Python Charset.body_encoding方法的具体用法?Python Charset.body_encoding怎么用?Python Charset.body_encoding使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在email.charset.Charset的用法示例。


在下文中一共展示了Charset.body_encoding方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: create_charset

# 需要导入模块: from email.charset import Charset [as 别名]
# 或者: from email.charset.Charset import body_encoding [as 别名]
def create_charset(mime_encoding):
    """Create an appropriate email charset for the given encoding.

    Valid options are 'base64' for Base64 encoding, 'qp' for
    Quoted-Printable, and 'none' for no encoding, in which case mails will
    be sent as 7bit if the content is all ASCII, or 8bit otherwise.
    """
    charset = Charset()
    charset.input_charset = 'utf-8'
    charset.output_charset = 'utf-8'
    charset.input_codec = 'utf-8'
    charset.output_codec = 'utf-8'
    pref = mime_encoding.lower()
    if pref == 'base64':
        charset.header_encoding = BASE64
        charset.body_encoding = BASE64
    elif pref in ('qp', 'quoted-printable'):
        charset.header_encoding = QP
        charset.body_encoding = QP
    elif pref == 'none':
        charset.header_encoding = SHORTEST
        charset.body_encoding = None
    else:
        raise TracError(_("Invalid email encoding setting: %(mime_encoding)s",
                          mime_encoding=mime_encoding))
    return charset
开发者ID:pkdevbox,项目名称:trac,代码行数:28,代码来源:mail.py

示例2: get_emails_header

# 需要导入模块: from email.charset import Charset [as 别名]
# 或者: from email.charset.Charset import body_encoding [as 别名]
    def get_emails_header(self, attr):
        c = Charset(self.charset)
        c.header_encoding = QP
        c.body_encoding = 0
        r = Charset(self.charset)
        r.header_encoding = 0
        r.body_encoding = 0

        h = Header()
        self.normalize_email_list(attr)
        emails = self.__getattribute__(attr)

        for i in range(len(emails)):
            name, email = emails[i]

            if i:
                h.append(',', r)

            if name:
                name = name.encode(self.charset, 'xmlcharrefreplace')
                h.append(name, r if is7bit(name) else c)
                h.append('<%s>' % email, r)
            else:
                h.append(email, r)

        return h
开发者ID:highcat,项目名称:emailer,代码行数:28,代码来源:__init__.py

示例3: as_message

# 需要导入模块: from email.charset import Charset [as 别名]
# 或者: from email.charset.Charset import body_encoding [as 别名]
    def as_message(self, escape_addresses=True):
        # http://wordeology.com/computer/how-to-send-good-unicode-email-with-python.html
        # http://stackoverflow.com/questions/31714221/how-to-send-an-email-with-quoted
        # http://stackoverflow.com/questions/9403265/how-do-i-use-python/9509718#9509718
        charset = Charset('utf-8')
        charset.header_encoding = QP
        charset.body_encoding = QP
        msg = MIMEMultipart()

        # Headers
        unixfrom = "From %s %s" % (
            self.sender.address, self.archived_date.strftime("%c"))
        header_from = self.sender.address
        if self.sender.name and self.sender.name != self.sender.address:
            header_from = "%s <%s>" % (self.sender.name, header_from)
        header_to = self.mailinglist.name
        if escape_addresses:
            header_from = header_from.replace("@", " at ")
            header_to = header_to.replace("@", " at ")
            unixfrom = unixfrom.replace("@", " at ")
        msg.set_unixfrom(unixfrom)
        headers = (
            ("From", header_from),
            ("To", header_to),
            ("Subject", self.subject),
            )
        for header_name, header_value in headers:
            if not header_value:
                continue
            try:
                msg[header_name] = header_value.encode('ascii')
            except UnicodeEncodeError:
                msg[header_name] = Header(
                    header_value.encode('utf-8'), charset).encode()
        tz = get_fixed_timezone(self.timezone)
        header_date = self.date.astimezone(tz).replace(microsecond=0)
        # Date format: http://tools.ietf.org/html/rfc5322#section-3.3
        msg["Date"] = header_date.strftime("%a, %d %b %Y %H:%M:%S %z")
        msg["Message-ID"] = "<%s>" % self.message_id
        if self.in_reply_to:
            msg["In-Reply-To"] = self.in_reply_to

        # Body
        content = self.ADDRESS_REPLACE_RE.sub(r"\1(a)\2", self.content)
        # Don't use MIMEText, it won't encode to quoted-printable
        textpart = MIMENonMultipart("text", "plain", charset='utf-8')
        textpart.set_payload(content, charset=charset)
        msg.attach(textpart)

        # Attachments
        for attachment in self.attachments.order_by("counter"):
            mimetype = attachment.content_type.split('/', 1)
            part = MIMEBase(mimetype[0], mimetype[1])
            part.set_payload(attachment.content)
            encode_base64(part)
            part.add_header('Content-Disposition', 'attachment',
                            filename=attachment.name)
            msg.attach(part)

        return msg
开发者ID:simonsmiley,项目名称:hyperkitty,代码行数:62,代码来源:email.py

示例4: write_patch_file

# 需要导入模块: from email.charset import Charset [as 别名]
# 或者: from email.charset.Charset import body_encoding [as 别名]
def write_patch_file(filename, commit_info, diff):
    """Write patch file"""
    if not diff:
        gbp.log.debug("I won't generate empty diff %s" % filename)
        return None
    try:
        with open(filename, 'wb') as patch:
            msg = Message()
            charset = Charset('utf-8')
            charset.body_encoding = None
            charset.header_encoding = QP

            # Write headers
            name = commit_info['author']['name']
            email = commit_info['author']['email']
            # Git compat: put name in quotes if special characters found
            if re.search(r'[,[email protected]()\[\]\\\:;]', name):
                name = '"%s"' % name
            from_header = Header(header_name='from')
            try:
                from_header.append(name, 'us-ascii')
            except UnicodeDecodeError:
                from_header.append(name, charset)
            from_header.append('<%s>' % email)
            msg['From'] = from_header
            date = commit_info['author'].datetime
            datestr = date.strftime('%a, %-d %b %Y %H:%M:%S %z')
            msg['Date'] = Header(datestr, 'us-ascii', 'date')
            subject_header = Header(header_name='subject')
            try:
                subject_header.append(commit_info['subject'], 'us-ascii')
            except UnicodeDecodeError:
                subject_header.append(commit_info['subject'], charset)
            msg['Subject'] = subject_header
            # Write message body
            if commit_info['body']:
                # Strip extra linefeeds
                body = commit_info['body'].rstrip() + '\n'
                try:
                    msg.set_payload(body.encode('us-ascii'))
                except (UnicodeEncodeError):
                    msg.set_payload(body, charset)
            policy = Compat32(max_line_length=77)
            patch.write(msg.as_bytes(unixfrom=False, policy=policy))

            # Write diff
            patch.write(b'---\n')
            patch.write(diff)
    except IOError as err:
        raise GbpError('Unable to create patch file: %s' % err)
    return filename
开发者ID:agx,项目名称:git-buildpackage,代码行数:53,代码来源:pq.py

示例5: _make_charset

# 需要导入模块: from email.charset import Charset [as 别名]
# 或者: from email.charset.Charset import body_encoding [as 别名]
 def _make_charset(self):
     charset = Charset()
     charset.input_charset = 'utf-8'
     pref = self.mime_encoding.lower()
     if pref == 'base64':
         charset.header_encoding = BASE64
         charset.body_encoding = BASE64
         charset.output_charset = 'utf-8'
         charset.input_codec = 'utf-8'
         charset.output_codec = 'utf-8'
     elif pref in ['qp', 'quoted-printable']:
         charset.header_encoding = QP
         charset.body_encoding = QP
         charset.output_charset = 'utf-8'
         charset.input_codec = 'utf-8'
         charset.output_codec = 'utf-8'
     elif pref == 'none':
         charset.header_encoding = None
         charset.body_encoding = None
         charset.input_codec = None
         charset.output_charset = 'ascii'
     else:
         raise TracError(_('Invalid email encoding setting: %s' % pref))
     return charset
开发者ID:CGI-define-and-primeportal,项目名称:trac-plugin-sourcesharing,代码行数:26,代码来源:sourcesharer.py

示例6: _mail

# 需要导入模块: from email.charset import Charset [as 别名]
# 或者: from email.charset.Charset import body_encoding [as 别名]
    def _mail(self, fromaddr, to, subject, payload):

        # prepare
        charset = Charset("utf-8")
        charset.header_encoding = QP
        charset.body_encoding = QP

        # create method and set headers
        msg = Message()
        msg.set_payload(payload.encode("utf8"))
        msg.set_charset(charset)
        msg['Subject'] = Header(subject, "utf8")
        msg['From'] = fromaddr
        msg['To'] = to

        self.server.connect()
        self.server.sendmail(fromaddr, [to], msg.as_string())
        self.server.quit()
开发者ID:mrtopf,项目名称:jmstvcamp,代码行数:20,代码来源:emails.py

示例7: write_patch_file

# 需要导入模块: from email.charset import Charset [as 别名]
# 或者: from email.charset.Charset import body_encoding [as 别名]
def write_patch_file(filename, commit_info, diff):
    """Write patch file"""
    if not diff:
        gbp.log.debug("I won't generate empty diff %s" % filename)
        return None
    try:
        with open(filename, "w") as patch:
            msg = Message()
            charset = Charset("utf-8")
            charset.body_encoding = None
            charset.header_encoding = QP

            # Write headers
            name = commit_info["author"]["name"]
            email = commit_info["author"]["email"]
            # Git compat: put name in quotes if special characters found
            if re.search("[,[email protected]()\[\]\\\:;]", name):
                name = '"%s"' % name
            from_header = Header(unicode(name, "utf-8"), charset, 77, "from")
            from_header.append(unicode("<%s>" % email))
            msg["From"] = from_header
            date = commit_info["author"].datetime
            datestr = date.strftime("%a, %-d %b %Y %H:%M:%S %z")
            msg["Date"] = Header(unicode(datestr, "utf-8"), charset, 77, "date")
            msg["Subject"] = Header(unicode(commit_info["subject"], "utf-8"), charset, 77, "subject")
            # Write message body
            if commit_info["body"]:
                # Strip extra linefeeds
                body = commit_info["body"].rstrip() + "\n"
                try:
                    msg.set_payload(body.encode("ascii"))
                except UnicodeDecodeError:
                    msg.set_payload(body, charset)
            patch.write(msg.as_string(unixfrom=False))

            # Write diff
            patch.write("---\n")
            patch.write(diff)
    except IOError as err:
        raise GbpError("Unable to create patch file: %s" % err)
    return filename
开发者ID:hemmop,项目名称:git-buildpackage,代码行数:43,代码来源:pq.py

示例8: sendMailMessage

# 需要导入模块: from email.charset import Charset [as 别名]
# 或者: from email.charset.Charset import body_encoding [as 别名]
	def sendMailMessage(self, xMailMessage):
		COMMASPACE = ', '

		if dbg:
			print("PyMailSMTPService sendMailMessage", file=dbgout)
		recipients = xMailMessage.getRecipients()
		sendermail = xMailMessage.SenderAddress
		sendername = xMailMessage.SenderName
		subject = xMailMessage.Subject
		ccrecipients = xMailMessage.getCcRecipients()
		bccrecipients = xMailMessage.getBccRecipients()
		if dbg:
			print("PyMailSMTPService subject: " + subject, file=dbgout)
			print("PyMailSMTPService from:  " + sendername, file=dbgout)
			print("PyMailSMTPService from:  " + sendermail, file=dbgout)
			print("PyMailSMTPService send to: %s" % (recipients,), file=dbgout)

		attachments = xMailMessage.getAttachments()

		textmsg = Message()

		content = xMailMessage.Body
		flavors = content.getTransferDataFlavors()
		if dbg:
			print("PyMailSMTPService flavors len: %d" % (len(flavors),), file=dbgout)

		#Use first flavor that's sane for an email body
		for flavor in flavors:
			if flavor.MimeType.find('text/html') != -1 or flavor.MimeType.find('text/plain') != -1:
				if dbg:
					print("PyMailSMTPService mimetype is: " + flavor.MimeType, file=dbgout)
				textbody = content.getTransferData(flavor)

				if len(textbody):
					mimeEncoding = re.sub("charset=.*", "charset=UTF-8", flavor.MimeType)
					if mimeEncoding.find('charset=UTF-8') == -1:
						mimeEncoding = mimeEncoding + "; charset=UTF-8"
					textmsg['Content-Type'] = mimeEncoding
					textmsg['MIME-Version'] = '1.0'

					try:
						#it's a string, get it as utf-8 bytes
						textbody = textbody.encode('utf-8')
					except:
						#it's a bytesequence, get raw bytes
						textbody = textbody.value
					if sys.version >= '3':
						if sys.version_info.minor < 3 or (sys.version_info.minor == 3 and sys.version_info.micro <= 1):
							#http://stackoverflow.com/questions/9403265/how-do-i-use-python-3-2-email-module-to-send-unicode-messages-encoded-in-utf-8-w
							#see http://bugs.python.org/16564, etc. basically it now *seems* to be all ok
							#in python 3.3.2 onwards, but a little busted in 3.3.0

							textbody = textbody.decode('iso8859-1')
						else:
							textbody = textbody.decode('utf-8')
						c = Charset('utf-8')
						c.body_encoding = QP
						textmsg.set_payload(textbody, c)
					else:
						textmsg.set_payload(textbody)

				break

		if (len(attachments)):
			msg = MIMEMultipart()
			msg.epilogue = ''
			msg.attach(textmsg)
		else:
			msg = textmsg

		hdr = Header(sendername, 'utf-8')
		hdr.append('<'+sendermail+'>','us-ascii')
		msg['Subject'] = subject
		msg['From'] = hdr
		msg['To'] = COMMASPACE.join(recipients)
		if len(ccrecipients):
			msg['Cc'] = COMMASPACE.join(ccrecipients)
		if xMailMessage.ReplyToAddress != '':
			msg['Reply-To'] = xMailMessage.ReplyToAddress

		mailerstring = "LibreOffice via Caolan's mailmerge component"
		try:
			ctx = uno.getComponentContext()
			aConfigProvider = ctx.ServiceManager.createInstance("com.sun.star.configuration.ConfigurationProvider")
			prop = uno.createUnoStruct('com.sun.star.beans.PropertyValue')
			prop.Name = "nodepath"
			prop.Value = "/org.openoffice.Setup/Product"
			aSettings = aConfigProvider.createInstanceWithArguments("com.sun.star.configuration.ConfigurationAccess",
				(prop,))
			mailerstring = aSettings.getByName("ooName") + " " + \
				aSettings.getByName("ooSetupVersion") + " via Caolan's mailmerge component"
		except:
			pass

		msg['X-Mailer'] = mailerstring
		msg['Date'] = formatdate(localtime=True)

		for attachment in attachments:
			content = attachment.Data
			flavors = content.getTransferDataFlavors()
#.........这里部分代码省略.........
开发者ID:Flatta,项目名称:LibreOffice-core,代码行数:103,代码来源:mailmerge.py

示例9: sendmail

# 需要导入模块: from email.charset import Charset [as 别名]
# 或者: from email.charset.Charset import body_encoding [as 别名]
def sendmail(subject, text, to=None, cc=None, bcc=None, mail_from=None, html=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
    :param html: html email body text
    :type html: unicode

    :rtype: tuple
    :returns: (is_ok, Description of error or OK message)
    """
    import smtplib
    import socket
    from email.message import Message
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.charset import Charset, QP
    from email.utils import formatdate, make_msgid

    cfg = app.cfg
    if not cfg.mail_enabled:
        return (0, _("Contact administrator: cannot send password recovery e-mail "
                     "because mail configuration is incomplete."))
    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(CHARSET)

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

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

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

    text_msg.set_payload(text)

    if html:
        msg = MIMEMultipart('alternative')
        msg.attach(text_msg)
        html = html.encode(CHARSET)
        html_msg = MIMEText(html, 'html')
        html_msg.set_charset(charset)
        msg.attach(html_msg)
    else:
        msg = text_msg

    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))
#.........这里部分代码省略.........
开发者ID:rciorba,项目名称:moin-2.0-mirror,代码行数:103,代码来源:sendmail.py

示例10: send

# 需要导入模块: from email.charset import Charset [as 别名]
# 或者: from email.charset.Charset import body_encoding [as 别名]
    def send(self, emails):
        if isinstance(emails, Email):
            emails = [emails]
        if len([e for e in emails if e.__class__ != Email]):
            raise TypeError('emails must be Email or list of Email instances')

        smtpclass = SMTP_SSL if self.ssl else SMTP
        if self.server == 'localhost':
            smtp = smtpclass(self.server)
        else:
            smtp = smtpclass(self.server, self.port)
        if self.tls:
            smtp.starttls()
        if self.login and self.password:
            smtp.login(self.login, self.password)
        for email in emails:
            c = Charset(email.charset)
            c.header_encoding = QP
            c.body_encoding = 0
            r = Charset(email.charset)
            r.header_encoding = 0
            r.body_encoding = 0

            email.normalize_email_list('rcpt')
            email.normalize_email_list('cc')
            email.normalize_email_list('bcc')
            mime1, mime2 = email.mimetype.split('/')
            mainpart = MIMEBase(mime1, mime2)
            if not email.force_7bit:
                mainpart.set_param('charset', email.charset)

            if len(email.attachments):
                message = MIMEMultipart('mixed')
                message.attach(mainpart)
                del mainpart['mime-version']
            else:
                message = mainpart

            message['Date'] = datetime.datetime.now().strftime(
                '%a, %d %b %Y %H:%M:%S') + (" +%04d" % (time.timezone/-36,))

            h = Header(maxlinelen=1000) # FIXME: what is correct max length?
            fromname = self.fromname.encode(email.charset, 'xmlcharrefreplace')
            h.append(fromname, r if is7bit(fromname) else c)
            h.append('<%s>' % self.email, r)
            message['From'] = h

            message['To'] = email.get_emails_header('rcpt')
            if len(email.cc):
                message['CC'] = email.get_emails_header('cc')
            if len(email.bcc):
                message['BCC'] = email.get_emails_header('bcc')

            subject = email.subject.encode(email.charset, 'xmlcharrefreplace')
            message['Subject'] = Header(subject, r if is7bit(subject) else c)

            if email.reply_to:
                message['Reply-To'] = email.get_emails_header('reply_to')

            if email.force_7bit:
                body = email.body.encode('ascii', 'xmlcharrefreplace')
            else:
                body = email.body.encode(email.charset, 'xmlcharrefreplace')
            mainpart.set_payload(body)

            if is7bit(body):
                mainpart['Content-Transfer-Encoding'] = '7bit'
            else:
                encode_quopri(mainpart)

            for attachment in email.attachments:
                if attachment.__class__ != Attachment:
                    raise TypeError("invalid attachment")

                mimetype = attachment.mimetype
                if not mimetype:
                    mimetype, encoding = guess_type(attachment.filename)
                    if not mimetype:
                        mimetype = 'application/octet-stream'
                mime1, mime2 = mimetype.split('/')
                part = MIMEBase(mime1, mime2)

                # using newer rfc2231 (not supported by Outlook):
                # part.set_param('name', attachment.filename.encode('utf-8'), charset = 'utf-8')

                # hack: using deprecated rfc2047 - supported by Outlook:
                part.set_param('name', str(Header(attachment.filename)))
                del part['mime-version']

                if attachment.id:
                    part['Content-Disposition'] = 'inline'
                else:
                    part['Content-Disposition'] = 'attachment'

                # using newer rfc2231 (not supported by Outlook):
                # part.set_param('filename',
                #                attachment.filename.encode('utf-8'),
                #                'Content-Disposition',
                #                charset = 'utf-8')

#.........这里部分代码省略.........
开发者ID:highcat,项目名称:emailer,代码行数:103,代码来源:__init__.py

示例11: Copyright

# 需要导入模块: from email.charset import Charset [as 别名]
# 或者: from email.charset.Charset import body_encoding [as 别名]
#
# Copyright (c) 2009 UK Citizens Online Democracy. All rights reserved.
# Email: [email protected]; WWW: http://www.mysociety.org/
#
# $Id: sendemail.py,v 1.5 2009/12/17 17:31:04 francis dead $
#

import re, smtplib
from minimock import mock, Mock
from email.message import Message
from email.header import Header
from email.utils import formataddr, make_msgid, formatdate
from email.charset import Charset, QP

charset = Charset('utf-8')
charset.body_encoding = QP

def send_email(sender, to, message, headers={}):
    """Sends MESSAGE from SENDER to TO, with HEADERS
    Returns True if successful, False if not
    
    >>> mock('smtplib.SMTP', returns=Mock('smtp_connection'))
    >>> send_email("[email protected]", "[email protected]", "Hello, this is a message!", {
    ...     'Subject': 'Mapumental message',
    ...     'From': ("[email protected]", "Ms. A"),
    ...     'To': "[email protected]"
    ... }) # doctest:+ELLIPSIS
    Called smtplib.SMTP('localhost')
    Called smtp_connection.sendmail(
        '[email protected]',
        '[email protected]',
开发者ID:Kagee,项目名称:commonlib,代码行数:33,代码来源:emailutils.py

示例12: __init__

# 需要导入模块: from email.charset import Charset [as 别名]
# 或者: from email.charset.Charset import body_encoding [as 别名]
    def __init__(self, payload, charset='utf-8'):
        MIMENonMultipart.__init__(self, 'text', 'plain', charset=charset)

        utf8qp = Charset(charset)
        utf8qp.body_encoding = QP
        self.set_payload(payload, charset=utf8qp)
开发者ID:jandd,项目名称:django-gnupg-mails,代码行数:8,代码来源:message.py


注:本文中的email.charset.Charset.body_encoding方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。