0

I am building this script to detect my face through a webcam and have the model detect if Im wearing a face mask or not. If the detected face is not wearing a mask, an email is sent to an admin to alert them. Everything works correctly except for the email part. It keeps giving an SMTPAuthenticationError saying my username and password are incorrect yet they are correct. What could I be doing wrong and how do I fix this? I have authorised Google through settings to authorize less secure apps. I have also disabled 2step verification but I'm still getting this error.

This is part of the code generating the error.

if (label == "No Mask"):
            # Throw a Warning Message to tell user to wear a mask if not wearing one. This will stay
            #open and No Access will be given He/She wears the mask
            messagebox.showwarning("Warning","Access Denied. Please wear a Face Mask")
            
            # Send an email alert to the administrator if access denied/user not wearing face mask 
            message = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT)
            mail = smtplib.SMTP('smtp.gmail.com', 587)
            mail.ehlo()
            mail.starttls()
            mail.login('kwerondaa@gmail.com','#####')
            mail.sendmail('kwerondaa@gmail.com','kwerondaa@gmail.com',message)
            mail.close
            
        else:
            pass

This is the error: SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials v25sm14100155wmh.4 - gsmtp')

This is the entire script file:

from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.models import load_model
from imutils.video import VideoStream
import numpy as np
import imutils
import time
import cv2
import os

import tkinter
from tkinter import messagebox
import smtplib

# Initialize Tkinter
root = tkinter.Tk()
root.withdraw()

SUBJECT = "Subject"   
TEXT = "One Visitor violated Face Mask Policy. See in the camera to recognize user. A Person has been detected without a face mask in the Hotel Lobby Area 9. Please Alert the authorities."



def find_face_and_mask(frame, detectFace, detectMask):
#get face dimensions and construct blob
    (h, w) = frame.shape[:2]
    blob = cv2.dnn.blobFromImage(frame, 1.0, (224, 224),
        (104.0, 177.0, 123.0))

    #obtaining the face
    detectFace.setInput(blob)
    detections = detectFace.forward()
    print(detections.shape)


    faces = [] # faces
    locs = [] #locations
    preds = [] #predictions

    for i in range(0, detections.shape[2]):
        
        confidence = detections[0, 0, i, 2]

        if confidence > 0.5: #setting min confidence
            box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
            (startX, startY, endX, endY) = box.astype("int")

            (startX, startY) = (max(0, startX), max(0, startY))
            (endX, endY) = (min(w - 1, endX), min(h - 1, endY))

            # extracting the face ROI and preprocessing
            face = frame[startY:endY, startX:endX]
            face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
            face = cv2.resize(face, (224, 224))
            face = img_to_array(face)
            face = preprocess_input(face)

            #append faces and locations
            faces.append(face) 
            locs.append((startX, startY, endX, endY))

    # only make a predictions if at least one face was detected
    if len(faces) > 0:
        # making batch predictions on *all* faces at the same time rather than one-by-one predictions
        faces = np.array(faces, dtype="float32")
        preds = detectMask.predict(faces, batch_size=100)

    return (locs, preds) #2-tuple of the face locations and their corresponding locations

# the serialized face detector model from disk
prototxtPath = r"face_detector\deploy.prototxt"
weightsPath = r"face_detector\res10_300x300_ssd_iter_140000.caffemodel"
detectFace = cv2.dnn.readNet(prototxtPath, weightsPath)

# face mask detector model from disk
detectMask = load_model("mask_det_final_model.h5")


vid_stream = VideoStream(src=0).start()

# loop over the frames from the video stream
while True:

    frame = vid_stream.read()
    frame = imutils.resize(frame, width=600)

    # detect faces in the frame and determine if the detected face is wearing a face mask or not
    (locs, preds) = find_face_and_mask(frame, detectFace, detectMask)

    for (box, pred) in zip(locs, preds):
        # unpack the bounding box and predictions
        (startX, startY, endX, endY) = box
        (mask, withoutMask) = pred


        label = "Mask" if mask > withoutMask else "No Mask" #labels of the box
        color = (0, 255, 0) if label == "Mask" else (0, 0, 255)
    
        
        
        
        if (label == "No Mask"):
            # Throw a Warning Message to tell user to wear a mask if not wearing one. This will stay
            #open and No Access will be given He/She wears the mask
            messagebox.showwarning("Warning","Access Denied. Please wear a Face Mask")
            
            # Send an email alert to the administrator if access denied/user not wearing face mask 
            message = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT)
            mail = smtplib.SMTP('smtp.gmail.com', 587)
            mail.ehlo()
            mail.starttls()
            mail.login('kwerondaa@gmail.com','######')
            mail.sendmail('kwerondaa@gmail.com','kwerondaa@gmail.com',message)
            mail.close
            
        else:
            pass
       
     

        # include the probability in the label
        label = "{}: {:.2f}%".format(label, max(mask, withoutMask) * 100)

        # display the label and bounding box rectangle on the output frame
        cv2.putText(frame, label, (startX, startY - 10),
            cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)
        cv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)

    cv2.imshow("Face mask detector Live webcam", frame)
    key = cv2.waitKey(1) & 0xFF

    if key == ord("q"):
        break

cv2.destroyAllWindows()
vid_stream.stop()
  • If an app or site doesn’t meet our security standards, Google might block anyone who’s trying to sign in to your account from it, https://stackoverflow.com/questions/16512592/login-credentials-not-working-with-gmail-smtp – Shijith Jan 30 '21 at 11:24
  • https://stackoverflow.com/questions/10147455/how-to-send-an-email-with-gmail-as-provider-using-python/27515833#27515833 – Shijith Jan 30 '21 at 11:30
  • So what do I do now? – Ambroze kweronda Jan 30 '21 at 11:40
  • you can turn on the `allow less secure apps` option at https://www.google.com/settings/security/lesssecureapps after logging into your account `kwerondaa@gmail.com` , it should work. (by default this is disabled, so please do at your own risk) – Shijith Jan 30 '21 at 11:46

1 Answers1

0

Provided your username and password is correct, these are the steps to get Gmail working from any client.

# Visit https://accounts.google.com
#
# 1. Click on [Security] menu
# 2. Scroll to section [Less secure app access] and set it to ON
# 3. Scroll to section [Signing in to Google] and set [Use your phone to sign in] to OFF 
# 4. Scroll to section [Signing in to Google] and set [2-step Verification] to OFF

Now a simple text/plain email example to send:

To: "Jane Doe" <jane@gmail.com>
From: "John Doe" <john@gmail.com>
Subject: A text/plain email
MIME-Version: 1.0 (Created with SublimeText 3)
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit

Good morning.

This is a message in text/plain format.
It contains text/plain.
It contains no base64 inline images or attachments.
Each line is no more than 76 characters in length.

Please reach out if you have any questions.


Thank you,

John Doe
SENIOR DEVELOPER
XYZ Solutions Inc.
P | 999.555.1234

Then, you can use CURL to send it:

# GMAIL TEST - text-plain.eml
curl --verbose -ssl smtps://smtp.gmail.com:465 --login-options AUTH=PLAIN --user john@gmail.com:passwword123 --mail-from john@gmail.com --mail-rcpt jane@gmail.com --mail-rcpt-allowfails --upload-file text-plain.eml 
suchislife
  • 4,251
  • 10
  • 47
  • 78