使用smtp从列表发送邮件

2024-04-19 21:48:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图用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新手,所以我不知道如何继续。你知道吗

谢谢你。你知道吗


Tags: inpyselfemailliblocallineusers
2条回答

正如dcg在评论中所说的,在发送电子邮件之前,您必须调用s.connect()来建立连接。你知道吗

当你这么做的时候,你提到它只发送一次:这是因为你在发送每一条消息之后都在给s.quit()打电话。一旦你做了那件事,s就没有任何意图和目的了:如果你想再次使用它,你必须重新启动配置。你知道吗

所以,在发送所有消息之前,先给s.connect()打一次电话,在你完全处理完s之前,不要给s.quit()打电话。你知道吗

如果想法是在引发异常时跳过收件人,那么异常处理应该围绕地址循环中的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

相关问题 更多 >