Skip to content

Instantly share code, notes, and snippets.

@Ch3mjor
Created August 28, 2019 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ch3mjor/f9f92f4184938977ba50384c6c625161 to your computer and use it in GitHub Desktop.
Save Ch3mjor/f9f92f4184938977ba50384c6c625161 to your computer and use it in GitHub Desktop.
Automated Sending of emails Python3 with Attachments (new file each new day)
#Code by Collins Chemjor
import os
import smtplib
from email.message import EmailMessage
from datetime import date
#Setting email address and password to be used
EMAIL_ADDRESS = os.environ.get('EMAIL_USER')
EMAIL_PASSWORD = os.environ.get("EMAIL_PASS")
#Obtain date and convert to string
today = date.today()
subject_date = today.strftime("%d %B, %Y")
mail_subject = f'Wallet Balances {subject_date} Report'
#Setting the email message, body, head, To etc
msg = EmailMessage()
msg['Subject'] = mail_subject
msg['From'] = EMAIL_ADDRESS
msg['To'] = 'example@gmail.com'
msg.set_content('Quotes attached...')
#Setting ,convert to correct format and set filename and extension
mail_today = str(today)
mail_today = mail_today.replace('-','')
original_file = 'File_'
file_ext = '.csv'
full_name = original_file + mail_today + file_ext
#Attaching the file to sent on the email
with open(full_name, 'rb') as f:
file_data = f.read()
file_name = f.name
msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)
#Sending the email to the client
with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
smtp.ehlo()
smtp.starttls() # Encrpytion method start
smtp.ehlo()
smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
smtp.send_message(msg)
@Ch3mjor
Copy link
Author

Ch3mjor commented Aug 28, 2019

To allow this script to access your Gmail account you need to enable unsecure apps login on your account at this link:

https://myaccount.google.com/lesssecureapps

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment