标签归档:message

如何在Python中使用自定义消息引发相同的Exception?

问题:如何在Python中使用自定义消息引发相同的Exception?

try我的代码中包含以下代码块:

try:
    do_something_that_might_raise_an_exception()
except ValueError as err:
    errmsg = 'My custom error message.'
    raise ValueError(errmsg)

严格来说,我实际上是提出了另一个问题 ValueError,而不是ValueError抛出do_something...()err在这种情况下称为。如何将自定义消息附加到err?我尝试下面的代码,但失败,因为err,一个ValueError 实例,不是赎回:

try:
    do_something_that_might_raise_an_exception()
except ValueError as err:
    errmsg = 'My custom error message.'
    raise err(errmsg)

I have this try block in my code:

try:
    do_something_that_might_raise_an_exception()
except ValueError as err:
    errmsg = 'My custom error message.'
    raise ValueError(errmsg)

Strictly speaking, I am actually raising another ValueError, not the ValueError thrown by do_something...(), which is referred to as err in this case. How do I attach a custom message to err? I try the following code but fails due to err, a ValueError instance, not being callable:

try:
    do_something_that_might_raise_an_exception()
except ValueError as err:
    errmsg = 'My custom error message.'
    raise err(errmsg)

回答 0

更新:对于Python 3,请检查Ben的答案


将消息附加到当前异常并重新引发它:(外部try / except只是为了显示效果)

对于python 2.x,其中x> = 6:

try:
    try:
      raise ValueError  # something bad...
    except ValueError as err:
      err.message=err.message+" hello"
      raise              # re-raise current exception
except ValueError as e:
    print(" got error of type "+ str(type(e))+" with message " +e.message)

这也将做正确的事情,如果err衍生ValueError。例如UnicodeDecodeError

请注意,您可以添加任何内容err。例如err.problematic_array=[1,2,3]


编辑: @Ducan在注释中指出以上内容不适用于python 3,因为.message它不是的成员ValueError。相反,您可以使用此代码(有效的python 2.6或更高版本或3.x):

try:
    try:
      raise ValueError
    except ValueError as err:
       if not err.args: 
           err.args=('',)
       err.args = err.args + ("hello",)
       raise 
except ValueError as e:
    print(" error was "+ str(type(e))+str(e.args))

编辑2:

根据目的,您还可以选择在自己的变量名下添加额外的信息。对于python2和python3:

try:
    try:
      raise ValueError
    except ValueError as err:
       err.extra_info = "hello"
       raise 
except ValueError as e:
    print(" error was "+ str(type(e))+str(e))
    if 'extra_info' in dir(e):
       print e.extra_info

Update: For Python 3, check Ben’s answer


To attach a message to the current exception and re-raise it: (the outer try/except is just to show the effect)

For python 2.x where x>=6:

try:
    try:
      raise ValueError  # something bad...
    except ValueError as err:
      err.message=err.message+" hello"
      raise              # re-raise current exception
except ValueError as e:
    print(" got error of type "+ str(type(e))+" with message " +e.message)

This will also do the right thing if err is derived from ValueError. For example UnicodeDecodeError.

Note that you can add whatever you like to err. For example err.problematic_array=[1,2,3].


Edit: @Ducan points in a comment the above does not work with python 3 since .message is not a member of ValueError. Instead you could use this (valid python 2.6 or later or 3.x):

try:
    try:
      raise ValueError
    except ValueError as err:
       if not err.args: 
           err.args=('',)
       err.args = err.args + ("hello",)
       raise 
except ValueError as e:
    print(" error was "+ str(type(e))+str(e.args))

Edit2:

Depending on what the purpose is, you can also opt for adding the extra information under your own variable name. For both python2 and python3:

try:
    try:
      raise ValueError
    except ValueError as err:
       err.extra_info = "hello"
       raise 
except ValueError as e:
    print(" error was "+ str(type(e))+str(e))
    if 'extra_info' in dir(e):
       print e.extra_info

回答 1

如果您有幸仅支持python 3.x,那么这真的很美:)

从…提高

我们可以使用raise from链接异常。

try:
    1 / 0
except ZeroDivisionError as e:
    raise Exception('Smelly socks') from e

在这种情况下,您的调用方法将捕获的异常具有我们提出异常的地方的行号。

Traceback (most recent call last):
  File "test.py", line 2, in <module>
    1 / 0
ZeroDivisionError: division by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    raise Exception('Smelly socks') from e
Exception: Smelly socks

请注意,底部异常仅包含引发异常的堆栈跟踪。您的调用者仍然可以通过访问__cause__他们捕获的异常的属性来获取原始异常。

with_traceback

或者,您可以使用with_traceback

try:
    1 / 0
except ZeroDivisionError as e:
    raise Exception('Smelly socks').with_traceback(e.__traceback__)

使用此表单,您的调用者将捕获的异常具有追溯到原始错误发生的位置。

Traceback (most recent call last):
  File "test.py", line 2, in <module>
    1 / 0
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    raise Exception('Smelly socks').with_traceback(e.__traceback__)
  File "test.py", line 2, in <module>
    1 / 0
Exception: Smelly socks

请注意,底部异常包含执行无效除法的行以及重新引发异常的行。

If you’re lucky enough to only support python 3.x, this really becomes a thing of beauty :)

raise from

We can chain the exceptions using raise from.

try:
    1 / 0
except ZeroDivisionError as e:
    raise Exception('Smelly socks') from e

In this case, the exception your caller would catch has the line number of the place where we raise our exception.

Traceback (most recent call last):
  File "test.py", line 2, in <module>
    1 / 0
ZeroDivisionError: division by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    raise Exception('Smelly socks') from e
Exception: Smelly socks

Notice the bottom exception only has the stacktrace from where we raised our exception. Your caller could still get the original exception by accessing the __cause__ attribute of the exception they catch.

with_traceback

Or you can use with_traceback.

try:
    1 / 0
except ZeroDivisionError as e:
    raise Exception('Smelly socks').with_traceback(e.__traceback__)

Using this form, the exception your caller would catch has the traceback from where the original error occurred.

Traceback (most recent call last):
  File "test.py", line 2, in <module>
    1 / 0
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    raise Exception('Smelly socks').with_traceback(e.__traceback__)
  File "test.py", line 2, in <module>
    1 / 0
Exception: Smelly socks

Notice the bottom exception has the line where we performed the invalid division as well as the line where we reraise the exception.


回答 2

try:
    try:
        int('a')
    except ValueError as e:
        raise ValueError('There is a problem: {0}'.format(e))
except ValueError as err:
    print err

印刷品:

There is a problem: invalid literal for int() with base 10: 'a'
try:
    try:
        int('a')
    except ValueError as e:
        raise ValueError('There is a problem: {0}'.format(e))
except ValueError as err:
    print err

prints:

There is a problem: invalid literal for int() with base 10: 'a'

回答 3

似乎所有答案都将信息添加到e.args [0],从而更改了现有的错误消息。扩展args元组有不利之处吗?我认为可能的好处是,在需要解析该字符串的情况下,您可以不考虑原始错误消息。如果您的自定义错误处理产生了多个消息或错误代码,并且可以通过编程方式(例如通过系统监视工具)解析回溯,则可以在元组中添加多个元素。

## Approach #1, if the exception may not be derived from Exception and well-behaved:

def to_int(x):
    try:
        return int(x)
    except Exception as e:
        e.args = (e.args if e.args else tuple()) + ('Custom message',)
        raise

>>> to_int('12')
12

>>> to_int('12 monkeys')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in to_int
ValueError: ("invalid literal for int() with base 10: '12 monkeys'", 'Custom message')

要么

## Approach #2, if the exception is always derived from Exception and well-behaved:

def to_int(x):
    try:
        return int(x)
    except Exception as e:
        e.args += ('Custom message',)
        raise

>>> to_int('12')
12

>>> to_int('12 monkeys')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in to_int
ValueError: ("invalid literal for int() with base 10: '12 monkeys'", 'Custom message')

您能看到这种方法的缺点吗?

It seems all the answers are adding info to e.args[0], thereby altering the existing error message. Is there a downside to extending the args tuple instead? I think the possible upside is, you can leave the original error message alone for cases where parsing that string is needed; and you could add multiple elements to the tuple if your custom error handling produced several messages or error codes, for cases where the traceback would be parsed programmatically (like via a system monitoring tool).

## Approach #1, if the exception may not be derived from Exception and well-behaved:

def to_int(x):
    try:
        return int(x)
    except Exception as e:
        e.args = (e.args if e.args else tuple()) + ('Custom message',)
        raise

>>> to_int('12')
12

>>> to_int('12 monkeys')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in to_int
ValueError: ("invalid literal for int() with base 10: '12 monkeys'", 'Custom message')

or

## Approach #2, if the exception is always derived from Exception and well-behaved:

def to_int(x):
    try:
        return int(x)
    except Exception as e:
        e.args += ('Custom message',)
        raise

>>> to_int('12')
12

>>> to_int('12 monkeys')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in to_int
ValueError: ("invalid literal for int() with base 10: '12 monkeys'", 'Custom message')

Can you see a downside to this approach?


回答 4

此代码模板应允许您使用自定义消息引发异常。

try:
     raise ValueError
except ValueError as err:
    raise type(err)("my message")

This code template should allow you to raise an exception with a custom message.

try:
     raise ValueError
except ValueError as err:
    raise type(err)("my message")

回答 5

使用以下错误消息引发新异常

raise Exception('your error message')

要么

raise ValueError('your error message')

在您要引发它的地方或使用’from’将错误消息附加(替换)到当前异常中(仅支持Python 3.x):

except ValueError as e:
  raise ValueError('your message') from e

Either raise the new exception with your error message using

raise Exception('your error message')

or

raise ValueError('your error message')

within the place where you want to raise it OR attach (replace) error message into current exception using ‘from’ (Python 3.x supported only):

except ValueError as e:
  raise ValueError('your message') from e

回答 6

这是我用来在保留原始回溯的同时修改Python 2.7和3.x中的异常消息的功能。这个需要six

def reraise_modify(caught_exc, append_msg, prepend=False):
    """Append message to exception while preserving attributes.

    Preserves exception class, and exception traceback.

    Note:
        This function needs to be called inside an except because
        `sys.exc_info()` requires the exception context.

    Args:
        caught_exc(Exception): The caught exception object
        append_msg(str): The message to append to the caught exception
        prepend(bool): If True prepend the message to args instead of appending

    Returns:
        None

    Side Effects:
        Re-raises the exception with the preserved data / trace but
        modified message
    """
    ExceptClass = type(caught_exc)
    # Keep old traceback
    traceback = sys.exc_info()[2]
    if not caught_exc.args:
        # If no args, create our own tuple
        arg_list = [append_msg]
    else:
        # Take the last arg
        # If it is a string
        # append your message.
        # Otherwise append it to the
        # arg list(Not as pretty)
        arg_list = list(caught_exc.args[:-1])
        last_arg = caught_exc.args[-1]
        if isinstance(last_arg, str):
            if prepend:
                arg_list.append(append_msg + last_arg)
            else:
                arg_list.append(last_arg + append_msg)
        else:
            arg_list += [last_arg, append_msg]
    caught_exc.args = tuple(arg_list)
    six.reraise(ExceptClass,
                caught_exc,
                traceback)

This is the function I use to modify the exception message in Python 2.7 and 3.x while preserving the original traceback. It requires six

def reraise_modify(caught_exc, append_msg, prepend=False):
    """Append message to exception while preserving attributes.

    Preserves exception class, and exception traceback.

    Note:
        This function needs to be called inside an except because
        `sys.exc_info()` requires the exception context.

    Args:
        caught_exc(Exception): The caught exception object
        append_msg(str): The message to append to the caught exception
        prepend(bool): If True prepend the message to args instead of appending

    Returns:
        None

    Side Effects:
        Re-raises the exception with the preserved data / trace but
        modified message
    """
    ExceptClass = type(caught_exc)
    # Keep old traceback
    traceback = sys.exc_info()[2]
    if not caught_exc.args:
        # If no args, create our own tuple
        arg_list = [append_msg]
    else:
        # Take the last arg
        # If it is a string
        # append your message.
        # Otherwise append it to the
        # arg list(Not as pretty)
        arg_list = list(caught_exc.args[:-1])
        last_arg = caught_exc.args[-1]
        if isinstance(last_arg, str):
            if prepend:
                arg_list.append(append_msg + last_arg)
            else:
                arg_list.append(last_arg + append_msg)
        else:
            arg_list += [last_arg, append_msg]
    caught_exc.args = tuple(arg_list)
    six.reraise(ExceptClass,
                caught_exc,
                traceback)

回答 7

Python 3内置异常具有以下strerror字段:

except ValueError as err:
  err.strerror = "New error message"
  raise err

Python 3 built-in exceptions have the strerror field:

except ValueError as err:
  err.strerror = "New error message"
  raise err

回答 8

当前的答案对我没有用,如果未重新捕获异常,则不会显示附加的消息。

但是,无论是否重新捕获异常,下面的操作都将保留跟踪并显示附加的消息。

try:
  raise ValueError("Original message")
except ValueError as err:
  t, v, tb = sys.exc_info()
  raise t, ValueError(err.message + " Appended Info"), tb

(我使用的是Python 2.7,还没有在Python 3中尝试过)

The current answer did not work good for me, if the exception is not re-caught the appended message is not shown.

But doing like below both keeps the trace and shows the appended message regardless if the exception is re-caught or not.

try:
  raise ValueError("Original message")
except ValueError as err:
  t, v, tb = sys.exc_info()
  raise t, ValueError(err.message + " Appended Info"), tb

( I used Python 2.7, have not tried it in Python 3 )


回答 9

以上解决方案均未达到我想要的目的,即向错误消息的第一部分添加了一些信息,即我希望用户首先看到我的自定义消息。

这为我工作:

exception_raised = False
try:
    do_something_that_might_raise_an_exception()
except ValueError as e:
    message = str(e)
    exception_raised = True

if exception_raised:
    message_to_prepend = "Custom text"
    raise ValueError(message_to_prepend + message)

None of the above solutions did exactly what I wanted, which was to add some information to the first part of the error message i.e. I wanted my users to see my custom message first.

This worked for me:

exception_raised = False
try:
    do_something_that_might_raise_an_exception()
except ValueError as e:
    message = str(e)
    exception_raised = True

if exception_raised:
    message_to_prepend = "Custom text"
    raise ValueError(message_to_prepend + message)

回答 10

这仅适用于Python 3。您可以修改异常的原始参数并添加自己的参数。

异常会记住创建它的参数。我认为这是为了您可以修改异常。

在函数中,reraise我们在异常的原始参数之前添加了所需的任何新参数(例如消息)。最后,我们在保留追溯历史的同时重新引发异常。

def reraise(e, *args):
  '''re-raise an exception with extra arguments
  :param e: The exception to reraise
  :param args: Extra args to add to the exception
  '''

  # e.args is a tuple of arguments that the exception with instantiated with.
  #
  e.args = args + e.args

  # Recreate the expection and preserve the traceback info so thta we can see 
  # where this exception originated.
  #
  raise e.with_traceback(e.__traceback__)   


def bad():
  raise ValueError('bad')

def very():
  try:
    bad()
  except Exception as e:
    reraise(e, 'very')

def very_very():
  try:
    very()
  except Exception as e:
    reraise(e, 'very')

very_very()

输出

Traceback (most recent call last):
  File "main.py", line 35, in <module>
    very_very()
  File "main.py", line 30, in very_very
    reraise(e, 'very')
  File "main.py", line 15, in reraise
    raise e.with_traceback(e.__traceback__)
  File "main.py", line 28, in very_very
    very()
  File "main.py", line 24, in very
    reraise(e, 'very')
  File "main.py", line 15, in reraise
    raise e.with_traceback(e.__traceback__)
  File "main.py", line 22, in very
    bad()
  File "main.py", line 18, in bad
    raise ValueError('bad')
ValueError: ('very', 'very', 'bad')

This only works with Python 3. You can modify the exception’s original arguments and add your own arguments.

An exception remembers the args it was created with. I presume this is so that you can modify the exception.

In the function reraise we prepend the exception’s original arguments with any new arguments that we want (like a message). Finally we re-raise the exception while preserving the trace-back history.

def reraise(e, *args):
  '''re-raise an exception with extra arguments
  :param e: The exception to reraise
  :param args: Extra args to add to the exception
  '''

  # e.args is a tuple of arguments that the exception with instantiated with.
  #
  e.args = args + e.args

  # Recreate the expection and preserve the traceback info so thta we can see 
  # where this exception originated.
  #
  raise e.with_traceback(e.__traceback__)   


def bad():
  raise ValueError('bad')

def very():
  try:
    bad()
  except Exception as e:
    reraise(e, 'very')

def very_very():
  try:
    very()
  except Exception as e:
    reraise(e, 'very')

very_very()

output

Traceback (most recent call last):
  File "main.py", line 35, in <module>
    very_very()
  File "main.py", line 30, in very_very
    reraise(e, 'very')
  File "main.py", line 15, in reraise
    raise e.with_traceback(e.__traceback__)
  File "main.py", line 28, in very_very
    very()
  File "main.py", line 24, in very
    reraise(e, 'very')
  File "main.py", line 15, in reraise
    raise e.with_traceback(e.__traceback__)
  File "main.py", line 22, in very
    bad()
  File "main.py", line 18, in bad
    raise ValueError('bad')
ValueError: ('very', 'very', 'bad')

回答 11

如果要自定义错误类型,您可以做的一件简单的事情就是基于ValueError定义一个错误类。

if you want to custom the error type, a simple thing you can do is to define an error class based on ValueError.


如何使用python smtplib向多个收件人发送电子邮件?

问题:如何使用python smtplib向多个收件人发送电子邮件?

经过大量搜索后,我无法找到如何使用smtplib.sendmail发送给多个收件人的方法。问题是每次发送邮件时,邮件标题似乎都包含多个地址,但实际上只有第一个收件人会收到电子邮件。

问题似乎在于email.Message模块期望的smtplib.sendmail()功能与功能不同。

简而言之,要发送给多个收件人,您应该将标题设置为以逗号分隔的电子邮件地址的字符串。但是,该sendmail()参数to_addrs应为电子邮件地址列表。

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import smtplib

msg = MIMEMultipart()
msg["Subject"] = "Example"
msg["From"] = "me@example.com"
msg["To"] = "malcom@example.com,reynolds@example.com,firefly@example.com"
msg["Cc"] = "serenity@example.com,inara@example.com"
body = MIMEText("example email body")
msg.attach(body)
smtp = smtplib.SMTP("mailhost.example.com", 25)
smtp.sendmail(msg["From"], msg["To"].split(",") + msg["Cc"].split(","), msg.as_string())
smtp.quit()

After much searching I couldn’t find out how to use smtplib.sendmail to send to multiple recipients. The problem was every time the mail would be sent the mail headers would appear to contain multiple addresses, but in fact only the first recipient would receive the email.

The problem seems to be that the email.Message module expects something different than the smtplib.sendmail() function.

In short, to send to multiple recipients you should set the header to be a string of comma delimited email addresses. The sendmail() parameter to_addrs however should be a list of email addresses.

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import smtplib

msg = MIMEMultipart()
msg["Subject"] = "Example"
msg["From"] = "me@example.com"
msg["To"] = "malcom@example.com,reynolds@example.com,firefly@example.com"
msg["Cc"] = "serenity@example.com,inara@example.com"
body = MIMEText("example email body")
msg.attach(body)
smtp = smtplib.SMTP("mailhost.example.com", 25)
smtp.sendmail(msg["From"], msg["To"].split(",") + msg["Cc"].split(","), msg.as_string())
smtp.quit()

回答 0

确实有效,我花了大量时间尝试多种变体。

import smtplib
from email.mime.text import MIMEText

s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = 'me@example.com'
recipients = ['john.doe@example.com', 'john.smith@example.co.uk']
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
s.sendmail(sender, recipients, msg.as_string())

This really works, I spent a lot of time trying multiple variants.

import smtplib
from email.mime.text import MIMEText

s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = 'me@example.com'
recipients = ['john.doe@example.com', 'john.smith@example.co.uk']
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
s.sendmail(sender, recipients, msg.as_string())

回答 1

msg['To']需要是一个字符串:

msg['To'] = "a@b.com, b@b.com, c@b.com"

虽然recipientsin sendmail(sender, recipients, message)需要是一个列表:

sendmail("a@a.com", ["a@b.com", "b@b.com", "c@b.com"], "Howdy")

The msg['To'] needs to be a string:

msg['To'] = "a@b.com, b@b.com, c@b.com"

While the recipients in sendmail(sender, recipients, message) needs to be a list:

sendmail("a@a.com", ["a@b.com", "b@b.com", "c@b.com"], "Howdy")

回答 2

您需要了解电子邮件的可见地址和投递之间的区别。

msg["To"]本质上是印刷在信件上的东西。它实际上没有任何作用。除了您的电子邮件客户端(与常规邮递员一样)之外,您还将假定这是您要将电子邮件发送给的人。

但是,实际交付可能会大不相同。所以你可以将电子邮件(或副本)放入完全不同的人的邮箱中。

有多种原因。例如转发。的To:头字段不上转发更改,但是,电子邮件被放入不同的邮箱。

smtp.sendmail现在,该命令将负责实际交付。email.Message仅是信件的内容,而不是交货的内容。

在低级中SMTP,您需要一个个地给接收者一个地址,这就是为什么地址列表(不包括名称!)才是明智的API的原因。

对于标题,它还可以包含例如名称,例如To: First Last <email@addr.tld>, Other User <other@mail.tld>因此,不建议您使用代码示例,因为它将无法传递此邮件,因为仅将其拆分给,您,您仍然没有有效的地址!

You need to understand the difference between the visible address of an email, and the delivery.

msg["To"] is essentially what is printed on the letter. It doesn’t actually have any effect. Except that your email client, just like the regular post officer, will assume that this is who you want to send the email to.

The actual delivery however can work quite different. So you can drop the email (or a copy) into the post box of someone completely different.

There are various reasons for this. For example forwarding. The To: header field doesn’t change on forwarding, however the email is dropped into a different mailbox.

The smtp.sendmail command now takes care of the actual delivery. email.Message is the contents of the letter only, not the delivery.

In low-level SMTP, you need to give the receipients one-by-one, which is why a list of adresses (not including names!) is the sensible API.

For the header, it can also contain for example the name, e.g. To: First Last <email@addr.tld>, Other User <other@mail.tld>. Your code example therefore is not recommended, as it will fail delivering this mail, since just by splitting it on , you still not not have the valid adresses!


回答 3

这个对我有用。

import smtplib
from email.mime.text import MIMEText

s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = 'me@example.com'
recipients = 'john.doe@example.com,john.smith@example.co.uk'
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = recipients
s.sendmail(sender, recipients.split(','), msg.as_string())

It works for me.

import smtplib
from email.mime.text import MIMEText

s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = 'me@example.com'
recipients = 'john.doe@example.com,john.smith@example.co.uk'
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = recipients
s.sendmail(sender, recipients.split(','), msg.as_string())

回答 4

我尝试了下面的方法,它就像一个魅力:)

rec_list =  ['first@example.com', 'second@example.com']
rec =  ', '.join(rec_list)

msg['To'] = rec

send_out = smtplib.SMTP('localhost')
send_out.sendmail(me, rec_list, msg.as_string())

I tried the below and it worked like a charm :)

rec_list =  ['first@example.com', 'second@example.com']
rec =  ', '.join(rec_list)

msg['To'] = rec

send_out = smtplib.SMTP('localhost')
send_out.sendmail(me, rec_list, msg.as_string())

回答 5

所以实际上问题是SMTP.sendmail和email.MIMEText需要两个不同的东西。

email.MIMEText设置电子邮件正文的“ To:”标头。它仅用于向另一端的人显示结果,并且像所有电子邮件头一样,必须为单个字符串。(请注意,它实际上与实际收到邮件的人没有任何关系。)

另一方面,SMTP.sendmail为SMTP协议设置邮件的“信封”。它需要一个Python字符串列表,每个字符串都有一个地址。

因此,您需要做的就是合并收到的两份回复。将msg [‘To’]设置为单个字符串,但将原始列表传递给sendmail:

emails = ['a.com','b.com', 'c.com']
msg['To'] = ', '.join( emails ) 
....
s.sendmail( msg['From'], emails, msg.as_string())

So actually the problem is that SMTP.sendmail and email.MIMEText need two different things.

email.MIMEText sets up the “To:” header for the body of the e-mail. It is ONLY used for displaying a result to the human being at the other end, and like all e-mail headers, must be a single string. (Note that it does not actually have to have anything to do with the people who actually receive the message.)

SMTP.sendmail, on the other hand, sets up the “envelope” of the message for the SMTP protocol. It needs a Python list of strings, each of which has a single address.

So, what you need to do is COMBINE the two replies you received. Set msg[‘To’] to a single string, but pass the raw list to sendmail:

emails = ['a.com','b.com', 'c.com']
msg['To'] = ', '.join( emails ) 
....
s.sendmail( msg['From'], emails, msg.as_string())

回答 6

我想出了这个可导入的模块功能。在此示例中,它使用gmail电子邮件服务器。它分为标题和消息,因此您可以清楚地看到发生了什么:

import smtplib

def send_alert(subject=""):

    to = ['email@one.com', 'email2@another_email.com', 'a3rd@email.com']
    gmail_user = 'me@gmail.com'
    gmail_pwd = 'my_pass'
    smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(gmail_user, gmail_pwd)
    header = 'To:' + ", ".join(to) + '\n' + 'From: ' + gmail_user + '\n' + 'Subject: ' + subject + '\n'
    msg = header + '\n' + subject + '\n\n'
    smtpserver.sendmail(gmail_user, to, msg)
    smtpserver.close()

I came up with this importable module function. It uses the gmail email server in this example. Its split into header and message so you can clearly see whats going on:

import smtplib

def send_alert(subject=""):

    to = ['email@one.com', 'email2@another_email.com', 'a3rd@email.com']
    gmail_user = 'me@gmail.com'
    gmail_pwd = 'my_pass'
    smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(gmail_user, gmail_pwd)
    header = 'To:' + ", ".join(to) + '\n' + 'From: ' + gmail_user + '\n' + 'Subject: ' + subject + '\n'
    msg = header + '\n' + subject + '\n\n'
    smtpserver.sendmail(gmail_user, to, msg)
    smtpserver.close()

回答 7

几个月前我弄清楚了,然后发表了博客。摘要是:

如果要使用smtplib向多个收件人发送电子邮件,请使用email.Message.add_header('To', eachRecipientAsString)添加它们,然后在调用sendmail方法时,use email.Message.get_all('To')将消息发送给所有收件人。抄送和密件抄送收件人的同上。

I figured this out a few months back and blogged about it. The summary is:

If you want to use smtplib to send email to multiple recipients, use email.Message.add_header('To', eachRecipientAsString) to add them, and then when you invoke the sendmail method, use email.Message.get_all('To') send the message to all of them. Ditto for Cc and Bcc recipients.


回答 8

下面的解决方案为我工作。它成功地将电子邮件发送给多个收件人,包括“抄送”和“密件抄送”。

toaddr = ['mailid_1','mailid_2']
cc = ['mailid_3','mailid_4']
bcc = ['mailid_5','mailid_6']
subject = 'Email from Python Code'
fromaddr = 'sender_mailid'
message = "\n  !! Hello... !!"

msg['From'] = fromaddr
msg['To'] = ', '.join(toaddr)
msg['Cc'] = ', '.join(cc)
msg['Bcc'] = ', '.join(bcc)
msg['Subject'] = subject

s.sendmail(fromaddr, (toaddr+cc+bcc) , message)

The solution below worked for me. It successfully sends an email to multiple recipients, including “CC” and “BCC.”

toaddr = ['mailid_1','mailid_2']
cc = ['mailid_3','mailid_4']
bcc = ['mailid_5','mailid_6']
subject = 'Email from Python Code'
fromaddr = 'sender_mailid'
message = "\n  !! Hello... !!"

msg['From'] = fromaddr
msg['To'] = ', '.join(toaddr)
msg['Cc'] = ', '.join(cc)
msg['Bcc'] = ', '.join(bcc)
msg['Subject'] = subject

s.sendmail(fromaddr, (toaddr+cc+bcc) , message)

回答 9

那么,在方法本asnwer方法并没有为我工作。我不知道,也许这是Python3(我正在使用3.4版本)或gmail相关问题,但是经过一番尝试之后,对我有用的解决方案是

s.send_message(msg)

代替

s.sendmail(sender, recipients, msg.as_string())

Well, the method in this asnwer method did not work for me. I don’t know, maybe this is a Python3 (I am using the 3.4 version) or gmail related issue, but after some tries, the solution that worked for me, was the line

s.send_message(msg)

instead of

s.sendmail(sender, recipients, msg.as_string())

回答 10

我使用python 3.6,以下代码对我有用

email_send = 'xxxxx@xxx.xxx,xxxx@xxx.xxx'
server.sendmail(email_user,email_send.split(','),text)    

I use python 3.6 and the following code works for me

email_send = 'xxxxx@xxx.xxx,xxxx@xxx.xxx'
server.sendmail(email_user,email_send.split(','),text)    

回答 11

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def sender(recipients): 

    body = 'Your email content here'
    msg = MIMEMultipart()

    msg['Subject'] = 'Email Subject'
    msg['From'] = 'your.email@gmail.com'
    msg['To'] = (', ').join(recipients.split(','))

    msg.attach(MIMEText(body,'plain'))

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login('your.email@gmail.com', 'yourpassword')
    server.send_message(msg)
    server.quit()

if __name__ == '__main__':
    sender('email_1@domain.com,email_2@domain.com')

它仅对我有用send_message函数,并在列表中使用接收函数python 3.6中的join函数。

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def sender(recipients): 

    body = 'Your email content here'
    msg = MIMEMultipart()

    msg['Subject'] = 'Email Subject'
    msg['From'] = 'your.email@gmail.com'
    msg['To'] = (', ').join(recipients.split(','))

    msg.attach(MIMEText(body,'plain'))

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login('your.email@gmail.com', 'yourpassword')
    server.send_message(msg)
    server.quit()

if __name__ == '__main__':
    sender('email_1@domain.com,email_2@domain.com')

It only worked for me with send_message function and using the join function in the list whith recipients, python 3.6.


回答 12

您可以在文本文件上写收件人电子邮件时尝试使用此方法

from email.mime.text import MIMEText
from email.header import Header
import smtplib

f =  open('emails.txt', 'r').readlines()
for n in f:
     emails = n.rstrip()
server = smtplib.SMTP('smtp.uk.xensource.com')
server.ehlo()
server.starttls()
body = "Test Email"
subject = "Test"
from = "me@example.com"
to = emails
msg = MIMEText(body,'plain','utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] =  Header(from, 'utf-8')
msg['To'] = Header(to, 'utf-8')
text = msg.as_string()
try:
   server.send(from, emails, text)
   print('Message Sent Succesfully')
except:
   print('There Was An Error While Sending The Message')

you can try this when you write the recpient emails on a text file

from email.mime.text import MIMEText
from email.header import Header
import smtplib

f =  open('emails.txt', 'r').readlines()
for n in f:
     emails = n.rstrip()
server = smtplib.SMTP('smtp.uk.xensource.com')
server.ehlo()
server.starttls()
body = "Test Email"
subject = "Test"
from = "me@example.com"
to = emails
msg = MIMEText(body,'plain','utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] =  Header(from, 'utf-8')
msg['To'] = Header(to, 'utf-8')
text = msg.as_string()
try:
   server.send(from, emails, text)
   print('Message Sent Succesfully')
except:
   print('There Was An Error While Sending The Message')