【问题标题】:Send Email to multiple recipients from .txt file with Python smtplib使用 Python smtplib 从 .txt 文件向多个收件人发送电子邮件
【发布时间】:2011-10-19 23:40:44
【问题描述】:

我尝试将邮件从 python 发送到多个电子邮件地址,从 .txt 文件导入,我尝试了不同的语法,但没有任何效果...

代码:

s.sendmail('sender@mail.com', ['recipient@mail.com', 'recipient2@mail.com', 'recipient3@mail.com'], msg.as_string())

所以我尝试从 .txt 文件中导入收件人地址:

urlFile = open("mailList.txt", "r+")
mailList = urlFile.read()
s.sendmail('sender@mail.com', mailList, msg.as_string())

mainList.txt 包含:

['recipient@mail.com', 'recipient2@mail.com', 'recipient3@mail.com']

但它不起作用......

我也尝试过:

... [mailList] ... in the code, and '...','...','...' in the .txt file, but also no effect

... [mailList] ... in the code, and ...','...','... in the .txt file, but also no effect...

有人知道该怎么做吗?

非常感谢!

【问题讨论】:

    标签: python email


    【解决方案1】:

    sendmail 函数需要一个地址列表,您正在向它传递一个字符串。

    如果文件中的地址如您所说的那样格式化,您可以使用eval() 将其转换为列表。

    【讨论】:

      【解决方案2】:
      urlFile = open("mailList.txt", "r+")
      mailList = [i.strip() for i in urlFile.readlines()]
      

      并将每个收件人放在自己的上(即用换行符分隔)。

      【讨论】:

        【解决方案3】:

        它必须是一个真实的列表。所以,在文件中有这个:

        recipient@mail.com,recipient2@mail.com,recipient3@mail.com
        

        你可以的

        mailList = urlFile.read().split(',')
        

        【讨论】:

          【解决方案4】:

          这个问题已经回答了,但还没有完全回答。我的问题是“To:”标头希望电子邮件作为字符串,而 sendmail 函数希望它在列表结构中。

          # list of emails
          emails = ["banjer@example.com", "slingblade@example.com", "dude@example.com"]
          
          # Use a string for the To: header
          msg['To'] = ', '.join( emails )
          
          # Use a list for sendmail function
          s.sendmail(from_email, emails, msg.as_string() )
          

          【讨论】:

            【解决方案5】:

            sendmail 函数调用中的 to_addrs 实际上是所有收件人(to、cc、bcc)的字典,而不仅仅是 to。

            在函数调用中提供所有收件人的同时,您还需要在 msg 中以逗号分隔的字符串格式为每种收件人发送相同收件人的列表。 (到,抄送,密送)。但是您可以轻松地做到这一点,但要维护单独的列表并组合成字符串或将字符串转换成列表。

            这里是例子

            TO = "1@to.com,2@to.com"
            CC = "1@cc.com,2@cc.com"
            msg['To'] = TO
            msg['CC'] = CC
            s.sendmail(from_email, TO.split(',') + CC.split(','), msg.as_string())
            

            TO = ['1@to.com','2@to.com']
            CC = ['1@cc.com','2@cc.com']
            msg['To'] = ",".join(To)
            msg['CC'] = ",".join(CC)
            s.sendmail(from_email, TO+CC, msg.as_string())
            

            【讨论】:

              猜你喜欢
              • 2012-02-09
              • 2015-03-06
              • 2015-08-29
              • 2014-04-02
              • 2023-04-07
              • 2012-05-18
              相关资源
              最近更新 更多