The executable file in question, ideally, should be able to retrieve mail merged documents from a specific folder and send emails with the attachments. The script runs perfectly fine but when I convert the .py to an executable, the absolute path changes. First time using pyinstaller
so I may not be familiar with it.
The error message from the executable file shows that the file I am looking for should be in c:\users\hp\AppData\Local\...which is not the case. Any help will be highly aprreciated.
Here is the python script.
from __future__ import print_function
#to create the different templates
from docxtpl import DocxTemplate
#Create df's from csv's
import pandas as pd
import os
#Identify file directories of output pdf files
import os.path
#Setup gmail,secure connection
import smtplib,ssl
#Maskpassword
import maskpass
#Progress bar
import tqdm
import tqdm
from tqdm import tqdm
#retrieves all PDF files from app directory
from collections import ChainMap
#building Email Parts
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
#Setting up gmail connections (between app and gmail)
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
def main():
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
try:
# Call the Gmail API
service = build('gmail', 'v1', credentials=creds)
results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])
except HttpError as error:
# TODO(developer) - Handle errors from gmail API.
print(f'An error occurred: {error}')
if __name__ == '__main__':
main()
#Initialization of MS Word
from win32com import client
word_app = client.Dispatch("word.application")
print("Mail Merging Initializing")
Data_frame = pd.read_csv('mailtest.csv') # whole source document
Data_frame1=pd.read_csv("mailtest.csv", usecols= ['email']) # where the emails are found
Data_frame2=pd.read_csv("mailtest.csv", usecols= ['file']) #shoo pdf files are named
#translates Data Frames 1 & 2 to List
mailtos=Data_frame1.values.tolist() # contains email addresses of recepients
pdf_files=Data_frame2.values.tolist() # contains pdf file names
# Identifying file directory and adding names as keys to dictionary
my_files =[{each_file.split(".")[0]:each_file} for each_file in os.listdir(os.path.abspath("PDF/")) if each_file.endswith(".pdf")]
print(my_files)
my_files_dict = dict(ChainMap(*my_files))
#------------STEP 1-Append-records from source(.csv) to doc template and convert to pdf to be saved in "pdf/" folder
for r_index, row in tqdm(Data_frame.iterrows(), total=Data_frame.shape[0]):
agent_name =row['Name'] # for file Name
tpl = DocxTemplate("mailmergev2.docx") #in the same directory
df_to_doct = Data_frame.to_dict() # dataframe ->dict for the template render
x = Data_frame.to_dict(orient='records')
context = x
tpl.render(context[r_index])
tpl.save('Doc\\'+agent_name+".docx")
#get project folder path**(THIS IS WHERE MY PROBLEM IS)**
root_dir=os.path.dirname(os.path.abspath(__file__))
print(root_dir)
# Convert file from Docx to PDF
doc = word_app.Documents.Open(root_dir+ '\\Doc\\' + agent_name + '.docx')
doc.SaveAs(root_dir+'\\PDF\\'+ agent_name + '.pdf', FileFormat=17)
print("Mail Merging Completed. Generating Emails...")
word_app.Quit()