Python: how to validate how many files I have in a folder and send by email

Asked

Viewed 64 times

-2

Good afternoon, all right?

I’m having a doubt in my python code, I’m trying to do an automation of sending emails with specific files, these emails I send daily and are random emails with random attachments, sometimes have 15 files that go to 15 e-different mails and has times that has 20 files that go to different emails, depends on the day. My question is how to validate how many files are in the folder on that specific day and how to parameterize which email it will be sent to. Studying throughout the day I created a code that validates whether the file with the specific name exists or not, if it exists, it changes the name of the file by the email of the person who will be sent and so sends by email, so it works, however, has more 15 e-mails to do this and this email number is random sometimes are 15,16,17,18 files to send on the day. Can someone help me? Obs(each file has a default name, for example teste1, teste2 and teste3, I have a list of the emails set for whom I need to send the teste1, teste2 and teste3).

import os
import win32com.client as win32
import time
from pathlib import Path
import os.path


if(os.path.exists(r'C:\Users\Desktop\convenios\teste1.txt')):
  print("O arquivo existe")
else:
  print("O arquivo não existe")



os.rename (r'C:\Users\Desktop\convenios\teste1.txt',r'C:\Users\Desktop\convenios2\[email protected]')

#Informações do e-mail
outlook = win32.Dispatch('outlook.application')

folder = Path(r"C:\Users\Desktop\convenios2")

#leitura documentos em anexo
for attachment in folder.iterdir():
    #envio de e-mail
    mail = outlook.CreateItem(0)
    mail.SentOnBehalfOfName = '[email protected]'
    mail.HTMLBody = """
    <p>Olá,</p>
    <p>Segue documentos em anexo!</p>
    <p>Atenciosamente.</p>
    <p>João</p>"""
    mail.Attachments.Add(str(attachment))
    # coloca o nome do arquivo, sem a extnsão, como endereço do email antes do "@"
    mail.To = f'{attachment.stem}'
    #mail.Subject = str(attachment)
    mail.subject = ('arquivo teste')
    mail.display()
    time.sleep(5)
    mail.Send()
    print ("email enviado com sucesso!")

1 answer

0


Good to get the files from the folder just use the dir = os.listdir('local onde os arquivos estão') the value returned will be a list of all files after this just create a repeat loop for each file

following example:

pasta_emails = os.listdir("local da Pasta")
for email in pasta_emails:
    print(email)

if you want to do using while you will have to have parameters for breaking the loop

see example:

pasta_emails = os.listdir("local da Pasta")

quantidade_arquivos_na_pasta = len(pasta_emails) - 1
contador = 0

while contador != quantidade_arquivos_na_pasta:
   #obter nome do arquivo
   print(pasta_emails[contador])
   contador +=1

in case the first step is to grab all files that are in the folder in which you save your email.

using the built-in function len() and using as parameter the list returned with the file names you get the amount of items you have in the list. (in this case I subtracted 1 because the function len() account from 1 and the first position in the lists we call for 0)

after that already has the parameter to define when the while must be stopped

I hope I’ve helped, good studies

  • Thanks for your help, Kelvin!

  • Anything if it’s not clear just tell me around here that I’m trying to help

  • Show bro, I just have one more question, I’m studying the repetition structure while, only I’m not able to imagine how to validate the file. example: today has 15 files, how would I know that there are 15 files and 15 are for the specific email, then tomorrow I have 16 files and he needs to add 1 more email, that automatically, understand?

  • I will edit my answer to illustrate better

  • Kelvin, the amendment has worked, thank you very much!

  • Kelvin, is out there?

  • Good morning Gabriel, I believe if it is any doubt, creates a question that I already answer as soon as you open

  • show, if you can give a boost ;-;

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.