COMPUTER SCIENCE CAFÉ
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
Picture
SENDING EMAILS WITH PYTHON
This section covers using Python to read, use or manipulate data from various sources. Send out automatic and customised emails with Python. We use a gmail account for this task because it has proven to us to be less problematic.
HOW TO PREPARE YOUR GMAIL
for this project we will use a gmail mail account. A change in the security setting of gmail will meed to be made to allow Python to access your gmail. It is very easy to make the change, you simple turn on allow 3rd party apps setting and it is easy to turn off again when your are not using Python to access your email.
Picture
To turn on the feature on your gmail account to allow Python to access follow these steps:
1: Go to https://myaccount.google.com/
2: Click on the security setting on the left
3: Find the option for 'Less secure App access'
4: Click 'Turn on access'
5: Click the switch to allow access.
Note: It is easy to turn this back off at any time and we recommend you leave it off when you are not testing/using your program.
FIRST EMAIL TEST
This first method shows how to send a basic email containing plain text and no subject comment. It is just 5 lines of code and useful to test everything is working, after using this method we suggest moving to the next stage to make your code better and your emails more comprehensive. Try the code below, remember to replace the details 'MYEMAILADDRESS' , 'MYPASSWORD' and ' RECEIVEREMAIL' with your details.
import smtplib

server = smtplib.SMTP_SSL("smtp.gmail.com", 465) #Connects to the server
server.login("[email protected]", "MYPASSOWRD") #Passes in your email address and password to login
server.sendmail("[email protected]","[email protected]","Hello world") #Details of -FROM, TO. MESSAGE

server.quit()#Disconnects from the server after send
EMAIL WITH PYTHON
Hopefully the method above worked and you were able to send your first email, the method has its limitations so this section take you through a more comprehensive method with better code and more control over your email. This method shows how to use passwords stored locally so you do not need to show them in your python program. To learn more on this watch the video.
import os
import smtplib
from email.message import EmailMessage

userName = os.environ.get('myUserName')#Gets the email address saved in the local profile bash file
password = os.environ.get('myPassword')#Gets the password saved in the local profile bash file

subject = ("Welcome to CS Cafe")

name = input("Welcome, please enter your name: ")
mail = input("Please enter your email address: ")
subscription = int(input("Would you like 1:LITE or 2:PRO subscription enter 1 or 2: "))
if subscription == (1):
   option = ("Lite")
elif subscription == (2):
   option == ("Pro")
   
body = ("Hi {}\n\nGlad to have you are onboard as a {} subscriber of CS Cafe.".format(name, option))

message = EmailMessage()
message['Subject'] = (subject)
message['From'] = (userName)
message['To'] = (mail)
message.set_content(body)


#Conenct to the server 465 for ssl - 587 for tls
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp:
   smtp.login(userName,password)
   smtp.send_message(message)
   smtp.quit()
TKINTER GUI AND PERSONALISED EMAILS
This section looks a combining some of the skills you will already have to create emails based on user options. Using a basic form set up using Tkinter then taking the user input to create the email tailored to their options. Watch the video to learn how this works.

Feel free to copy and use the code from below. Make changes to make it your own, and use the principles in your own GUI.
from tkinter import * #this format means you dont have to type tkinter.tk() everytime you call it
from PIL import ImageTk, Image#ImageTk to use pillow with Tk, Image to user the resize method
import os
import smtplib
from email.message import EmailMessage

#Create lists to store new users details - really they should be stored in a database
firstNameList = []
lastNameList = []
emailAddList = []
userIDList = []

#Set the screen attributes
screen = Tk()
screen.minsize(605,615)# H / V
screen.maxsize(605,615)# H / V
screen.title("E-SPORTS")
screen.configure(background="Black")

#Setup the zones of the GUI
zone1 = Canvas(screen,  width = 600, height = 100, bg = "#71d0c8")
zone1.place(x = 0, y = 0)

zone2 = Canvas(screen,  width = 600, height = 400, bg = "#626060")
zone2.place(x = 0, y = 105)

zone3 = Canvas(screen,  width = 600, height = 100, bg = "#71d0c8")
zone3.place(x = 0, y = 510)

#Place and resize the logo image - REMEMBER the image need to be saved int he same location as your python file
#First you need to create a new image that is smaller
photo = Image.open("cscafebadge.png")#Replace image details with your own image
newPhoto = photo.resize((90,90), Image.ANTIALIAS) #Create a new image - Antialias minimises distortion at low res
photo = ImageTk.PhotoImage(newPhoto)#Assign the resized image to a variable

pic = Label(zone1, image=photo, bg = "#71d0c8")
pic.place(x=5,y=5)

#Function runs when submit button pressed and will get the details from the form
def submit():
    firstName = Entry1.get()
    lastName = Entry2.get()
    emailAdd = Entry3.get()
    firstNameList.append(firstName)
    lastNameList.append(lastName)
    emailAddList.append(emailAdd)
    userID = ((len(emailAddList)) + 1)
    userIDList.append(userID)
    clearScreen()#Run the clearScreen function to clear the screen

def clearScreen():
   for i in zone2.winfo_children():
      i.destroy()
   thankYouScreen()#run the function to say thank you and the submit was received

def thankYouScreen():
    thankYou = Label(zone2, text = "Thank you for your entry", bg = "#71d0c8")
    thankYou.place(x = 200, y = 100)
    checkEmail = Label(zone2, text = "Check Your email", bg = "#71d0c8")
    checkEmail.place(x = 220, y = 140)
    email()#Run the function to send the email

def email():
    subject = ("Welcome to the E-Sports Competition")
    body = ('''Hi {}\n\nGlad to have you onboard, your entry number is ES{}\n
We look forward to seeing you at the games.\n
Many thanks and good luck\n
Computer Science Cafe E-Sports Team'''.format(firstNameList[-1], userIDList[-1]))

    #Set up the message details
    message = EmailMessage()
    message['Subject'] = (subject)
    message['From'] = ("[email protected]")#Put your email address here
    message['To'] = (emailAddList[-1])
    message.set_content(body)

    #Conenct to the server 465 for ssl - 587 for tls
    with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp:
       smtp.login('[email protected]','YOURPASSWORD')#Put your email and password here
       smtp.send_message(message)
       smtp.quit()

#Title at the top of the window    
title = Label(zone1, text = "E-SPORTS COMPETITION ENTRY FORM", bg = "#626060")
title.place(x = 180, y = 40)

#Place the submit button    
submitButton = Button(zone2,text="SUBMIT", command = submit)#Calls the function submit
submitButton.place(x = 260, y = 300)
submitButton.bind("")#Binds an action the the buttons   

#Creates a user entry box and label for First Name
firstName = Label(zone2, text = "First Name", bg = "#71d0c8")
firstName.place(x = 100, y = 100)
Entry1 = Entry(zone2)
Entry1.place(x = 200, y = 100)

#Creates a user entry box and label for Last Name
lastName = Label(zone2, text = "Last Name", bg = "#71d0c8")
lastName.place(x = 100, y = 140)
Entry2 = Entry(zone2)
Entry2.place(x = 200, y = 140)

#Creates a user entry box and label for email address
emailAdd = Label(zone2, text = "Email Address", bg = "#71d0c8")
emailAdd.place(x = 100, y = 182)
Entry3 = Entry(zone2)
Entry3.place(x = 200, y = 180)

screen.mainloop()#keeps the window open 
Picture
SUGGESTIONS
We would love to hear from you
SUBSCRIBE 
To enjoy more benefits
We hope you find this site useful. If you notice any errors or would like to contribute material then please contact us.