【问题标题】:properly format string of emails using python使用 python 正确格式化电子邮件字符串
【发布时间】:2020-04-22 08:07:29
【问题描述】:

我有一段代码可以从列表中提取电子邮件地址并将它们添加到 MIME 服务的“收件人”字段中。由于错误的电子邮件列表,只有第一个收件人会收到电子邮件。

“list.csv”文件如下所示

john.doe@domain.com
jean.donna@domain.com

我用来格式化地址的代码是这样的:

with open('list.csv') as allusers:
        concat_out =', '.join(email for (email,) in csv.reader(allusers))
receiver = [concat_out]

MIME 部分:

msg = MIMEMultipart()
msg['Subject'] = 'Notification'
msg['From'] = sender
msg['To'] = '; '.join(receiver)

输出:

['john.doe@domain.com, jean.donna@domain.com'] #notice the missing quotes and a comma
                                               #instead of a semi-colon

我怎样才能使列表正确格式化为如下所示?:

['john.doe@domain.com', 'jean.donna@domain.com'] 

感谢任何帮助。

【问题讨论】:

    标签: python-3.x mime


    【解决方案1】:

    为什么不直接创建一个列表,然后从列表中创建一个字符串。

    with open('list.csv') as allusers:
            concat_out = [email for (email,) in csv.reader(allusers)]
    receiver = str(concat_out)
    

    这将为您提供如下输出:

    "['john.doe@domain.com', 'jean.donna@domain.com'] "
    

    【讨论】:

      【解决方案2】:

      这将在不触及旧代码的情况下解决您的问题

      with open('list.csv') as allusers:
              concat_out =', '.join(email for (email,) in csv.reader(allusers))
      reciever=concat_out.split(',')
      print(reciever)
      

      输出:['john.doe@domain.com', 'jean.donna@domain.com']

      【讨论】:

        【解决方案3】:
        email_list = []
        with open('list.csv', 'r') as file:
           for line in file.readlines():
               email_list.append(line.strip('\n'))
        
        print(email_list)
        

        输出: ['john.doe@domain.com', 'jean.donna@domain.com']

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-06-21
          • 2014-02-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-02-13
          相关资源
          最近更新 更多