Search code examples
pythonemailpyserialsmtplib

Python - using smtplib to send to multiple recipients


I'm finding it very difficult to modify this code to send to send to multiple recipients, I have tried many variations of the examples already out there. I'm very new to python so any help would be much appreciated.

It is as part of safety system I am designing to alert parents and carers of potential elopement risk for children and adults with ASD.

'''
import time
import serial
import smtplib

TO = 'email@mail.org'
GMAIL_USER = 'email@gmail.com'
GMAIL_PASS = 'passowrd'

SUBJECT = 'Security Alert'
TEXT = 'Movement detected!'

ser = serial.Serial('COM6', 9600)

def send_email():
print("Sending Email")
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(GMAIL_USER, GMAIL_PASS)
header = 'To:' + TO + '\n' + 'From: ' + GMAIL_USER
header = header + '\n' + 'Subject:' + SUBJECT + '\n'
print header
msg = header + '\n' + TEXT + ' \n\n'
smtpserver.sendmail(GMAIL_USER, TO, msg)
smtpserver.close()

while True:
    message = ser.readline()
    print(message)
    if message[0] == 'M' :
        send_email()
    time.sleep(0.5)

'''

Send the alert to multiple people.


Solution

  • Have you had a look at this yet? How to send email to multiple recipients using python smtplib?

    It looks like you might be dropping some of the pieces of your header too by overwriting them:

    header = 'From: ' + GMAIL_USER
    

    Instead of:

    header = header + 'From: ' + GMAIL_USER
    

    You might also want to consider using format instead, but I'm already out of my depth on Python :-)