joeboy69
Posts: 7
Joined: Fri May 17, 2019 6:58 pm

How to separate the body of the email in Gmail (like 1 email 1 body)?

Fri Aug 16, 2019 11:43 am

I have been doing a detection system using RPi Zero W. I have done it fully but there are still some minor issues. Could someone help me with the codes (if needed)? I will provide the codes and screenshots here below. Thanks in adv :)
Situation: If the RPi system send mail to Gmail, it seems the body of the email keep on bulking up on the upcoming emails and it makes the email to be so messy with the same sentences again and again. I'm not sure, what to add up with the Python codes.

Code:

Code: Select all

mail['From'] = fromaddr
mail['To'] = toaddr
mail['Subject'] = "[Intruder Alert] Motion Detected!"
body = "Who is the Intruder? Find the attachment for the Intruder's picture!"

Code:

Code: Select all

def sendMail(data):
    mail.attach(MIMEText(body, 'plain'))
    print (data)

    # open the file to be sent
    dat = '%s.jpg' %data
    print (dat)
    attachment = open(dat, 'rb')

    # instance of MIMEBase and named as p
    p = MIMEBase('application', 'octet-stream')

    # To change the payload into encoded form
    p.set_payload(attachment.read())
    attachment.close()

    # encode into base64
    encoders.encode_base64(p)

    p.add_header('Content-Disposition', "attachment; filename= %s" %dat)

    # attach the instance 'p' to instance 'mail'
    mail.attach(p)

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(fromaddr, "-password-")
    text = mail.as_string()
    server.sendmail(fromaddr, toaddr, text)
    server.quit()

Gmail screenshot (the congested body):
Image

pcmanbob
Posts: 7268
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: How to separate the body of the email in Gmail (like 1 email 1 body)?

Fri Aug 16, 2019 12:20 pm

As you have not shown us your compete code its hard to say what the problem might be.

So here is an example of a working python program that sends an email each time on of my pi's boots

Code: Select all

import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import subprocess



def send_email(subject,body,email_send):
    email_user = "[email protected]"
    email_password = "xxxxxxxxxx"
    



    msg = MIMEMultipart()
    msg["From"] = email_user
    msg["To"] = email_send
    msg["Subject"] = subject

    
    msg.attach(MIMEText(body,"plain"))

    text = msg.as_string()
    server = smtplib.SMTP("smtp.gmail.com",587)
    server.starttls()
    server.login(email_user,email_password)


    server.sendmail(email_user,email_send,text)
    server.quit()

subject = "Garage Pi IP"    

p = subprocess.Popen("hostname -I", stdout=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
status = p.wait()


data = str(output)
result = data.split("'")
data = result[1]
result = data.split(" ")

    
body = "Garage temperature Pi Just Booted \n" + time.strftime("%a %b %d %Y %H:%M:%S") + " \n IP : " + result[0] 
 

email_send = "send [email protected]"
send_email(subject,body,email_send)

all email address/passwords removed.

also look at this which has some code to send image as attachment . https://stackoverflow.com/questions/130 ... ing-python
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

joeboy69
Posts: 7
Joined: Fri May 17, 2019 6:58 pm

Re: How to separate the body of the email in Gmail (like 1 email 1 body)?

Fri Aug 16, 2019 2:11 pm

@pcmanbob bro, here i provide my whole codings. please have a check.

Code: Select all

import RPi.GPIO as gpio
import picamera
import time
import telepot
from subprocess import call

import glob
import os

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from email.mime.image import MIMEImage
 
fromaddr = "email1gmail.com"    # change the email address accordingly
toaddr = "[email protected]"
 
mail = MIMEMultipart()
 
mail['From'] = fromaddr
mail['To'] = toaddr
mail['Subject'] = "[Intruder Alert] Motion Detected!"
body = "Who is the Intruder? Find the attachment for the Intruder's picture!"

pir=4
#HIGH=1
#LOW=0
gpio.setwarnings(False)
gpio.setmode(gpio.BCM)            
gpio.setup(pir, gpio.IN, gpio.PUD_DOWN)            # initialize GPIO Pin as input
data=""

previous_state = False
current_state = False

chat_id = -1
token = "token"

bot = telepot.Bot('api-token')
print (bot.getMe())

def sendMail(data):
    mail.attach(MIMEText(body, 'plain'))
    print (data)

    # open the file to be sent
    dat = '%s.jpg' %data
    print (dat)
    attachment = open(dat, 'rb')

    # instance of MIMEBase and named as p
    p = MIMEBase('application', 'octet-stream')

    # To change the payload into encoded form
    p.set_payload(attachment.read())
    attachment.close()

    # encode into base64
    encoders.encode_base64(p)

    p.add_header('Content-Disposition', "attachment; filename= %s" %dat)

    # attach the instance 'p' to instance 'mail'
    mail.attach(p)

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(fromaddr, "-password-")
    text = mail.as_string()
    server.sendmail(fromaddr, toaddr, text)
    server.quit()

def capture_image():
    data= time.strftime("%d_%b_%Y_%H_%M_%S")
    camera.start_preview()
    #time.sleep(5)
    print (data)
    camera.capture('%s.jpg'%data)
    camera.stop_preview()
    #time.sleep(1)
    sendMail(data)
    newest = max(glob.iglob('*.jpg'), key=os.path.getctime)
    bot.sendMessage(chat_id=enter chat id, text="[Intruder Alert] Motion Detected 5 seconds ago!")
    bot.sendPhoto(chat_id=enter chat id, photo=open('/home/pi/Desktop/New/%s'%newest,'rb'), caption="Here's the intruder's picture!")

camera = picamera.PiCamera()
camera.rotation=360
camera.awb_mode= 'auto'
camera.brightness=65

while True:
    time.sleep(1)
    previous_state = current_state
    current_state = gpio.input(pir)
    #print("Current State : %s" % current_state)
    if current_state != previous_state:
        new_state = "ACTIVATED" if current_state else "DEACTIVATED"
        print("SENSOR %s is %s" % (pir, new_state))
        if new_state == "ACTIVATED":
            print("Detected Activity")
            capture_image()

pcmanbob
Posts: 7268
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: How to separate the body of the email in Gmail (like 1 email 1 body)?

Fri Aug 16, 2019 3:50 pm

If you compare my program and your program you don't actually pass the body , to or from email address or subject lines to the sendmail function .

anything that is defined in the main program that you want to use in a function has to be passed to the function when its called.

So in my program you can see I pass the subject,body and email_send variables when I call the function using the line

Code: Select all

send_email(subject,body,email_send)
either that or you need to include all these variables in the function as shown in the example I linked to.

the answer is there which every way you decide to do it you just need to read and compare the examples to your code.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

ghp
Posts: 1420
Joined: Wed Jun 12, 2013 12:41 pm
Location: Stuttgart Germany
Contact: Website

Re: How to separate the body of the email in Gmail (like 1 email 1 body)?

Fri Aug 16, 2019 6:08 pm

Hello, the problem with the growing text could be that the mail object is build in main code once, and in sending the mail some text is attached each time.

Code: Select all

mail = MIMEMultipart()
 
mail['From'] = fromaddr
mail['To'] = toaddr
mail['Subject'] = "[Intruder Alert] Motion Detected!"
body = "Who is the Intruder? Find the attachment for the Intruder's picture!"

def sendMail(data):
    mail.attach(MIMEText(body, 'plain'))
Think that moving the object creation into the sendMail function will result in a fresh object used each time.

Code: Select all


def sendMail(data):
    mail = MIMEMultipart()
 
    mail['From'] = fromaddr
    mail['To'] = toaddr 
    mail['Subject'] = "[Intruder Alert] Motion Detected!"
    body = "Who is the Intruder? Find the attachment for the Intruder's picture!"
    mail.attach(MIMEText(body, 'plain'))

joeboy69
Posts: 7
Joined: Fri May 17, 2019 6:58 pm

Re: How to separate the body of the email in Gmail (like 1 email 1 body)?

Sat Aug 17, 2019 10:25 pm

@pcmanbob ok noted, thank you bro ;)

@ghp great bro, that's working. thank you so much ;)

Return to “Python”