Search code examples
pythonmimemultipart

How to replace body text in MIME message?


I am trying to send an automated email to various users with the lake that they are subscribed to changing:

message = MIMEMultipart()
message['From'] = email  # Sender
message['Subject'] = "Algae Bloom Alert\n"  # Subject

for user in subscriber_dict:
    sms_gateway = subscriber_dict[user]['email']
    message['To'] = subscriber_dict[user]['email']
    body = (
        f"This is an algae alert for Lake {subscriber_dict[user]['lake']}.\n\n"
        f"Sent at {sent_time_date} {sent_time_time}"
    )
    message.attach(MIMEText(body, 'plain'))  # Attaching body to email
    sms = message.as_string()
    server.sendmail(email, sms_gateway, sms)
        
    # Reset body here ideally

    print(f"Email sent at {formatted_time}")

However, when the emails are sent, each successive email contains the contents from the emails prior to it. Does anyone know how I can reset the body so that I am not attaching to the previous bodies but rather writing new ones?


Solution

  • Righto - there's no need to keep digging back into subscriber_dict. Instead of:

    for user in subscriber_dict:
        sms_gateway = subscriber_dict[user]['email']
    

    You can do:

    for user in subscriber_dict.values():
        sms_gateway = user['email']
    

    Your for loop is reusing the same message. It should probably create a new one on each loop:

    FROM_ADDR = "jake@lakefacts.gov.au"
    
    for user in subscriber_dict.values():
        message = MIMEMultipart()
        message['From'] = FROM_ADDR
        message['To'] = user['email']
        message['Subject'] = "Algae Bloom Alert\n"
        body = (
            f"This is an algae alert for Lake {user['lake']}.\n\n"
            f"Sent at {sent_time_date} {sent_time_time}"
        )
        message.attach(MIMEText(body, 'plain'))
        sms_gateway = user['email']
        sms = message.as_string()
        server.sendmail(email, sms_gateway, sms)
        print(f"Email sent at {formatted_time}")