Send Email to multiple recipients from .txt file with Python smtplib

前端 未结 5 729
不思量自难忘°
不思量自难忘° 2020-12-06 08:23

I try to send mails from python to multiple email-addresses, imported from a .txt file, I\'ve tried differend syntaxes, but nothing would work...

The code:



        
相关标签:
5条回答
  • 2020-12-06 08:30

    It needs to be a real list. So, with this in the file:

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

    you can do

    mailList = urlFile.read().split(',')
    
    0 讨论(0)
  • 2020-12-06 08:39
    urlFile = open("mailList.txt", "r+")
    mailList = [i.strip() for i in urlFile.readlines()]
    

    and put each recipient on its own line (i.e. separate with a line break).

    0 讨论(0)
  • 2020-12-06 08:39

    The sendmail function requires a list of addresses, you are passing it a string.

    If the addresses within the file are formatted as you say, you could use eval() to convert it into a list.

    0 讨论(0)
  • 2020-12-06 08:43

    to_addrs in the sendmail function call is actually a dictionary of all the recipients (to, cc, bcc) and not just to.

    While providing all the recipients in the functional call, you also need to send a list of same recipients in the msg as a comma separated string format for each types of recipients. (to,cc,bcc). But you can do this easily but maintaing either separate lists and combining into string or convert strings into lists.

    Here are the examples

    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())
    

    or

    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())
    
    0 讨论(0)
  • 2020-12-06 08:45

    This question has sort of been answered, but not fully. The issue for me is that "To:" header wants the emails as a string, and the sendmail function wants it in a list structure.

    # 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() )
    
    0 讨论(0)
提交回复
热议问题