Python sending multiple email with different attachments

Asked

Viewed 661 times

-1

I’m creating a bot in python, for sending emails to some people with different attachments, the code is like this:

    import win32com.client as win32
    import time
    import os
    
    #Informações do e-mail
    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.SentOnBehalfOfName = '[email protected]'
    
   #Percorre o diretório de anexos
for attachment in  os.listdir(r"pasta_anexos"):
      #Agrengando os arquivos da pasta a uma string
      file = (os.path.join(r"pasta_anexos",str(attachment)))       
      if str(file).endswith('test1.txt'):
          #Anexando test1.txt
          mail.Attachments.Add(file)        
          #Percorrendo novamente o diretorio, para nexar o segundo arquivo
          for attachment2 in os.listdir(r"pasta_anexo"):
              #Agrengando os arquivos da pasta a uma string
              file2 = (os.path.join(r"pasta_anexo",str(attachment2))) 
              if str(attachment2).endswith("test2.txt"):
                  #Anexando test2.txt
                  mail.Attachments.Add(file2)
          #informações finais do e-mail, para quem e assunto
          mail.To = '[email protected]'
          mail.Subject = "Empresa X " + attachment
          mail.display()
          time.sleep(5)
          mail.Send()
          break
              
print('------------------ Primeiro e-mail ------------------')

I am currently sending an email with two attachments, but I would need to send one more with two different attachments, in the first email will two files Test1.txt and test2.text, in the second would test3.txt and test4.text, but when I try to put another For the error Spyder that did not find the second test3.txt

1 answer

2


you create the "email" object on the line mail = outlook.CreateItem(0) - just place this line and the following within the for - to create and send an email to each file.

You didn’t say you need to send the files to different emails, but you didn’t say how you’re gonna know about these emails. If they are based on the file name, you can make a dictionary, for example by mapping each file extension to a -address or if they are addresses in sequence, you could use the call zip in the for to have a different email address, along with a different file on each call from for - but this will basically join random pairs of files and emails, it’s hardly what you’d like in real life.

Anyway, to send 4 different emails, with each one a file, and changing the access to files to use the pathlib - Python’s new way of accessing folders and files looks like this:

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

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

folder = Path(r"pasta_de_anexos")

#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>"
    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}@gmail.com.br'
    mail.Subject = str(attachment)
    mail.display()
    time.sleep(5)
    mail.Send()    

Using pathlib. Path nãp is more necessary to keep calling os.path.join - on the other hand, to treat the path of the aquivo as a string, you need to make the call str(...) as I did above.

Also, the way you were trying to test the file name on the line "if" was essentially random - you’ve been throwing things without understanding what I was doing and hoping it would work: in programming nothing works thus.

Python became famous for being easy to learn more than 15 years ago behind because of a feature that today people don’t realize it exists, maybe because the courses and documentation do not stress: there is the interactive mode where you can test things.

Use Python in the terminal, in the app idle, or embedded in the IDE that you’re using, if you’re using one to test direct things - seeing the result, before try to get into the program.

If you enter Python and call the method .startswith of a string can understand how it works, and not will keep trying to put "=="

In [33]: "teste23".startswith("teste")                                                   
Out[33]: True

In [34]: "tosto23".startswith("teste")                                                   
Out[34]: False

Doing this will also make you more familiar with for, if and others basic commands and calls - when placing in the program, you’ll be tempted, right and wrong ways, 10, 20 times in interactive mode and will know how it works. It is much quieter than have no idea what it’s like to be in the code, and then run and see a error message and keep trying to guess what error that is to say.

  • About the emails, just to quote, Test1 should be sent to [email protected], test2 to [email protected], I was thinking about putting each email inside if

  • No = a[i just extract the recipient’s email name from the file name itself. If the file name was a string, as in your code, just do .split('.')[0] - with pathlib just use the attribute "Stem" (the file name without the extension) - I will update above

Browser other questions tagged

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