Python email.header.Header() Examples

The following are 30 code examples of email.header.Header(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module email.header , or try the search function .
Example #1
Source File: informer.py    From zvt with MIT License 15 votes vote down vote up
def send_message(self, to_user, title, body, **kwargs):
        if self.ssl:
            smtp_client = smtplib.SMTP_SSL()
        else:
            smtp_client = smtplib.SMTP()
        smtp_client.connect(zvt_env['smtp_host'], zvt_env['smtp_port'])
        smtp_client.login(zvt_env['email_username'], zvt_env['email_password'])
        msg = MIMEMultipart('alternative')
        msg['Subject'] = Header(title).encode()
        msg['From'] = "{} <{}>".format(Header('zvt').encode(), zvt_env['email_username'])
        if type(to_user) is list:
            msg['To'] = ", ".join(to_user)
        else:
            msg['To'] = to_user
        msg['Message-id'] = email.utils.make_msgid()
        msg['Date'] = email.utils.formatdate()

        plain_text = MIMEText(body, _subtype='plain', _charset='UTF-8')
        msg.attach(plain_text)

        try:
            smtp_client.sendmail(zvt_env['email_username'], to_user, msg.as_string())
        except Exception as e:
            self.logger.exception('send email failed', e) 
Example #2
Source File: send_email_with_python.py    From autopython with GNU General Public License v3.0 7 votes vote down vote up
def send_mail(to_email,message):
# 定义邮件发送
# Define send_mail() function
	smtp_host = 'smtp.xxx.com'
	# 发件箱服务器
	# Outbox Server
	from_email = 'from_email@xxx.com'
	# 发件邮箱
	# from_email
	passwd = 'xxxxxx'
	# 发件邮箱密码
	# from_email_password
	msg = MIMEText(message,'plain','utf-8')
	msg['Subject'] = Header(u'Email Subject','utf-8').encode()
	# 邮件主题
	# Email Subject
	smtp_server = smtplib.SMTP(smtp_host,25)
	# 发件服务器端口
	# Outbox Server Port
	smtp_server.login(from_email,passwd)
	smtp_server.sendmail(from_email,[to_email],msg.as_string())
	smtp_server.quit() 
Example #3
Source File: utils.py    From GerbLook with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def send_email(msg_to, msg_subject, msg_body, msg_from=None,
        smtp_server='localhost', envelope_from=None,
        headers={}):

  if not msg_from:
    msg_from = app.config['EMAIL_FROM']

  if not envelope_from:
    envelope_from = parseaddr(msg_from)[1]

  msg = MIMEText(msg_body)

  msg['Subject'] = Header(msg_subject)
  msg['From'] = msg_from
  msg['To'] = msg_to
  msg['Date'] = formatdate()
  msg['Message-ID'] = make_msgid()
  msg['Errors-To'] = envelope_from

  if request:
    msg['X-Submission-IP'] = request.remote_addr

  s = smtplib.SMTP(smtp_server)
  s.sendmail(envelope_from, msg_to, msg.as_string())
  s.close() 
Example #4
Source File: message.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def forbid_multi_line_headers(name, val, encoding):
    """Forbids multi-line headers, to prevent header injection."""
    encoding = encoding or settings.DEFAULT_CHARSET
    val = force_text(val)
    if '\n' in val or '\r' in val:
        raise BadHeaderError("Header values can't contain newlines (got %r for header %r)" % (val, name))
    try:
        val.encode('ascii')
    except UnicodeEncodeError:
        if name.lower() in ADDRESS_HEADERS:
            val = ', '.join(sanitize_address(addr, encoding)
                for addr in getaddresses((val,)))
        else:
            val = Header(val, encoding).encode()
    else:
        if name.lower() == 'subject':
            val = Header(val).encode()
    return str(name), val 
Example #5
Source File: test_email_renamed.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test__all__(self):
        module = __import__('email')
        # Can't use sorted() here due to Python 2.3 compatibility
        all = module.__all__[:]
        all.sort()
        self.assertEqual(all, [
            # Old names
            'Charset', 'Encoders', 'Errors', 'Generator',
            'Header', 'Iterators', 'MIMEAudio', 'MIMEBase',
            'MIMEImage', 'MIMEMessage', 'MIMEMultipart',
            'MIMENonMultipart', 'MIMEText', 'Message',
            'Parser', 'Utils', 'base64MIME',
            # new names
            'base64mime', 'charset', 'encoders', 'errors', 'generator',
            'header', 'iterators', 'message', 'message_from_file',
            'message_from_string', 'mime', 'parser',
            'quopriMIME', 'quoprimime', 'utils',
            ]) 
Example #6
Source File: test_email_renamed.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_get_param(self):
        eq = self.assertEqual
        msg = email.message_from_string(
            "X-Header: foo=one; bar=two; baz=three\n")
        eq(msg.get_param('bar', header='x-header'), 'two')
        eq(msg.get_param('quuz', header='x-header'), None)
        eq(msg.get_param('quuz'), None)
        msg = email.message_from_string(
            'X-Header: foo; bar="one"; baz=two\n')
        eq(msg.get_param('foo', header='x-header'), '')
        eq(msg.get_param('bar', header='x-header'), 'one')
        eq(msg.get_param('baz', header='x-header'), 'two')
        # XXX: We are not RFC-2045 compliant!  We cannot parse:
        # msg["Content-Type"] = 'text/plain; weird="hey; dolly? [you] @ <\\"home\\">?"'
        # msg.get_param("weird")
        # yet. 
Example #7
Source File: generator.py    From BinderFilter with MIT License 6 votes vote down vote up
def __init__(self, outfp, mangle_from_=True, maxheaderlen=78):
        """Create the generator for message flattening.

        outfp is the output file-like object for writing the message to.  It
        must have a write() method.

        Optional mangle_from_ is a flag that, when True (the default), escapes
        From_ lines in the body of the message by putting a `>' in front of
        them.

        Optional maxheaderlen specifies the longest length for a non-continued
        header.  When a header line is longer (in characters, with tabs
        expanded to 8 spaces) than maxheaderlen, the header will split as
        defined in the Header class.  Set maxheaderlen to zero to disable
        header wrapping.  The default is 78, as recommended (but not required)
        by RFC 2822.
        """
        self._fp = outfp
        self._mangle_from_ = mangle_from_
        self._maxheaderlen = maxheaderlen 
Example #8
Source File: test_email_renamed.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_long_lines_with_different_header(self):
        eq = self.ndiffAssertEqual
        h = """\
List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
        <mailto:spamassassin-talk-request@lists.sourceforge.net?subject=unsubscribe>"""
        msg = Message()
        msg['List'] = h
        msg['List'] = Header(h, header_name='List')
        self.ndiffAssertEqual(msg.as_string(), """\
List: List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
 <mailto:spamassassin-talk-request@lists.sourceforge.net?subject=unsubscribe>
List: List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
 <mailto:spamassassin-talk-request@lists.sourceforge.net?subject=unsubscribe>

""")



# Test mangling of "From " lines in the body of a message 
Example #9
Source File: generator.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def __init__(self, outfp, mangle_from_=True, maxheaderlen=78):
        """Create the generator for message flattening.

        outfp is the output file-like object for writing the message to.  It
        must have a write() method.

        Optional mangle_from_ is a flag that, when True (the default), escapes
        From_ lines in the body of the message by putting a `>' in front of
        them.

        Optional maxheaderlen specifies the longest length for a non-continued
        header.  When a header line is longer (in characters, with tabs
        expanded to 8 spaces) than maxheaderlen, the header will split as
        defined in the Header class.  Set maxheaderlen to zero to disable
        header wrapping.  The default is 78, as recommended (but not required)
        by RFC 2822.
        """
        self._fp = outfp
        self._mangle_from_ = mangle_from_
        self._maxheaderlen = maxheaderlen 
Example #10
Source File: test_email_renamed.py    From BinderFilter with MIT License 6 votes vote down vote up
def test__all__(self):
        module = __import__('email')
        # Can't use sorted() here due to Python 2.3 compatibility
        all = module.__all__[:]
        all.sort()
        self.assertEqual(all, [
            # Old names
            'Charset', 'Encoders', 'Errors', 'Generator',
            'Header', 'Iterators', 'MIMEAudio', 'MIMEBase',
            'MIMEImage', 'MIMEMessage', 'MIMEMultipart',
            'MIMENonMultipart', 'MIMEText', 'Message',
            'Parser', 'Utils', 'base64MIME',
            # new names
            'base64mime', 'charset', 'encoders', 'errors', 'generator',
            'header', 'iterators', 'message', 'message_from_file',
            'message_from_string', 'mime', 'parser',
            'quopriMIME', 'quoprimime', 'utils',
            ]) 
Example #11
Source File: generator.py    From meddle with MIT License 6 votes vote down vote up
def __init__(self, outfp, mangle_from_=True, maxheaderlen=78):
        """Create the generator for message flattening.

        outfp is the output file-like object for writing the message to.  It
        must have a write() method.

        Optional mangle_from_ is a flag that, when True (the default), escapes
        From_ lines in the body of the message by putting a `>' in front of
        them.

        Optional maxheaderlen specifies the longest length for a non-continued
        header.  When a header line is longer (in characters, with tabs
        expanded to 8 spaces) than maxheaderlen, the header will split as
        defined in the Header class.  Set maxheaderlen to zero to disable
        header wrapping.  The default is 78, as recommended (but not required)
        by RFC 2822.
        """
        self._fp = outfp
        self._mangle_from_ = mangle_from_
        self._maxheaderlen = maxheaderlen 
Example #12
Source File: message.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def sanitize_address(addr, encoding):
    if isinstance(addr, six.string_types):
        addr = parseaddr(force_text(addr))
    nm, addr = addr
    # This try-except clause is needed on Python 3 < 3.2.4
    # http://bugs.python.org/issue14291
    try:
        nm = Header(nm, encoding).encode()
    except UnicodeEncodeError:
        nm = Header(nm, 'utf-8').encode()
    try:
        addr.encode('ascii')
    except UnicodeEncodeError:  # IDN
        if '@' in addr:
            localpart, domain = addr.split('@', 1)
            localpart = str(Header(localpart, encoding))
            domain = domain.encode('idna').decode('ascii')
            addr = '@'.join([localpart, domain])
        else:
            addr = Header(addr, encoding).encode()
    return formataddr((nm, addr)) 
Example #13
Source File: test_email_renamed.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_long_lines_with_different_header(self):
        eq = self.ndiffAssertEqual
        h = """\
List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
        <mailto:spamassassin-talk-request@lists.sourceforge.net?subject=unsubscribe>"""
        msg = Message()
        msg['List'] = h
        msg['List'] = Header(h, header_name='List')
        self.ndiffAssertEqual(msg.as_string(), """\
List: List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
 <mailto:spamassassin-talk-request@lists.sourceforge.net?subject=unsubscribe>
List: List-Unsubscribe: <https://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,
 <mailto:spamassassin-talk-request@lists.sourceforge.net?subject=unsubscribe>

""")



# Test mangling of "From " lines in the body of a message 
Example #14
Source File: test_email_renamed.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_get_param(self):
        eq = self.assertEqual
        msg = email.message_from_string(
            "X-Header: foo=one; bar=two; baz=three\n")
        eq(msg.get_param('bar', header='x-header'), 'two')
        eq(msg.get_param('quuz', header='x-header'), None)
        eq(msg.get_param('quuz'), None)
        msg = email.message_from_string(
            'X-Header: foo; bar="one"; baz=two\n')
        eq(msg.get_param('foo', header='x-header'), '')
        eq(msg.get_param('bar', header='x-header'), 'one')
        eq(msg.get_param('baz', header='x-header'), 'two')
        # XXX: We are not RFC-2045 compliant!  We cannot parse:
        # msg["Content-Type"] = 'text/plain; weird="hey; dolly? [you] @ <\\"home\\">?"'
        # msg.get_param("weird")
        # yet. 
Example #15
Source File: test_email_renamed.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_splitting_multiple_long_lines(self):
        eq = self.ndiffAssertEqual
        hstr = """\
from babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <mailman-admin@babylon.socal-raves.org>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
\tfrom babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <mailman-admin@babylon.socal-raves.org>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
\tfrom babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <mailman-admin@babylon.socal-raves.org>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
"""
        h = Header(hstr, continuation_ws='\t')
        eq(h.encode(), """\
from babylon.socal-raves.org (localhost [127.0.0.1]);
\tby babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
\tfor <mailman-admin@babylon.socal-raves.org>;
\tSat, 2 Feb 2002 17:00:06 -0800 (PST)
\tfrom babylon.socal-raves.org (localhost [127.0.0.1]);
\tby babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
\tfor <mailman-admin@babylon.socal-raves.org>;
\tSat, 2 Feb 2002 17:00:06 -0800 (PST)
\tfrom babylon.socal-raves.org (localhost [127.0.0.1]);
\tby babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
\tfor <mailman-admin@babylon.socal-raves.org>;
\tSat, 2 Feb 2002 17:00:06 -0800 (PST)""") 
Example #16
Source File: test_email_renamed.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_splitting_multiple_long_lines(self):
        eq = self.ndiffAssertEqual
        hstr = """\
from babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <mailman-admin@babylon.socal-raves.org>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
\tfrom babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <mailman-admin@babylon.socal-raves.org>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
\tfrom babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <mailman-admin@babylon.socal-raves.org>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)
"""
        h = Header(hstr, continuation_ws='\t')
        eq(h.encode(), """\
from babylon.socal-raves.org (localhost [127.0.0.1]);
\tby babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
\tfor <mailman-admin@babylon.socal-raves.org>;
\tSat, 2 Feb 2002 17:00:06 -0800 (PST)
\tfrom babylon.socal-raves.org (localhost [127.0.0.1]);
\tby babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
\tfor <mailman-admin@babylon.socal-raves.org>;
\tSat, 2 Feb 2002 17:00:06 -0800 (PST)
\tfrom babylon.socal-raves.org (localhost [127.0.0.1]);
\tby babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81;
\tfor <mailman-admin@babylon.socal-raves.org>;
\tSat, 2 Feb 2002 17:00:06 -0800 (PST)""") 
Example #17
Source File: git_multimail_upstream.py    From pagure with GNU General Public License v2.0 6 votes vote down vote up
def addr_header_encode(text, header_name=None):
    """Encode and line-wrap the value of an email header field containing
    email addresses."""

    # Convert to unicode, if required.
    if not isinstance(text, unicode):
        text = unicode(text, "utf-8")

    text = ", ".join(
        formataddr((header_encode(name), emailaddr))
        for name, emailaddr in getaddresses([text])
    )

    if is_ascii(text):
        charset = "ascii"
    else:
        charset = "utf-8"

    return Header(
        text, header_name=header_name, charset=Charset(charset)
    ).encode() 
Example #18
Source File: test_email_renamed.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_encoded_adjacent_nonencoded(self):
        eq = self.assertEqual
        h = Header()
        h.append('hello', 'iso-8859-1')
        h.append('world')
        s = h.encode()
        eq(s, '=?iso-8859-1?q?hello?= world')
        h = make_header(decode_header(s))
        eq(h.encode(), s) 
Example #19
Source File: __init__.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _bind_write_headers(msg):
    def _write_headers(self):
        # Self refers to the Generator object.
        for h, v in msg.items():
            print("%s:" % h, end=" ", file=self._fp)
            if isinstance(v, header.Header):
                print(v.encode(maxlinelen=self._maxheaderlen), file=self._fp)
            else:
                # email.Header got lots of smarts, so use it.
                headers = header.Header(
                    v, maxlinelen=self._maxheaderlen, charset="utf-8", header_name=h
                )
                print(headers.encode(), file=self._fp)
        # A blank line always separates headers from body.
        print(file=self._fp)

    return _write_headers 
Example #20
Source File: send_mail_function.py    From ParrotSecCN_Community_QQbot with GNU General Public License v2.0 5 votes vote down vote up
def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr)) 
Example #21
Source File: mailer.py    From daf-recipes with GNU General Public License v3.0 5 votes vote down vote up
def _mail_recipient(recipient_name, recipient_email,
                    sender_name, sender_url, subject,
                    body, headers={}):
    mail_from = config.get('smtp.mail_from')
    msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8')
    for k, v in headers.items():
        msg[k] = v
    subject = Header(subject.encode('utf-8'), 'utf-8')
    msg['Subject'] = subject
    msg['From'] = _("%s <%s>") % (sender_name, mail_from)
    recipient = u"%s <%s>" % (recipient_name, recipient_email)
    msg['To'] = Header(recipient, 'utf-8')
    msg['Date'] = Utils.formatdate(time())
    msg['X-Mailer'] = "CKAN %s" % ckan.__version__

    # Send the email using Python's smtplib.
    smtp_connection = smtplib.SMTP()
    if 'smtp.test_server' in config:
        # If 'smtp.test_server' is configured we assume we're running tests,
        # and don't use the smtp.server, starttls, user, password etc. options.
        smtp_server = config['smtp.test_server']
        smtp_starttls = False
        smtp_user = None
        smtp_password = None
    else:
        smtp_server = config.get('smtp.server', 'localhost')
        smtp_starttls = paste.deploy.converters.asbool(
            config.get('smtp.starttls'))
        smtp_user = config.get('smtp.user')
        smtp_password = config.get('smtp.password')

    try:
        smtp_connection.connect(smtp_server)
    except socket.error, e:
        log.exception(e)
        raise MailerException('SMTP server could not be connected to: "%s" %s'
                              % (smtp_server, e)) 
Example #22
Source File: response.py    From bioforum with MIT License 5 votes vote down vote up
def _convert_to_charset(self, value, charset, mime_encode=False):
        """
        Convert headers key/value to ascii/latin-1 native strings.

        `charset` must be 'ascii' or 'latin-1'. If `mime_encode` is True and
        `value` can't be represented in the given charset, apply MIME-encoding.
        """
        if not isinstance(value, (bytes, str)):
            value = str(value)
        if ((isinstance(value, bytes) and (b'\n' in value or b'\r' in value)) or
                isinstance(value, str) and ('\n' in value or '\r' in value)):
            raise BadHeaderError("Header values can't contain newlines (got %r)" % value)
        try:
            if isinstance(value, str):
                # Ensure string is valid in given charset
                value.encode(charset)
            else:
                # Convert bytestring using given charset
                value = value.decode(charset)
        except UnicodeError as e:
            if mime_encode:
                value = Header(value, 'utf-8', maxlinelen=sys.maxsize).encode()
            else:
                e.reason += ', HTTP response headers must be in %s format' % charset
                raise
        return value 
Example #23
Source File: generator.py    From BinderFilter with MIT License 5 votes vote down vote up
def _write_headers(self, msg):
        for h, v in msg.items():
            print >> self._fp, '%s:' % h,
            if self._maxheaderlen == 0:
                # Explicit no-wrapping
                print >> self._fp, v
            elif isinstance(v, Header):
                # Header instances know what to do
                print >> self._fp, v.encode()
            elif _is8bitstring(v):
                # If we have raw 8bit data in a byte string, we have no idea
                # what the encoding is.  There is no safe way to split this
                # string.  If it's ascii-subset, then we could do a normal
                # ascii split, but if it's multibyte then we could break the
                # string.  There's no way to know so the least harm seems to
                # be to not split the string and risk it being too long.
                print >> self._fp, v
            else:
                # Header's got lots of smarts, so use it.  Note that this is
                # fundamentally broken though because we lose idempotency when
                # the header string is continued with tabs.  It will now be
                # continued with spaces.  This was reversedly broken before we
                # fixed bug 1974.  Either way, we lose.
                print >> self._fp, Header(
                    v, maxlinelen=self._maxheaderlen, header_name=h).encode()
        # A blank line always separates headers from body
        print >> self._fp

    #
    # Handlers for writing types and subtypes
    # 
Example #24
Source File: test_email_renamed.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_get_params(self):
        eq = self.assertEqual
        msg = email.message_from_string(
            'X-Header: foo=one; bar=two; baz=three\n')
        eq(msg.get_params(header='x-header'),
           [('foo', 'one'), ('bar', 'two'), ('baz', 'three')])
        msg = email.message_from_string(
            'X-Header: foo; bar=one; baz=two\n')
        eq(msg.get_params(header='x-header'),
           [('foo', ''), ('bar', 'one'), ('baz', 'two')])
        eq(msg.get_params(), None)
        msg = email.message_from_string(
            'X-Header: foo; bar="one"; baz=two\n')
        eq(msg.get_params(header='x-header'),
           [('foo', ''), ('bar', 'one'), ('baz', 'two')]) 
Example #25
Source File: test_email_renamed.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_long_header_encode(self):
        eq = self.ndiffAssertEqual
        h = Header('wasnipoop; giraffes="very-long-necked-animals"; '
                   'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"',
                   header_name='X-Foobar-Spoink-Defrobnit')
        eq(h.encode(), '''\
wasnipoop; giraffes="very-long-necked-animals";
 spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"''') 
Example #26
Source File: email.py    From PushBank2 with Apache License 2.0 5 votes vote down vote up
def _execute(self, account, history, param):
        p = param
        param = self.options[param]
        user, target = param.get('user'), param.get('target')
        title = param.get('title').format(**self.format_args(account, history))
        params = {
            'server': param.get('server'),
            'port': param.get('port'),
            'user': param.get('user'),
            'passwd': param.get('password'),
            'tls': param.get('tls', False),
        }
        try:
            session = yield from self._smtp_session(**params)
        except Exception as e:
            logger.error(e)
            return

        content = self.template.render(**history.as_dict())
        corpo = MIMEText(content, 'html', 'utf-8')
        corpo['From'] = user
        corpo['To'] = target
        corpo['Subject'] = Header(title, 'utf-8')
        try:
            session.sendmail(target, [target], corpo.as_string())
        except:
            logger.error('SMTP 서버를 통해 메일을 보내지 못했습니다.')
            traceback.print_exc()
        else:
            logger.info('"{}" 계좌의 내역을 성공적으로 메일로 발송했습니다. ({})'.format(
                account.account, p)) 
Example #27
Source File: send_email.py    From python-tools with MIT License 5 votes vote down vote up
def send_email(server, port, ssl, user, password, to, subject, body):
    """Send html or text email.

    Args:
        server (str): SMTP server.
        port (int): Port.
        ssl (bool): True if use ssl and False if use tls.
        user (str): User address.
        password (str): Password to authenticate.
        to (str/list): Recipients.
        subject (str): Subject.
        body (str): Message, can be string or html.

    """
    if ssl:
        smtp_server = smtplib.SMTP_SSL(server, port)
    else:
        smtp_server = smtplib.SMTP(server, port)
        smtp_server.ehlo()
        smtp_server.starttls()
        smtp_server.ehlo()
    smtp_server.login(user, password)
    types = 'plain'
    regex_html = '(?i)<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|\'.*?\'|[^\'">\s]+))?)+\s*|\s*)\/?>'
    if re.match(regex_html, body):
        types = 'html'
    msg = MIMEMultipart('alternative')
    msg['Subject'] = Header(subject, 'utf-8')
    msg.attach(MIMEText(body, types, 'utf-8'))
    smtp_server.sendmail(user, to, msg.as_string())
    smtp_server.close() 
Example #28
Source File: send_mail_function.py    From ParrotSecCN_Community_QQbot with GNU General Public License v2.0 5 votes vote down vote up
def send_email(email_num, words):
    if SECRETS['qq_mail']['msg_from'] and SECRETS['qq_mail']['passwd']:
        msg_from = SECRETS['qq_mail']['msg_from'] 
        passwd = SECRETS['qq_mail']['passwd'] 
        msg_to = email_num
        subject = 'SS服务器'
        mail_info = words

        # msg = MIMEText(mail_content, "plain", 'utf-8')
        msg = MIMEText(mail_info, "html", 'utf-8')
        msg["Subject"] = Header(subject, 'utf-8')
        msg["From"] = _format_addr(u'Parrot-CN <%s>' % msg_from)
        msg["To"] = _format_addr(u'管理员 <%s>' % msg_to)

        try:
            # ssl登录
            smtp = SMTP_SSL('smtp.qq.com')
            # set_debuglevel()用来调试,1开启调试,0关闭调试
            smtp.set_debuglevel(0)
            smtp.ehlo('smtp.qq.com')
            smtp.login(msg_from, passwd)
            # Send_email
            smtp.sendmail(msg_from, msg_to, msg.as_string())
            smtp.quit()
            return "Mail sent successfully!"
        except Exception as e:
            return "Mail delivery failed!" 
Example #29
Source File: test_email_renamed.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_has_key(self):
        msg = email.message_from_string('Header: exists')
        self.assertTrue(msg.has_key('header'))
        self.assertTrue(msg.has_key('Header'))
        self.assertTrue(msg.has_key('HEADER'))
        self.assertFalse(msg.has_key('headeri')) 
Example #30
Source File: test_email_renamed.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_long_field_name(self):
        eq = self.ndiffAssertEqual
        fn = 'X-Very-Very-Very-Long-Header-Name'
        gs = "Die Mieter treten hier ein werden mit einem Foerderband komfortabel den Korridor entlang, an s\xfcdl\xfcndischen Wandgem\xe4lden vorbei, gegen die rotierenden Klingen bef\xf6rdert. "
        h = Header(gs, 'iso-8859-1', header_name=fn)
        # BAW: this seems broken because the first line is too long
        eq(h.encode(), """\
=?iso-8859-1?q?Die_Mieter_treten_hier_?=
 =?iso-8859-1?q?ein_werden_mit_einem_Foerderband_komfortabel_den_Korridor_?=
 =?iso-8859-1?q?entlang=2C_an_s=FCdl=FCndischen_Wandgem=E4lden_vorbei=2C_g?=
 =?iso-8859-1?q?egen_die_rotierenden_Klingen_bef=F6rdert=2E_?=""")