Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
All you need to do today is call Python’s camera to take a picture and send it to the mailbox.
Here’s the idea:
1. Call the camera through OpencV to take photos and save the image locally
2, use the email library to construct the email content, save the picture to insert the email content in the form of attachment
3. Use smtPLib library to send mail to the specified mailbox
4. Generate the.exe file
Importing tool Packages
Import cv2 from email.mime.image imort MIMEImage # From email.mime.text import MIMEText from Email.mime. Multipart import MIMEMultipart import smtplib #Copy the code
PIP install opencv-python-i to install cv2. PIP install opencv-python-i
def GetPicture(): Camera cv2.namedWindow('camera',1) #'1' indicates that the window cannot be dragged arbitrarily # Call camera cap = cv2.videocapture (0) ret,frame = Cv2.imwrite (path+images+".jpg",frame) # Save to disk # Release camera Cap.release () # Close window cv2.destroyWindow("camera")Copy the code
The above code is to use Cv2 to save the photo to the local path.
def SetMsg(): Set the message format: return: MSG = MIMEMultipart('mixed') # MSG ['Subject'] = 'test' MSG ['From'] = sender MSG ['To'] = receiver # Text_plain = MIMEText(text,'plain',' UTF-8 ') # attach(text_plain) # SendImageFile = open(path+images+'.jpg','rb').read() image = MIMEImage(SendImageFile) image['Content-Disposition'] = 'attachment; filename="people.jpg"' msg.attach(image) return msg.as_string() def SendEmail(msg): MSG: message content :return "" try: SMTP = smtplib.smtp_ssl (host,port) # create a mail service # smtp.connect(host) smtp.login(sender, PWD) Smtp.sendmail (sender,receiver, MSG) time.sleep(3) smtp.quit() #Copy the code
Above is a complete demonstration of the ability to format and send messages.
You are welcome to discuss procedural questions with me and answer any questions you may have. Follow the public number: poetic code, make a friend.