簡體   English   中英

使用Python smtplib從.txt文件向多個收件人發送電子郵件

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

我嘗試從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...

有誰知道該怎么辦?

非常感謝!

這個問題已經得到了回答,但還沒有完全解決。 對我來說,問題是“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() )
urlFile = open("mailList.txt", "r+")
mailList = [i.strip() for i in urlFile.readlines()]

並將每個收件人放在自己的行上 (即與換行符分開)。

sendmail函數需要一個地址列表,你傳遞一個字符串。

如果文件中的地址按照您的說法進行格式化,則可以使用eval()將其轉換為列表。

它需要是一個真實的清單。 所以,在文件中有這個:

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

你可以做

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

sendmail函數調用中的to_addrs實際上是所有收件人(to,cc,bcc)的字典,而不僅僅是。

在功能調用中提供所有收件人時,還需要在msg中發送相同收件人的列表,作為每種類型收件人的逗號分隔字符串格式。 (到,CC,BCC)。 但您可以輕松地執行此操作,但維護單獨的列表並組合成字符串或將字符串轉換為列表。

以下是示例

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

暫無
暫無

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

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