开发者

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

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:

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

So I tried this to import the recipient-addresses from a .txt file:

urlFile = open("mailList.txt", "r+")
mailList = urlFile.r开发者_如何转开发ead()
s.sendmail('sender@mail.com', mailList, msg.as_string())

The mainList.txt contains:

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

But it doesn't work...

I've also tried to do:

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

and

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

Does anyone knows what to do?

Thanks a lot!


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


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


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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜