繁体   English   中英

在Python中自动向延迟的人发送带有附件的电子邮件

[英]Sending E-Mail with attachment automatically to person with delay in Python

我对编码很陌生,我知道的不多,我想制作一个脚本,将 1 封电子邮件发送给一个人,其中包含从我的目录中获取的 1 个附件。 假设我有 100 个文件,我想每封电子邮件发送 1 个文件,然后在发送电子邮件后,我发送的文件将被删除,以便脚本不会两次发送相同的附件,最后将整个代码放在随机位置延迟 10 到 20 秒只是为了重复整个过程。 问题是脚本进入睡眠状态然后正在执行,并且向一个人发送大量电子邮件而没有附件,文件也没有被删除。 请帮忙。

import smtplib, time, random, glob, os

while True:
time.sleep(random.randint(10,20))
#checking files
os.chdir("path")

for file in glob.glob('*.txt'):
#sending
    gmail_user = 'my@gmail.com'
    gmail_password = 'password'

    sent_from = gmail_user
    to = "someones@gmail.com"
    subject = 'X'
    body = 'Y'

    email_text = """\
    From: %s
    To: %s
    Subject: %s

    %s
    """ % (sent_from, ", ".join(to), subject, body)

    try:
        server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        server.ehlo()
        server.login(gmail_user, gmail_password)
        server.sendmail(sent_from, to, email_text)
        server.close()

        print ("Sent")
    except:
        print ("Error")


else:
    print('No files with extensions .txt')
#removing
os.remove(os.path.join("path", file))

你的 while 循环是不必要的。 你可以删除它。 然后,将time.sleep(random.randint(10,20))到实际发送电子邮件的 for 循环。 此外,您的变量(如 gmail_user、gmail_password)不会更改,因此您可以在 for 循环之外声明它们。

所以更正后的代码如下所示:

# first declare constants
gmail_user = "whatever"

for file in glob.glob('*.txt'):
    time.sleep(random.randint(10,20))
    try:
        # sending the mail

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM