簡體   English   中英

使用smtp從列表發送郵件

[英]Sending mail from a list with smtp

我正在嘗試使用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的新手,所以不確定如何繼續。

謝謝。

正如dcg在評論中所說,您必須在發送電子郵件之前調用s.connect()建立連接。

您提到它在執行此操作時僅發送一次:這是因為在發送每條消息后要調用s.quit() 完成此操作后, s就所有意圖而言都是無效的:如果要再次使用它,則必須重新啟動配置。

於是呼s.connect()一次發送的所有消息之前,不要叫s.quit()直到你完全符合做s

如果想法是在引發異常時跳過收件人,則異常處理應圍繞地址循環內的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM