使用smtp从列表发送邮件

时间:2019-03-28 22:28:47

标签: python smtplib

我正在尝试使用Python将电子邮件发送给收件人列表,但被告知先连接。

 import smtplib

    try:

        s = smtplib.SMTP('smtp.xxx.com', 587)
        s.starttls()

        s.login('barbaramilleraz@xxx.com', 'xxx')
        message = '''

    ...message text...

    '''
        s.connect()
        with open('players.txt') as f:
            email = f.readlines()
            email = [e.strip() for e in email]

            for person in range(len(email)):
                print('Sending email to {}'.format(email[person]))
                s.sendmail('barbaramilleraz', email[person], message)

    except(smtplib.SMTPSenderRefused):
        pass

输出为:

C:\Users\BMiller>python mailing.py
Sending email xxx@xxx.com
Sending email to xxx@xxx.com
Traceback (most recent call last):
  File "mailing.py", line 25, in <module>
    s.sendmail('barbaramilleraz', email[person], message)
  File "C:\Users\BMiller\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 852, in sendmail
    self.ehlo_or_helo_if_needed()
  File "C:\Users\BMiller\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 600, in ehlo_or_helo_if_needed
    if not (200 <= self.ehlo()[0] <= 299):
  File "C:\Users\BMiller\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 440, in ehlo
    self.putcmd(self.ehlo_msg, name or self.local_hostname)
  File "C:\Users\BMiller\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 367, in putcmd
    self.send(str)
  File "C:\Users\BMiller\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 359, in send
    raise SMTPServerDisconnected('please run connect() first')
smtplib.SMTPServerDisconnected: please run connect() first

我是Python的新手,所以不确定如何继续。

谢谢。

2 个答案:

答案 0 :(得分:0)

如dcg在评论中所述,您必须在发送电子邮件之前致电s.connect()建立连接。

您提到的是,每次发送仅发送一次:这是因为发送每条消息后您正在呼叫s.quit()。完成此操作后,s对于所有意图和目的都是无效的:如果要再次使用它,则必须重新启动配置。

因此,在发送所有消息之前,请先致电s.connect(),直到完全完成s.quit()为止,才致电s

答案 1 :(得分:0)

如果想法是在引发异常时跳过收件人,则异常处理应该围绕地址循环内的sendmail调用进行。

        for person in range(len(email)):
            print('Sending email to {}'.format(email[person]))
            try:
                s.sendmail('barbaramilleraz', email[person], message)
            except(smtplib.SMTPSenderRefused):
                print('Sender Refused for {}'.format(email[person]))
                continue