Aplikasi Sederhana Dengan Python save data to email
Mau paham tentang Aplikasi Sederhana Dengan Python save data to email, hanya disiniaja

You can watch this lesson on YouTube to understand better.
YOUTUBE LINK = https://www.youtube.com/watch?v=Yq8AnVp0IHc
Don't forget to help our channel to develope further so that, there is nothing that can't be done except https://disiniaja.id.
This tutorial is a continuation of the tutorial in another post
Aplikasi sederhana dengan python save data to excel
Then run command prompt to install secure-smtplib and emails library
python -m pip install secure-smtplib
python -m pip install emails
Signup to https://mailtrap.io/
then login and get your current user and password
Then paste to Notepad
copy your login generated by Mailtrap then paste to source code
copy your password generated by Mailtrap then paste to source code
OK NOW CREATE NEW THEN COPY THIS CODE OR YOU CAN DOWNLOAD FROM HERE
import mysql.connector
import PySimpleGUI as sg
import pandas as pd
import os
import json
import requests
import smtplib
# import the corresponding modules
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
mysqldb=mysql.connector.connect(host="localhost",user="root",password="",database="aplikasi")
#if mysqldb.is_connected():
#print("Berhasil terhubung ke database")
mycursor=mysqldb.cursor()
sg.theme('DarkGreen4')
EXCEL_FILE = 'Pendaftaran.xlsx'
df = pd.read_excel(EXCEL_FILE)
layout=[
[sg.Text('Masukan Data Kamu: ')],
[sg.Text('Nama',size=(15,1)), sg.InputText(key='Nama')],
[sg.Text('No Telp',size=(15,1)), sg.InputText(key='Tlp')],
[sg.Text('Alamat',size=(15,1)), sg.Multiline(key='Alamat')],
[sg.Text('Tgl Lahir',size=(15,1)), sg.InputText(key='Tgl Lahir'),
sg.CalendarButton('Kalender', target='Tgl Lahir', format=('%Y-%m-%d'))],
[sg.Text('Jenis Kelamin',size=(15,1)), sg.Combo(['pria','wanita'],key='Jekel')],
[sg.Text('Hobi',size=(15,1)), sg.Checkbox('Belajar',key='Belajar'),
sg.Checkbox('Menonton',key='Menonton'),
sg.Checkbox('Musik',key='Musik')],
[sg.Submit(), sg.Button('clear'), sg.Button('view data'), sg.Button('open excel'), sg.Exit()]
]
window=sg.Window('Form pendaftaran',layout)
def select():
results = []
mycursor.execute("select nama,tlp,alamat,tgl_lahir,jekel,hobi from pendaftaran order by id desc")
for res in mycursor:
results.append(list(res))
headings=['Nama','Tlp','Alamat','Tgl Lahir', 'Jekel', 'Hobi']
layout2=[
[sg.Table(values=results,
headings=headings,
max_col_width=35,
auto_size_columns=True,
display_row_numbers=True,
justification='right',
num_rows=20,
key='-Table-',
row_height=35)]
]
window=sg.Window("List Data", layout2)
event, values = window.read()
def send_gdrive():
headers={
"Authorization":"Bearer ya29.a0AXooCgs601toKsQpCqDCGLz6aBphWS0a3zUT4TBJPuzQE6HPlzPfDpWxPf7EDXZZNvuU8rV-OJ5v614K8dFJ9qZg0aMGwAoMzmdSfR9aOyZDHzBEbQ3kcF-e7BOIBVGvei42B60C4yl6WCg1Ns6nKM-mlzld3EwH4EUDaCgYKAUkSARASFQHGX2MifeqhlbHtiQ_eIee4cyEgTg0171"
}
name={
"name":"Pendaftaran.xlsx",
}
files={
'data':('metadata',json.dumps(name),'application/json;charset=UTF-8'),
'file':('mimeType',open("./Pendaftaran.xlsx","rb"))
}
r=requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
headers=headers,
files=files
)
print(r.text)
def send_email(nama,tlp,alamat,tgl_lahir,jekel,hobi):
port = 2525
smtp_server = "sandbox.smtp.mailtrap.io"
login = "your" # paste your login generated by Mailtrap
password = "your" # paste your password generated by Mailtrap
subject = "Pendaftaran"
sender_email = "sender@gmail.com" # paste your sender email
receiver_email = "receiver@gmail.com" # paste your receive email
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
# Add body to email
body = "Terimakasih Anda Telah Mengisi Form Pendaftaran Sbb :\n"
detail=body+'nama:'+nama+'\nNo Tlp:'+tlp+'\nAlamat:'+alamat+'\nTanggal Lahir'+tgl_lahir+'\nJenis Kelamin'+jekel+'\nHoby'+hobi
message.attach(MIMEText(detail, "plain"))
with open(EXCEL_FILE, "rb") as attachment:
# The content type "application/octet-stream" means that a MIME attachment is a binary file
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
# Encode to base64
encoders.encode_base64(part)
part.add_header(
"Content-Disposition",
f"attachment; filename= {EXCEL_FILE}",
)
# Add attachment to your message and convert it to string
message.attach(part)
text = message.as_string()
# send your email
with smtplib.SMTP("sandbox.smtp.mailtrap.io", 2525) as server:
server.starttls()
server.login(login, password)
server.sendmail(
sender_email, receiver_email, text
)
print('Sent')
def clear_input():
for key in values:
window[key]('')
#window['Nama'].update('')
window.Element('Nama').SetFocus(force = True)
return None
while True :
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Exit':
break
if event == 'clear':
clear_input()
if event == 'view data':
select()
if event == 'open excel':
os.startfile(EXCEL_FILE)
if event == 'Submit':
nama=values["Nama"]
tlp=values["Tlp"]
alamat=values["Alamat"]
tgl_lahir=values["Tgl Lahir"]
jekel=values["Jekel"]
belajar=values["Belajar"]
menonton=values["Menonton"]
musik=values["Musik"]
if belajar == True:
hobi="Belajar"
if menonton == True:
hobi="Menonton"
if musik == True:
hobi="Musik"
if nama == '':
sg.popup('MISSION FAILED')
window.Element('Nama').SetFocus(force = True)
else:
sql="insert into pendaftaran(nama,tlp,alamat,tgl_lahir,jekel,hobi) values(%s,%s,%s,%s,%s,%s)"
val=(nama,tlp,alamat,tgl_lahir,jekel,hobi)
mycursor.execute(sql,val)
mysqldb.commit()
df =df._append(values, ignore_index=True)
df.to_excel(EXCEL_FILE, index=False)
sg.popup('Data Berhasil Di Simpan')
#send_gdrive()
send_email(nama,tlp,alamat,tgl_lahir,jekel,hobi)
clear_input()
window.close()
SAVE AND RUN PROGRAM
There is no sense of pride in what we do, it's just to share experiences when our financial condition is not in a good condition.
If we try to count the blessings that Allah has bestowed on us, we will certainly not be able to count them.
May we all be given health and long life, so we can share for science.
What's Your Reaction?






