Created
August 28, 2019 08:43
-
-
Save Ch3mjor/f9f92f4184938977ba50384c6c625161 to your computer and use it in GitHub Desktop.
Automated Sending of emails Python3 with Attachments (new file each new day)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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'] = '[email protected]' | |
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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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