Programming, Python, Tutorials

Download file from URL and send email using python

Recently one of my friend ask me to write a script which can download a file from from urls saved in a excel file and the downloaded files to a bunch of email address saved in a separate excel file.

So I decided to write a script in python and here’s how I did it.

Flow of the program

Read URL from excel file

To read excel file in python we will use the openpyxl library. Alternatively you can use other libraries like pandas, openpyxl, xlsxwrite, xlwt, xlutils, but some doesnot support the xlsx file format so I used openpyxl. Leave a comment if you tries using other libraries to read your xlsx file.

To install xlrd library run command in cmd

pip install openpyxl

Now we need to read oepn the file and read the cell of which contain the url from where the files will be downloaded.

Read cells in an excel .xlsx file using openpyxl

Now that we have read the excel file and get the list of urls we ready to download the file from the url .

Downlaod file from url

To download file from the url we will be sending a get request to the url and in response receive the file which can be saved or can be used within without saving.

Code to download file using a url

Note: Response from the request url is in binary format which can only be written by opening the file in “wb” mode.

You might need to debug depending on the format of response you get.

Reading recepients email address from Email

This is similar to reading url from excel file read as explained above.

Now, we have the downloaded file, and recipient email address, lets create an email.

Creating an email using python

To send emails python already provide a built-in email, smtplib and ssl library.

To create a email we will need the following things

  • sender address
  • receivers address
  • subject
  • body

To enable your gmail to send email using smtp you need to enable 2-factor authentication and a different “app password”

Follow this guide to generate app password use any device name .

Code to send email with image attachment

Explaining all each line of code will make this blog post too long you can check out Realpython’s send simple email blog post to know more about the above code.

Stitching all pieces together

Finally we have all the pre-requisite, now its time to put them all in one script and start bombarding emails to the recepients.

Sending downloaded images to recipients email address

The above script reads the recipient one by one and send all the downloaded file to each recipient in separate email.

You can download the file from Download Now

Feel free to comment if you want to add extra feature or need help in debugging your version of the code.


Thank you for reading, Happy Learning, drop your suggestion in the comments.

Feel free to follow us on Youtube , Linked In , Instagram

0 0 vote
Article Rating