def sendMail(self): """ Send the mail via the Gmail server. Note, due to an unknown reason, the yagmail library can't send zipfiles. Therefore the code has been changed to send each png file. Code adapted on 11/01/2020 """ # Zip the files # result = makezip(self._scan_base_folder, self._defaultZipFileName, self._lastIndexOfMail) result = Get_png_images(self._scan_base_folder + os.sep + str(self._lastIndexOfMail)) print(result) mg = GmailClient(receiver=self.txtTo.text(), body=self.txtBody.toPlainText(), subject=self.txtSubject.text(), files=result, gmail_key=self._gmailappkey) try: mg.sendGMail() session = Session() x = session.query(MailBox).get(self._lastIndexOfMail) # Set sent date and time x.date_sent = datetime.datetime.now() session.commit() logging.info( f"Mail sent and updated record {self._lastIndexOfMail}") except MailSendError as err: MsgBox.show("Probleem!", QMessageBox.Critical, "Fout", "Email niet verzonden!", QMessageBox.Ok) logging.error(f"Unable to send mail {err.msg} {err.destination}")
def query_session_scope(self): """Provide a transactional scope around a series of operations.""" session = Session() session.expire_on_commit = False try: yield session except Exception as err: raise finally: session.close()
def command_session_scope(self): """Provide a transactional scope around a series of operations.""" session = Session() try: yield session session.commit() except Exception as err: session.rollback() raise finally: session.close()
def _loadSentItemsTable(self, status): """ Fill sent items table :param status: sent or unset :return: """ # Number of columns session = Session() self.table_SentItems.setColumnCount(COLUMN_COUNT) self.table_SentItems.clear() """ The next part was tricky, when creating a join, the results are returns with indexes for each table. Hence in this case MailBox in table 0, and Projects is index 1. The SqlAlchemy code is equivalent to this SQL SELECT mailbox.id AS mailbox_id, mailbox.date_created AS mailbox_date_created, mailbox.date_sent AS mailbox_date_sent, mailbox.mail_to AS mailbox_mail_to, mailbox.subject AS mailbox_subject, mailbox.mail_body AS mailbox_mail_body, projects.id AS projects_id, projects.parent_mail_id AS projects_parent_mail_id, projects.scan_path AS projects_scan_path FROM mailbox JOIN projects ON mailbox.id = projects.parent_mail_id ORDER BY mailbox_id desc """ mails = session.query(MailBox, Projects).join( Projects, MailBox.id == Projects.parent_mail_id).order_by(desc(MailBox.id)) # Set the headers self.table_SentItems.setHorizontalHeaderLabels( ("ID", "Datum aanmaak", "Datum Verzonden", "Naar", "Onderwerp", "Project id", "Project naam")) # Create rows, use double ( for tuple rows = [] for mail in mails: # Notice the indexes of the table rows.append( (str(mail[MAILBOX].id), str(mail[MAILBOX].date_created), str(mail[MAILBOX].date_sent), mail[MAILBOX].mail_to, mail[MAILBOX].subject, str(mail[PROJECTS].id), mail[PROJECTS].scan_path)) self.table_SentItems.setRowCount(len(rows)) for row, cols in enumerate(rows): for col, text in enumerate(cols): table_item = QTableWidgetItem(text) # Optional, but very useful. table_item.setData(Qt.UserRole + 1, "user") self.table_SentItems.setItem(row, col, table_item) # Make the table look good self.table_SentItems.resizeColumnsToContents() # Don't need to see id field self.table_SentItems.hideColumn(5)
def activate_mail_instance(self, messageid): """ Get the contents of the selected mail :param messageid: id of selected message :return: Nothing """ self._lastIndexOfMail = messageid session = Session() mails = session.query(MailBox).filter(MailBox.id == messageid).first() proj = session.query(Projects).filter( Projects.parent_mail_id == messageid).first() # fill the textfields with the contents of the mail, # also activate the 'scan' and 'send' buttons in this case self.txtTo.setText(mails.mail_to) self.txtSubject.setText(mails.subject) self.txtProjectName.setText(proj.scan_path) self.txtBody.setPlainText(mails.mail_body) if not mails.date_sent: # user can still modify this email self.lblWarningNewMail.setVisible(True) # buttons self.msgFrameBox.setStyleSheet("background-color: rgb(148, 0, 0);") self.msgFrameBox.setVisible(False) self.btnSendEmail.setEnabled(True) self.btnSaveEmail.setEnabled(True) self.btnScanDoc.setEnabled(True) # input boxes self.txtTo.setEnabled(True) self.txtSubject.setEnabled(True) self.txtBody.setEnabled(True) self.txtProjectName.setEnabled(True) else: # mail was already sent, changes not allowed anymore self.msgFrameBox.setVisible(True) self.btnSendEmail.setEnabled(False) self.btnSaveEmail.setEnabled(False) self.btnScanDoc.setEnabled(False) self.txtTo.setEnabled(False) self.txtSubject.setEnabled(False) self.txtBody.setEnabled(False) self.txtProjectName.setEnabled(False)
import database.orm as m with open('room caius list 2014-15.csv') as f: d = csv.DictReader(f) data = list(d) rent_keys = { 2011: 'Rent/Term 2011', 2012: 'Rent 2012', 2013: 'Rent 2013', 2014: 'Rent 2014' } print data[0] s = Session() bt_ugrad = (s .query(m.BallotType) .filter(m.BallotType.name == 'Undergraduate') ).one() def get_room_by_name(name): """ Convert whatever name the spreadsheet uses into a room object """ name = name.replace('Ct', 'Court') name = name.replace('Rd', 'Road') name = name.replace('Green St', 'Green Street') name = name.replace('Marys', 'Mary\'s') name = name.replace('Michaels', 'Michael\'s') name = name.replace('Cres', 'Crescent')
def save_email(self): """ Adds or update a new record to the scampy mailbox. """ mail_action = "CREATE" if self._lastIndexOfMail: """ We already have a record """ mail_action = "UPDATE" path = self._scan_base_folder + os.sep + str(self._lastIndexOfMail) self._full_doc_path = path if len(self.checkInputFields()) == 0: session = Session() date_created = datetime.datetime.now() date_sent = None mailbox_item = MailBox(date_created, date_sent, self.txtTo.text(), self.txtSubject.text(), self.txtBody.toPlainText()) # Add new record if mail_action == "CREATE": session.add(mailbox_item) print("Message created") session.commit() self._lastIndexOfMail = mailbox_item.id project_item = Projects(mailbox_item.id, self.txtProjectName.text()) session.add(project_item) session.commit() # Remember last project item id self._lastIndexOfProject = project_item.id logging.info(f"Created record {mailbox_item.id}") # Now create the target folder for the scans related to this email # Note, the folders will reside under the selected target folder in the settings. path = self._scan_base_folder + \ os.sep + str(self._lastIndexOfMail) self.lblScanTarget.setText(path) logging.warning(f"Creating folder {path}") try: os.mkdir(path) except Exception as ex: logging.error(f"Could not create path {path} {ex}") else: print("Message updated") # Get the item with the last mail id and update this record x = session.query(MailBox).get(self._lastIndexOfMail) # Now we can update the information x.subject = self.txtSubject.text() x.mail_to = self.txtTo.text() x.mail_body = self.txtBody.toPlainText() session.commit() logging.info(f"Updated record {self._lastIndexOfMail}") self.showMailOverview() session.close() # Now enable the scanning controls self.toggleScanControls(True) else: errfields = "" for field in self.checkInputFields(): errfields += field + "\n" MsgBox.show("Probleem!", QMessageBox.Critical, "De volgende velden zijn niet ingevuld!", errfields, QMessageBox.Ok) logging.error(f"Problem with input") self.txtProjectName.setFocus() return False