从txt文件中的数组发送单个电子邮件

时间:2019-02-05 07:29:33

标签: python smtplib

我的代码获取txt文件,然后将电子邮件发送到列表中的第一封电子邮件,然后停止并且不对下一封电子邮件进行处理。我在用这个数组做错什么了?

我尝试创建一个数组来为target_email中的每封电子邮件运行该功能,并且它仅将电子邮件发送到数组中的第一封电子邮件。当我打印数组时,它看起来像这样[123@txt.att.net, 876@txt.att.net]

####the py script

import time
import smtplib

#CONFIG. You can change any of the values on the right.
email_provider = '' #server for your email- see ReadMe on github
email_address = "" #your email
email_port = 587 #port for email server- see ReadMe on github
password = "" #your email password
msg = "Meow" #your txt message
text_amount = 1 #amount sent

#Gets phone number emails from txt file
text_file = open("mails.txt", "r")
target_email = text_file.readlines()

wait = 15 #seconds in between messages
#END CONFIG

#Loops for each phone email in list text_amount of times
for emails in target_email:
     server = smtplib.SMTP(email_provider, email_port)
     server.starttls()
     server.login(email_address, password)
        for _ in range(0,text_amount):
         server.sendmail(email_address,target_email,msg)
         print("sent")
         time.sleep(wait)
print("{} texts were sent.".format(text_amount))


###the txt file contents

123@txt.att.net, 876@txt.att.net

该脚本应分别为每封电子邮件运行### DO NOT EDIT BELOW THIS LINE ###,而不是BBC,或者只发送给一封电子邮件并停止。

1 个答案:

答案 0 :(得分:1)

您将发送完整列表,而不是发送单个电子邮件地址。

使用:

#Loops for each phone email in list text_amount of times
for emails in target_email:
    ### DO NOT EDIT BELOW THIS LINE ###
    server = smtplib.SMTP(email_provider, email_port)
    server.starttls()
    server.login(email_address, password)
    for _ in range(0,text_amount):
        server.sendmail(email_address,emails,msg)        #Update!!
        print("sent")
        time.sleep(wait)
print("{} texts were sent.".format(text_amount))

根据评论进行编辑。

server = smtplib.SMTP(email_provider, email_port)
server.starttls()
server.login(email_address, password)

with open("mails.txt") as infile:
    for line in infile:
        line = line.strip()
        if "," in line:
            emails = line.split(",")
        else:
            emails = line
        for _ in range(0,text_amount):
            server.sendmail(email_address,emails,msg)
            print("sent")
            time.sleep(wait)
        print("{} texts were sent.".format(text_amount))