0

I have a program that detects faces and saves them to a folder. I want to send these images to an email id but I don't have any clue how to do it.

Here is the code to save images:

import cv2


#import the cascade for face detection
FaceClassifier =cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# access the webcam (every webcam has 
capture = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame

    ret, frame = capture.read()
    if not capture:
        print ("Error opening webcam device")
        sys.exit(1)


    # to detect faces in video
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = FaceClassifier.detectMultiScale(gray, 1.3, 5)

    # Resize Image 
    minisize = (frame.shape[1],frame.shape[0])
    miniframe = cv2.resize(frame, minisize)
    # Store detected frames in variable name faces
    faces =  FaceClassifier.detectMultiScale(miniframe)
   # Draw rectangle 
    for f in faces:
        x, y, w, h = [ v for v in f ]
        cv2.rectangle(frame, (x,y), (x+w,y+h), (255,255,255))
        #Save just the rectangle faces in SubRecFaces
        sub_face = frame[y:y+h, x:x+w]
        FaceFileName = "faces/face_" + str(y) + ".jpg"
        cv2.imwrite(FaceFileName, sub_face)
        #Display the image 
        cv2.imshow('Result',frame)
        cv2.waitKey(180)
        break

    # When everything is done, release the capture

img.release()
cv2.destroyAllWindows()

I don't know how can I send the saved images to an email id. Please Help!

Miki
  • 40,887
  • 13
  • 123
  • 202
Arpit
  • 3
  • 2
  • 9
  • Possible duplicate of [Embed picture in email](https://stackoverflow.com/questions/7755501/embed-picture-in-email) – Jake P Jul 17 '19 at 16:45
  • standard module [smtplib](https://docs.python.org/3/library/smtplib.html) (Simple Mail Transfer Protocol) or [imaplib](https://docs.python.org/3/library/imaplib.html) or more interesting external module [imapclient](https://imapclient.readthedocs.io/en/2.1.0/) – furas Jul 17 '19 at 16:46
  • @JakePerret didn't work :( – Arpit Jul 17 '19 at 17:21

2 Answers2

0

We use SendGrid for this. It's a web based service and there's a python module to interface with it.

SendGrid

SendGrid Python Module

Here's some example code to attach a PDF so basically you just change the FileType call to whatever your image is and the FileName call to your image.

import base64
import os
import json
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import (
    Mail, Attachment, FileContent, FileName,
    FileType, Disposition, ContentId)
try:
    # Python 3
    import urllib.request as urllib
except ImportError:
    # Python 2
    import urllib2 as urllib

import os
import json
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

message = Mail(
    from_email='from_email@example.com',
    to_emails='to@example.com',
    subject='Sending with Twilio SendGrid is Fun',
    html_content='<strong>and easy to do anywhere, even with Python</strong>')
file_path = 'example.pdf'
with open(file_path, 'rb') as f:
    data = f.read()
    f.close()
encoded = base64.b64encode(data).decode()
attachment = Attachment()
attachment.file_content = FileContent(encoded)
attachment.file_type = FileType('application/pdf')
attachment.file_name = FileName('test_filename.pdf')
attachment.disposition = Disposition('attachment')
attachment.content_id = ContentId('Example Content ID')
message.attachment = attachment
try:
    sendgrid_client = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
    response = sendgrid_client.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
except Exception as e:
    print(e.message)
Matthew Wachter
  • 132
  • 1
  • 7
0

@Arpit says it must be smtp. Here's an easy way to do that using smtplib:

# Import smtplib for the actual sending function
import smtplib

# And imghdr to find the types of our images
import imghdr

# Here are the email package modules we'll need
from email.message import EmailMessage

# Create the container email message.
msg = EmailMessage()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = ', '.join(family)
msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'

# Open the files in binary mode.  Use imghdr to figure out the
# MIME subtype for each specific image.
for file in pngfiles:
    with open(file, 'rb') as fp:
        img_data = fp.read()
    msg.add_attachment(img_data, maintype='image',
                                 subtype=imghdr.what(None, img_data))

# Send the email via our own SMTP server.
with smtplib.SMTP('localhost') as s:
    s.send_message(msg)

Taken from here: SMTPLIB

Matthew Wachter
  • 132
  • 1
  • 7